def generateMatrix(n): matrix = [[0 for _ in xrange(n)] for _ in xrange(n)] for (x, y), v in izip(spiral(True, 0, 0, n, n), count(1)): matrix[y][x] = v return matrix
def maxProfit(prices): profit = 0 for previous, current in izip(prices[:-1],prices[1:]): if current > previous: profit += current - previous return profit
def maxProfit(prices): profit = 0 for previous, current in izip(prices[:-1], prices[1:]): if current > previous: profit += current - previous return profit
def pow(x, n): r = 1.0 if n < 0: x = 1.0/x n = -n for a, b in izip(square(x), int2digits(n, 2)): if b: r *= a return r
def convert(s, nRows): if nRows == 1: return s n = nRows * 2 - 2 s += ' ' * (n - len(s) % n) l = [s[i::n] for i in xrange(n)] r = l[0] for i in xrange(1, nRows - 1): r += "".join(a + b for a, b in izip(l[i], l[n - i])) r += l[nRows - 1] return "".join(r.split(" "))
def convert(s, nRows): if nRows == 1: return s n = nRows * 2 - 2 s += ' ' * (n - len(s) % n) l = [s[i::n] for i in xrange(n)] r = l[0] for i in xrange(1, nRows-1): r += "".join(a+b for a,b in izip(l[i], l[n-i])) r += l[nRows-1] return "".join(r.split(" "))
def canCompleteCircuit(gas, cost): change = [(g-c) for g, c in izip(gas, cost)] total = 0 stops = len(change) l, r = 0, 0 while True: while True: total += change[r] r = (r + 1) % stops if total < 0: break if l == r: return l while total < 0: total -= change[l] l += 1 if l == stops: return -1
def connect(root): for level in iter_level([root]): for a, b in izip(level, level[1:] + [None]): a.next = b
def zigzagLevelOrder(root): return [[node.val for node in v[::s]] for v, s in izip(iter_level([root]), zigzag())]
def longestCommonPrefix(strs): return "".join(c[0] for c in takewhile(lambda x: len(set(x))==1, izip(*strs)))