desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
':type t1: TreeNode :type t2: TreeNode :rtype: TreeNode'
def mergeTrees(self, t1, t2):
if (t1 is None): return t2 if (t2 is None): return t1 t1.val += t2.val t1.left = self.mergeTrees(t1.left, t2.left) t1.right = self.mergeTrees(t1.right, t2.right) return t1
':type n: int :rtype: int'
def minSteps(self, n):
result = 0 p = 2 while ((p ** 2) <= n): while ((n % p) == 0): result += p n //= p p += 1 if (n > 1): result += n return result
':type n: int :rtype: int'
def lastRemaining(self, n):
(start, step, direction) = (1, 2, 1) while (n > 1): start += (direction * ((step * (n / 2)) - (step / 2))) n /= 2 step *= 2 direction *= (-1) return start
':type numRows: int :rtype: List[List[int]]'
def generate3(self, numRows):
if (numRows == 0): return [] if (numRows == 1): return [[1]] res = [[1], [1, 1]] def add(nums): res = nums[:1] for (i, j) in enumerate(nums): if (i < (len(nums) - 1)): res += [(nums[i] + nums[(i + 1)])] res += nums[:1] return re...
':type s: str :rtype: str'
def reverseString(self, s):
string = list(s) (i, j) = (0, (len(string) - 1)) while (i < j): (string[i], string[j]) = (string[j], string[i]) i += 1 j -= 1 return ''.join(string)
':type s: str :rtype: str'
def reverseString(self, s):
return s[::(-1)]
':type rowIndex: int :rtype: List[int]'
def getRow2(self, rowIndex):
row = [1] for _ in range(rowIndex): row = [(x + y) for (x, y) in zip(([0] + row), (row + [0]))] return row
':type rowIndex: int :rtype: List[int]'
def getRow3(self, rowIndex):
if (rowIndex == 0): return [1] res = [1, 1] def add(nums): res = nums[:1] for (i, j) in enumerate(nums): if (i < (len(nums) - 1)): res += [(nums[i] + nums[(i + 1)])] res += nums[:1] return res while (res[1] < rowIndex): res = ad...
':type prices: List[int] :rtype: int'
def maxProfit(self, prices):
if (not prices): return 0 (buy, sell, coolDown) = (([0] * 2), ([0] * 2), ([0] * 2)) buy[0] = (- prices[0]) for i in xrange(1, len(prices)): buy[(i % 2)] = max(buy[((i - 1) % 2)], (coolDown[((i - 1) % 2)] - prices[i])) sell[(i % 2)] = (buy[((i - 1) % 2)] + prices[i]) coolD...
':type num: int :rtype: List[int]'
def countBits(self, num):
res = [0] for i in xrange(1, (num + 1)): res.append(((i & 1) + res[(i >> 1)])) return res
':type num: int :rtype: List[int]'
def countBits2(self, num):
s = [0] while (len(s) <= num): s.extend(map((lambda x: (x + 1)), s)) return s[:(num + 1)]
':type n: int :rtype: int'
def guessNumber(self, n):
(left, right) = (1, n) while (left <= right): mid = (left + ((right - left) / 2)) if (guess(mid) <= 0): right = (mid - 1) else: left = (mid + 1) return left
':type root: TreeNode :type target: float :type k: int :rtype: List[int]'
def closestKValues(self, root, target, k):
def nextNode(stack, child1, child2): if stack: if child2(stack): stack.append(child2(stack)) while child1(stack): stack.append(child1(stack)) else: child = stack.pop() while (stack and (child is child...
':type root: TreeNode :type target: float :type k: int :rtype: List[int]'
def closestKValues(self, root, target, k):
class BSTIterator: def __init__(self, stack, child1, child2): self.stack = list(stack) self.cur = self.stack.pop() self.child1 = child1 self.child2 = child2 def next(self): node = None if (self.cur and self.child1(self.cur)): ...
':type points: List[List[int]] :rtype: bool'
def isReflected(self, points):
if (not points): return True groups_by_y = collections.defaultdict(set) (left, right) = (float('inf'), float('-inf')) for p in points: groups_by_y[p[1]].add(p[0]) (left, right) = (min(left, p[0]), max(right, p[0])) mid = (left + right) for group in groups_by_y.values(): ...
':type points: List[List[int]] :rtype: bool'
def isReflected(self, points):
if (not points): return True points.sort() points[(len(points) / 2):] = sorted(points[(len(points) / 2):], (lambda x, y: ((y[1] - x[1]) if (x[0] == y[0]) else (x[0] - y[0])))) mid = (points[0][0] + points[(-1)][0]) (left, right) = (0, (len(points) - 1)) while (left <= right): if ...
':type nums: List[int] :type numsSize: int'
def __init__(self, nums):
self.__nums = nums
':type target: int :rtype: int'
def pick(self, target):
reservoir = (-1) n = 0 for i in xrange(len(self.__nums)): if (self.__nums[i] != target): continue reservoir = (i if ((n == 0) or (randint(1, (n + 1)) == 1)) else reservoir) n += 1 return reservoir
':type s: str :rtype: int'
def titleToNumber(self, s):
result = 0 for i in xrange(len(s)): result *= 26 result += ((ord(s[i]) - ord('A')) + 1) return result
':type root: TreeNode :rtype: List[int]'
def inorderTraversal(self, root):
(result, curr) = ([], root) while curr: if (curr.left is None): result.append(curr.val) curr = curr.right else: node = curr.left while (node.right and (node.right != curr)): node = node.right if (node.right is None): ...
':type root: TreeNode :rtype: List[int]'
def inorderTraversal(self, root):
(result, stack) = ([], [(root, False)]) while stack: (root, is_visited) = stack.pop() if (root is None): continue if is_visited: result.append(root.val) else: stack.append((root.right, False)) stack.append((root, True)) ...
':type candies: List[int] :rtype: int'
def distributeCandies(self, candies):
lookup = set() for candy in candies: lookup.add(candy) return min(len(lookup), (len(candies) / 2))
':type tasks: List[str] :type n: int :rtype: int'
def leastInterval(self, tasks, n):
count = collections.defaultdict(int) max_count = 0 for task in tasks: count[task] += 1 max_count = max(max_count, count[task]) result = ((max_count - 1) * (n + 1)) for count in count.values(): if (count == max_count): result += 1 return max(result, len(tasks))...
':type s: str :rtype: str'
def frequencySort(self, s):
freq = collections.defaultdict(int) for c in s: freq[c] += 1 counts = ([''] * (len(s) + 1)) for c in freq: counts[freq[c]] += c result = '' for count in reversed(xrange((len(counts) - 1))): for c in counts[count]: result += (c * count) return result
':type nums: List[int] :rtype: List[int]'
def largestDivisibleSubset(self, nums):
if (not nums): return [] nums.sort() dp = ([1] * len(nums)) prev = ([(-1)] * len(nums)) largest_idx = 0 for i in xrange(len(nums)): for j in xrange(i): if ((nums[i] % nums[j]) == 0): if (dp[i] < (dp[j] + 1)): dp[i] = (dp[j] + 1) ...
':type n: int :rtype: int'
def findCelebrity(self, n):
candidate = 0 for i in xrange(1, n): if knows(candidate, i): candidate = i for i in xrange(n): if ((i != candidate) and (knows(candidate, i) or (not knows(i, candidate)))): return (-1) return candidate
':type s: str :type t: str :rtype: str'
def findTheDifference(self, s, t):
return chr((reduce(operator.xor, map(ord, s), 0) ^ reduce(operator.xor, map(ord, t), 0)))
':type s: str :type t: str :rtype: str'
def findTheDifference2(self, s, t):
t = list(t) s = list(s) for i in s: t.remove(i) return t[0]
':type pattern: str :type str: str :rtype: bool'
def wordPattern(self, pattern, str):
if (len(pattern) != self.wordCount(str)): return False (w2p, p2w) = ({}, {}) for (p, w) in izip(pattern, self.wordGenerator(str)): if ((w not in w2p) and (p not in p2w)): w2p[w] = p p2w[p] = w elif ((w not in w2p) or (w2p[w] != p)): return False ...
':type pattern: str :type str: str :rtype: bool'
def wordPattern(self, pattern, str):
words = str.split() if (len(pattern) != len(words)): return False (w2p, p2w) = ({}, {}) for (p, w) in izip(pattern, words): if ((w not in w2p) and (p not in p2w)): w2p[w] = p p2w[p] = w elif ((w not in w2p) or (w2p[w] != p)): return False r...
':type c: int :rtype: bool'
def judgeSquareSum(self, c):
for a in xrange((int(math.sqrt(c)) + 1)): b = int(math.sqrt((c - (a ** 2)))) if (((a ** 2) + (b ** 2)) == c): return True return False
':type dividend: int :type divisor: int :rtype: int'
def divide(self, dividend, divisor):
(result, dvd, dvs) = (0, abs(dividend), abs(divisor)) while (dvd >= dvs): inc = dvs i = 0 while (dvd >= inc): dvd -= inc result += (1 << i) inc <<= 1 i += 1 if (((dividend > 0) and (divisor < 0)) or ((dividend < 0) and (divisor > 0))): ...
':type dividend: int :type divisor: int :rtype: int'
def divide2(self, dividend, divisor):
positive = ((dividend < 0) is (divisor < 0)) (dividend, divisor) = (abs(dividend), abs(divisor)) res = 0 while (dividend >= divisor): (temp, i) = (divisor, 1) while (dividend >= temp): dividend -= temp res += i i <<= 1 temp <<= 1 if (no...
':type root: TreeNode :rtype: int'
def findBottomLeftValue(self, root):
def findBottomLeftValueHelper(root, curr_depth, max_depth, bottom_left_value): if (not root): return (max_depth, bottom_left_value) if ((not root.left) and (not root.right) and ((curr_depth + 1) > max_depth)): return ((curr_depth + 1), root.val) (max_depth, bottom_lef...
':type root: TreeNode :rtype: int'
def findBottomLeftValue(self, root):
queue = [root] for node in queue: queue += filter(None, (node.right, node.left)) return node.val
':type s: str :type t: str :rtype: str'
def minWindow(self, s, t):
current_count = [0 for i in xrange(52)] expected_count = [0 for i in xrange(52)] for char in t: expected_count[(ord(char) - ord('a'))] += 1 (i, count, start, min_width, min_start) = (0, 0, 0, float('inf'), 0) while (i < len(s)): current_count[(ord(s[i]) - ord('a'))] += 1 if (...
':type s: str :type dict: List[str] :rtype: str'
def addBoldTag(self, s, dict):
bold = ([0] * len(s)) for d in dict: pos = s.find(d) while (pos != (-1)): bold[pos:(pos + len(d))] = ([1] * len(d)) pos = s.find(d, (pos + 1)) (result, prev) = ([], 0) for i in xrange(len(s)): if (prev != bold[i]): result += ('</b>' if prev els...
':type equations: List[List[str]] :type values: List[float] :type query: List[List[str]] :rtype: List[float]'
def calcEquation(self, equations, values, query):
def check(up, down, lookup, visited): if ((up in lookup) and (down in lookup[up])): return (True, lookup[up][down]) for (k, v) in lookup[up].iteritems(): if (k not in visited): visited.add(k) tmp = check(k, down, lookup, visited) ...
'Initialize your data structure here. :type size: int'
def __init__(self, size):
self.__size = size self.__sum = 0 self.__q = deque([])
':type val: int :rtype: float'
def next(self, val):
if (len(self.__q) == self.__size): self.__sum -= self.__q.popleft() self.__sum += val self.__q.append(val) return ((1.0 * self.__sum) / len(self.__q))
':type s: str :rtype: List[str]'
def findRepeatedDnaSequences2(self, s):
(l, r) = ([], []) if (len(s) < 10): return [] for i in range((len(s) - 9)): l.extend([s[i:(i + 10)]]) return [k for (k, v) in collections.Counter(l).items() if (v > 1)]
':type nums: List[int] :type lower: int :type upper: int :rtype: List[str]'
def findMissingRanges(self, nums, lower, upper):
def getRange(lower, upper): if (lower == upper): return '{}'.format(lower) else: return '{}->{}'.format(lower, upper) ranges = [] pre = (lower - 1) for i in xrange((len(nums) + 1)): if (i == len(nums)): cur = (upper + 1) else: ...
'initialize your data structure here'
def __init__(self):
self.lookup = defaultdict(int)
'Add the number to an internal data structure. :rtype: nothing'
def add(self, number):
self.lookup[number] += 1
'Find if there exists any pair of numbers which sum is equal to the value. :type value: int :rtype: bool'
def find(self, value):
for key in self.lookup: num = (value - key) if ((num in self.lookup) and ((num != key) or (self.lookup[key] > 1))): return True return False
':type l1: ListNode :type l2: ListNode :rtype: ListNode'
def addTwoNumbers(self, l1, l2):
(stk1, stk2) = ([], []) while l1: stk1.append(l1.val) l1 = l1.next while l2: stk2.append(l2.val) l2 = l2.next (prev, head) = (None, None) sum = 0 while (stk1 or stk2): sum /= 10 if stk1: sum += stk1.pop() if stk2: su...
':type grid: List[List[int]] :rtype: int'
def minTotalDistance(self, grid):
x = [i for (i, row) in enumerate(grid) for v in row if (v == 1)] y = [j for row in grid for (j, v) in enumerate(row) if (v == 1)] mid_x = self.findKthLargest(x, ((len(x) / 2) + 1)) mid_y = self.findKthLargest(y, ((len(y) / 2) + 1)) return sum([(abs((mid_x - i)) + abs((mid_y - j))) for (i, row) in en...
':type nums: List[int] :rtype: List[List[int]]'
def findSubsequences(self, nums):
def findSubsequencesHelper(nums, pos, seq, result): if (len(seq) >= 2): result.append(list(seq)) lookup = set() for i in xrange(pos, len(nums)): if (((not seq) or (nums[i] >= seq[(-1)])) and (nums[i] not in lookup)): lookup.add(nums[i]) ...
':type intervals: List[Interval] :rtype: List[int]'
def findRightInterval(self, intervals):
sorted_intervals = sorted(((interval.start, i) for (i, interval) in enumerate(intervals))) result = [] for interval in intervals: idx = bisect.bisect_left(sorted_intervals, (interval.end,)) result.append((sorted_intervals[idx][1] if (idx < len(sorted_intervals)) else (-1))) return result...
':type n: int :rtype: int'
def checkRecord(self, n):
M = 1000000007 (a0l0, a0l1, a0l2, a1l0, a1l1, a1l2) = (1, 0, 0, 0, 0, 0) for i in xrange((n + 1)): (a0l2, a0l1, a0l0) = (a0l1, a0l0, (((a0l0 + a0l1) + a0l2) % M)) (a1l2, a1l1, a1l0) = (a1l1, a1l0, ((((a0l0 + a1l0) + a1l1) + a1l2) % M)) return a1l0
':type points: List[List[int]] :rtype: bool'
def isConvex(self, points):
def det(A): return ((A[0][0] * A[1][1]) - (A[0][1] * A[1][0])) (n, prev, curr) = (len(points), 0, None) for i in xrange(len(points)): A = [[(points[((i + j) % n)][0] - points[i][0]), (points[((i + j) % n)][1] - points[i][1])] for j in (1, 2)] curr = det(A) if curr: ...
':type head: ListNode :rtype: ListNode'
def plusOne(self, head):
if (not head): return None dummy = ListNode(0) dummy.next = head (left, right) = (dummy, head) while right.next: if (right.val != 9): left = right right = right.next if (right.val != 9): right.val += 1 else: left.val += 1 right = le...
':type head: ListNode :rtype: ListNode'
def plusOne(self, head):
def reverseList(head): dummy = ListNode(0) curr = head while curr: (dummy.next, curr.next, curr) = (curr, dummy.next, curr.next) return dummy.next rev_head = reverseList(head) (curr, carry) = (rev_head, 1) while (curr and carry): curr.val += carry ...
':type nums: List[int] :rtype: List[int]'
def findErrorNums(self, nums):
x_xor_y = 0 for i in xrange(len(nums)): x_xor_y ^= (nums[i] ^ (i + 1)) bit = (x_xor_y & (~ (x_xor_y - 1))) result = ([0] * 2) for (i, num) in enumerate(nums): result[bool((num & bit))] ^= num result[bool(((i + 1) & bit))] ^= (i + 1) if (result[0] not in nums): (re...
':type nums: List[int] :rtype: List[int]'
def findErrorNums(self, nums):
result = ([0] * 2) for i in nums: if (nums[(abs(i) - 1)] < 0): result[0] = abs(i) else: nums[(abs(i) - 1)] *= (-1) for i in xrange(len(nums)): if (nums[i] > 0): result[1] = (i + 1) else: nums[i] *= (-1) return result
':type nums: List[int] :rtype: List[int]'
def findErrorNums(self, nums):
N = len(nums) x_minus_y = (sum(nums) - ((N * (N + 1)) // 2)) x_plus_y = ((sum(((x * x) for x in nums)) - (((N * (N + 1)) * ((2 * N) + 1)) / 6)) // x_minus_y) return (((x_plus_y + x_minus_y) // 2), ((x_plus_y - x_minus_y) // 2))
':type nums: List[int] :rtype: int'
def minMoves(self, nums):
return (sum(nums) - (len(nums) * min(nums)))
':type nums: List[int] :rtype: List[int]'
def singleNumber(self, nums):
return [x[0] for x in sorted(collections.Counter(nums).items(), key=(lambda i: i[1]), reverse=False)[:2]]
':type num1: str :type num2: str :rtype: str'
def multiply(self, num1, num2):
(num1, num2) = (num1[::(-1)], num2[::(-1)]) res = ([0] * (len(num1) + len(num2))) for i in xrange(len(num1)): for j in xrange(len(num2)): res[(i + j)] += (int(num1[i]) * int(num2[j])) res[((i + j) + 1)] += (res[(i + j)] / 10) res[(i + j)] %= 10 i = (len(res) -...
':type num1: str :type num2: str :rtype: str'
def multiply(self, num1, num2):
return str((int(num1) * int(num2)))
':type nums: List[int] :rtype: int'
def arrayPairSum(self, nums):
(LEFT, RIGHT) = ((-10000), 10000) lookup = ([0] * ((RIGHT - LEFT) + 1)) for num in nums: lookup[(num - LEFT)] += 1 (r, result) = (0, 0) for i in xrange(LEFT, (RIGHT + 1)): result += ((((lookup[(i - LEFT)] + 1) - r) / 2) * i) r = ((lookup[(i - LEFT)] + r) % 2) return resul...
':type nums: List[int] :rtype: int'
def arrayPairSum(self, nums):
nums.sort() result = 0 for i in xrange(0, len(nums), 2): result += nums[i] return result
':type s: str :rtype: List[str]'
def generatePossibleNextMoves(self, s):
res = [] (i, n) = (0, (len(s) - 1)) while (i < n): if (s[i] == '+'): while ((i < n) and (s[(i + 1)] == '+')): res.append(((s[:i] + '--') + s[(i + 2):])) i += 1 i += 1 return res
':type s: str :rtype: List[str]'
def generatePossibleNextMoves(self, s):
return [((s[:i] + '--') + s[(i + 2):]) for i in xrange((len(s) - 1)) if (s[i:(i + 2)] == '++')]
':type houses: List[int] :type heaters: List[int] :rtype: int'
def findRadius(self, houses, heaters):
heaters.sort() min_radius = 0 for house in houses: equal_or_larger = bisect.bisect_left(heaters, house) curr_radius = float('inf') if (equal_or_larger != len(heaters)): curr_radius = (heaters[equal_or_larger] - house) if (equal_or_larger != 0): smaller...
':type nums: List[int] :type S: int :rtype: int'
def findTargetSumWays(self, nums, S):
def subsetSum(nums, S): dp = collections.defaultdict(int) dp[0] = 1 for n in nums: for i in reversed(xrange(n, (S + 1))): if ((i - n) in dp): dp[i] += dp[(i - n)] return dp[S] total = sum(nums) if ((total < S) or ((S + total) % ...
':type nums: List[int] :type k: int :rtype: int'
def subarraySum(self, nums, k):
result = 0 accumulated_sum = 0 lookup = collections.defaultdict(int) lookup[0] += 1 for num in nums: accumulated_sum += num result += lookup[(accumulated_sum - k)] lookup[accumulated_sum] += 1 return result
':type nums: List[int] :rtype: int'
def singleNonDuplicate(self, nums):
(left, right) = (0, (len(nums) - 1)) while (left <= right): mid = (left + ((right - left) / 2)) if ((not (((mid % 2) == 0) and ((mid + 1) < len(nums)) and (nums[mid] == nums[(mid + 1)]))) and (not (((mid % 2) == 1) and (nums[mid] == nums[(mid - 1)])))): right = (mid - 1) else...
':type root: TreeNode :rtype: List[int]'
def postorderTraversal(self, root):
dummy = TreeNode(0) dummy.left = root (result, cur) = ([], dummy) while cur: if (cur.left is None): cur = cur.right else: node = cur.left while (node.right and (node.right != cur)): node = node.right if (node.right is None):...
':type root: TreeNode :rtype: List[int]'
def postorderTraversal(self, root):
(result, stack) = ([], [(root, False)]) while stack: (root, is_visited) = stack.pop() if (root is None): continue if is_visited: result.append(root.val) else: stack.append((root, True)) stack.append((root.right, False)) ...
':type x: float :type n: int :rtype: float'
def myPow(self, x, n):
result = 1 abs_n = abs(n) while abs_n: if (abs_n & 1): result *= x abs_n >>= 1 x *= x return ((1 / result) if (n < 0) else result)
':type x: float :type n: int :rtype: float'
def myPow(self, x, n):
if ((n < 0) and (n != (- n))): return (1.0 / self.myPow(x, (- n))) if (n == 0): return 1 v = self.myPow(x, (n / 2)) if ((n % 2) == 0): return (v * v) else: return ((v * v) * x)
':type citations: List[int] :rtype: int'
def hIndex(self, citations):
n = len(citations) count = ([0] * (n + 1)) for x in citations: if (x >= n): count[n] += 1 else: count[x] += 1 h = 0 for i in reversed(xrange(0, (n + 1))): h += count[i] if (h >= i): return i return h
':type citations: List[int] :rtype: int'
def hIndex(self, citations):
citations.sort(reverse=True) h = 0 for x in citations: if (x >= (h + 1)): h += 1 else: break return h
':type citations: List[int] :rtype: int'
def hIndex(self, citations):
return sum(((x >= (i + 1)) for (i, x) in enumerate(sorted(citations, reverse=True))))
':type envelopes: List[List[int]] :rtype: int'
def maxEnvelopes(self, envelopes):
def insert(target): (left, right) = (0, (len(result) - 1)) while (left <= right): mid = (left + ((right - left) / 2)) if (result[mid] >= target): right = (mid - 1) else: left = (mid + 1) if (left == len(result)): ...
':type str: str :rtype: int'
def myAtoi(self, str):
INT_MAX = 2147483647 INT_MIN = (-2147483648) result = 0 if (not str): return result i = 0 while ((i < len(str)) and str[i].isspace()): i += 1 sign = 1 if (str[i] == '+'): i += 1 elif (str[i] == '-'): sign = (-1) i += 1 while ((i < len(str))...
'Encodes a tree to a single string. :type root: TreeNode :rtype: str'
def serialize(self, root):
def serializeHelper(node, vals): if node: vals.append(node.val) serializeHelper(node.left, vals) serializeHelper(node.right, vals) vals = [] serializeHelper(root, vals) return ' '.join(map(str, vals))
'Decodes your encoded data to tree. :type data: str :rtype: TreeNode'
def deserialize(self, data):
def deserializeHelper(minVal, maxVal, vals): if (not vals): return None if (minVal < vals[0] < maxVal): val = vals.popleft() node = TreeNode(val) node.left = deserializeHelper(minVal, val, vals) node.right = deserializeHelper(val, maxVal, v...
':type nums: List[int] :rtype: int'
def lengthOfLIS(self, nums):
LIS = [] def insert(target): (left, right) = (0, (len(LIS) - 1)) while (left <= right): mid = (left + ((right - left) / 2)) if (LIS[mid] >= target): right = (mid - 1) else: left = (mid + 1) if (left == len(LIS)): ...
':type nums: List[int] :rtype: int'
def lengthOfLIS(self, nums):
dp = [] for i in xrange(len(nums)): dp.append(1) for j in xrange(i): if (nums[j] < nums[i]): dp[i] = max(dp[i], (dp[j] + 1)) return (max(dp) if dp else 0)
':type rectangles: List[List[int]] :rtype: bool'
def isRectangleCover(self, rectangles):
left = min((rec[0] for rec in rectangles)) bottom = min((rec[1] for rec in rectangles)) right = max((rec[2] for rec in rectangles)) top = max((rec[3] for rec in rectangles)) points = defaultdict(int) for (l, b, r, t) in rectangles: for (p, q) in zip(((l, b), (r, b), (l, t), (r, t)), (1, ...
':type n: int :rtype: str'
def convertToTitle(self, n):
(result, dvd) = ('', n) while dvd: result += chr((((dvd - 1) % 26) + ord('A'))) dvd = ((dvd - 1) / 26) return result[::(-1)]
':type n: int :rtype: int'
def magicalString(self, n):
def gen(): for c in (1, 2, 2): (yield c) for (i, c) in enumerate(gen()): if (i > 1): for _ in xrange(c): (yield ((i % 2) + 1)) return sum(((c & 1) for c in itertools.islice(gen(), n)))
':type picture: List[List[str]] :type N: int :rtype: int'
def findBlackPixel(self, picture, N):
(rows, cols) = (([0] * len(picture)), ([0] * len(picture[0]))) lookup = collections.defaultdict(int) for i in xrange(len(picture)): for j in xrange(len(picture[0])): if (picture[i][j] == 'B'): rows[i] += 1 cols[j] += 1 lookup[tuple(picture[i])] += ...
':type picture: List[List[str]] :type N: int :rtype: int'
def findBlackPixel(self, picture, N):
lookup = collections.Counter(map(tuple, picture)) cols = [col.count('B') for col in zip(*picture)] return sum(((N * zip(row, cols).count(('B', N))) for (row, cnt) in lookup.iteritems() if (cnt == N == row.count('B'))))
':type m: int :type n: int :type ops: List[List[int]] :rtype: int'
def maxCount(self, m, n, ops):
for op in ops: m = min(m, op[0]) n = min(n, op[1]) return (m * n)
':type s: str :type t: str :rtype: bool'
def isIsomorphic(self, s, t):
if (len(s) != len(t)): return False (s2t, t2s) = ({}, {}) for (p, w) in izip(s, t): if ((w not in s2t) and (p not in t2s)): s2t[w] = p t2s[p] = w elif ((w not in s2t) or (s2t[w] != p)): return False return True
':type wall: List[List[int]] :rtype: int'
def leastBricks(self, wall):
widths = collections.defaultdict(int) result = len(wall) for row in wall: width = 0 for i in xrange((len(row) - 1)): width += row[i] widths[width] += 1 result = min(result, (len(wall) - widths[width])) return result
'Initialize your data structure here.'
def __init__(self):
self.__k = 300 self.__dq = deque() self.__count = 0
'Record a hit. @param timestamp - The current timestamp (in seconds granularity). :type timestamp: int :rtype: void'
def hit(self, timestamp):
self.getHits(timestamp) if (self.__dq and (self.__dq[(-1)][0] == timestamp)): self.__dq[(-1)][1] += 1 else: self.__dq.append([timestamp, 1]) self.__count += 1
'Return the number of hits in the past 5 minutes. @param timestamp - The current timestamp (in seconds granularity). :type timestamp: int :rtype: int'
def getHits(self, timestamp):
while (self.__dq and (self.__dq[0][0] <= (timestamp - self.__k))): self.__count -= self.__dq.popleft()[1] return self.__count
':type nums1: List[int] :type nums2: List[int] :rtype: List[int]'
def intersect(self, nums1, nums2):
if (len(nums1) > len(nums2)): return self.intersect(nums2, nums1) lookup = collections.defaultdict(int) for i in nums1: lookup[i] += 1 res = [] for i in nums2: if (lookup[i] > 0): res += (i,) lookup[i] -= 1 return res
':type nums1: List[int] :type nums2: List[int] :rtype: List[int]'
def intersect2(self, nums1, nums2):
c = (collections.Counter(nums1) & collections.Counter(nums2)) intersect = [] for i in c: intersect.extend(([i] * c[i])) return intersect
':type nums1: List[int] :type nums2: List[int] :rtype: List[int]'
def intersect(self, nums1, nums2):
if (len(nums1) > len(nums2)): return self.intersect(nums2, nums1) def binary_search(compare, nums, left, right, target): while (left < right): mid = (left + ((right - left) / 2)) if compare(nums[mid], target): right = mid else: ...
':type nums1: List[int] :type nums2: List[int] :rtype: List[int]'
def intersect(self, nums1, nums2):
(nums1.sort(), nums2.sort()) res = [] (it1, it2) = (0, 0) while ((it1 < len(nums1)) and (it2 < len(nums2))): if (nums1[it1] < nums2[it2]): it1 += 1 elif (nums1[it1] > nums2[it2]): it2 += 1 else: res += (nums1[it1],) it1 += 1 ...
':type nums1: List[int] :type nums2: List[int] :rtype: List[int]'
def intersect(self, nums1, nums2):
(nums1.sort(), nums2.sort()) res = [] (it1, it2) = (0, 0) while ((it1 < len(nums1)) and (it2 < len(nums2))): if (nums1[it1] < nums2[it2]): it1 += 1 elif (nums1[it1] > nums2[it2]): it2 += 1 else: res += (nums1[it1],) it1 += 1 ...
':type nums: List[int] :type target: int :rtype: int'
def search(self, nums, target):
(left, right) = (0, (len(nums) - 1)) while (left <= right): mid = (left + ((right - left) / 2)) if (nums[mid] == target): return True elif (nums[mid] == nums[left]): left += 1 elif (((nums[mid] > nums[left]) and (nums[left] <= target < nums[mid])) or ((num...
':type M: List[List[int]] :rtype: int'
def longestLine(self, M):
if (not M): return 0 result = 0 dp = [[([0] * 4) for _ in xrange(len(M[0]))] for _ in xrange(2)] for i in xrange(len(M)): for j in xrange(len(M[0])): dp[(i % 2)][j][:] = ([0] * 4) if (M[i][j] == 1): dp[(i % 2)][j][0] = ((dp[(i % 2)][(j - 1)][0] + 1...
':type n: int :type k: int :rtype: int'
def kInversePairs(self, n, k):
M = 1000000007 dp = [([0] * (k + 1)) for _ in xrange(2)] dp[0][0] = 1 for i in xrange(1, (n + 1)): dp[(i % 2)] = ([0] * (k + 1)) dp[(i % 2)][0] = 1 for j in xrange(1, (k + 1)): dp[(i % 2)][j] = ((dp[(i % 2)][(j - 1)] + dp[((i - 1) % 2)][j]) % M) if ((j - i...