diff --git a/Python/basic-calculator-ii.py b/Python/basic-calculator-ii.py index 03df2953e..57dca8ff5 100644 --- a/Python/basic-calculator-ii.py +++ b/Python/basic-calculator-ii.py @@ -4,7 +4,8 @@ # Implement a basic calculator to evaluate a simple expression string. # # The expression string contains only non-negative integers, +, -, *, / -# operators and empty spaces . The integer division should truncate toward zero. +# operators and empty spaces . The integer division should truncate toward +# zero. # # You may assume that the given expression is always valid. # @@ -15,6 +16,12 @@ # Note: Do not use the eval built-in library function. # +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution: # @param {string} s # @return {integer} @@ -24,7 +31,7 @@ def calculate(self, s): for i in reversed(xrange(len(s))): if s[i].isdigit(): operand += s[i] - if i == 0 or not s[i-1].isdigit(): + if i == 0 or not s[i-1].isdigit(): operands.append(int(operand[::-1])) operand = "" elif s[i] == ')' or s[i] == '*' or s[i] == '/': diff --git a/Python/basic-calculator-iii.py b/Python/basic-calculator-iii.py index 04568b2cf..43c67b25a 100644 --- a/Python/basic-calculator-iii.py +++ b/Python/basic-calculator-iii.py @@ -6,7 +6,8 @@ # The expression string may contain open ( and closing parentheses ), # the plus + or minus sign -, non-negative integers and empty spaces . # -# The expression string contains only non-negative integers, +, -, *, / operators , +# The expression string contains only non-negative integers, +, -, *, / +# operators , # open ( and closing parentheses ) and empty spaces . # The integer division should truncate toward zero. # @@ -21,6 +22,12 @@ # # Note: Do not use the eval built-in library function. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def calculate(self, s): """ @@ -32,7 +39,7 @@ def calculate(self, s): for i in reversed(xrange(len(s))): if s[i].isdigit(): operand += s[i] - if i == 0 or not s[i-1].isdigit(): + if i == 0 or not s[i-1].isdigit(): operands.append(int(operand[::-1])) operand = "" elif s[i] == ')' or s[i] == '*' or s[i] == '/': @@ -63,4 +70,3 @@ def compute(self, operands, operators): operands.append(left * right) elif op == '/': operands.append(left / right) - diff --git a/Python/basic-calculator-iv.py b/Python/basic-calculator-iv.py index ddb15ab7c..e4238e5da 100644 --- a/Python/basic-calculator-iv.py +++ b/Python/basic-calculator-iv.py @@ -1,4 +1,5 @@ -# Time: +: O(d * t), t is the number of terms, d is the average degree of terms +# Time: +: O(d * t), t is the number of terms, +# d is the average degree of terms # -: O(d * t) # *: O(d * t^2) # eval: O(d * t) @@ -6,10 +7,14 @@ # Space: O(e + d * t), e is the number of evalvars # Given an expression such as expression = "e + 8 - a + 5" and -# an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), -# return a list of tokens representing the simplified expression, such as ["-1*a","14"] -# - An expression alternates chunks and symbols, with a space separating each chunk and symbol. -# - A chunk is either an expression in parentheses, a variable, or a non-negative integer. +# an evaluation map such as {"e": 1} +# (given in terms of evalvars = ["e"] and evalints = [1]), +# return a list of tokens representing the simplified expression, +# such as ["-1*a","14"] +# - An expression alternates chunks and symbols, +# with a space separating each chunk and symbol. +# - A chunk is either an expression in parentheses, a variable, +# or a non-negative integer. # - A variable is a string of lowercase letters (not including digits.) # Note that variables can be multiple letters, and note that variables never # have a leading coefficient or unary operator like "2x" or "-x". @@ -20,15 +25,19 @@ # # The format of the output is as follows: # - For each term of free variables with non-zero coefficient, -# we write the free variables within a term in sorted order lexicographically. +# we write the free variables within a term in sorted order +# lexicographically. # For example, we would never write a term like "b*a*c", only "a*b*c". # - Terms have degree equal to the number of free variables being multiplied, # counting multiplicity. (For example, "a*a*b*c" has degree 4.) # We write the largest degree terms of our answer first, -# breaking ties by lexicographic order ignoring the leading coefficient of the term. -# - The leading coefficient of the term is placed directly to the left with an asterisk separating it -# from the variables (if they exist.) A leading coefficient of 1 is still printed. -# - An example of a well formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] +# breaking ties by lexicographic order ignoring the leading coefficient of +# the term. +# - The leading coefficient of the term is placed directly to the left with an +# asterisk separating it from the variables (if they exist.) +# A leading coefficient of 1 is still printed. +# - An example of a well formatted answer is +# ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] # - Terms (including constant terms) with coefficient 0 are not included. # For example, an expression of "0" has an output of []. # @@ -50,7 +59,8 @@ # Input: expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = [] # Output: ["5*a*b*c"] # -# Input: expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))", +# Input: expression = +# "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))", # evalvars = [], evalints = [] # Output: # ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c", @@ -120,8 +130,9 @@ def eval(self, lookup): return result def to_list(self): - return ["*".join((str(v),) + k) \ - for k, v in sorted(self.items(), key=lambda(k, _): (-len(k), k)) \ + return ["*".join((str(v),) + k) + for k, v in sorted(self.items(), + key=lambda(k, _): (-len(k), k)) if v] diff --git a/Python/basic-calculator.py b/Python/basic-calculator.py index cae7f5527..21cb994d9 100644 --- a/Python/basic-calculator.py +++ b/Python/basic-calculator.py @@ -14,6 +14,12 @@ # "(1+(4+5+2)-3)+(6+8)" = 23 # +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution: # @param {string} s # @return {integer} @@ -23,7 +29,7 @@ def calculate(self, s): for i in reversed(xrange(len(s))): if s[i].isdigit(): operand += s[i] - if i == 0 or not s[i-1].isdigit(): + if i == 0 or not s[i-1].isdigit(): operands.append(int(operand[::-1])) operand = "" elif s[i] == ')' or s[i] == '+' or s[i] == '-': diff --git a/Python/battleships-in-a-board.py b/Python/battleships-in-a-board.py index 7d6c7490b..23ccf5273 100644 --- a/Python/battleships-in-a-board.py +++ b/Python/battleships-in-a-board.py @@ -2,12 +2,14 @@ # Space: O(1) # Given an 2D board, count how many different battleships are in it. -# The battleships are represented with 'X's, empty slots are represented with '.'s. +# The battleships are represented with 'X's, empty slots are represented with +# '.'s. # You may assume the following rules: # # You receive a valid board, made of only battleships or empty slots. # Battleships can only be placed horizontally or vertically. In other words, -# they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), +# they can only be made of the shape 1xN (1 row, N columns) or Nx1 +# (N rows, 1 column), # where N can be of any size. # At least one horizontal or vertical cell separates between two battleships - # there are no adjacent battleships. @@ -21,9 +23,15 @@ # ...X # XXXX # ...X -# This is not a valid board - as battleships will always have a cell separating between them. +# This is not a valid board - as battleships will always have a cell +# separating between them. # Your algorithm should not modify the value of the board. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class Solution(object): def countBattleships(self, board): @@ -37,7 +45,7 @@ def countBattleships(self, board): cnt = 0 for i in xrange(len(board)): for j in xrange(len(board[0])): - cnt += int(board[i][j] == 'X' and \ - (i == 0 or board[i - 1][j] != 'X') and \ - (j == 0 or board[i][j - 1] != 'X')) + cnt += int(board[i][j] == 'X' and + (i == 0 or board[i - 1][j] != 'X') and + (j == 0 or board[i][j - 1] != 'X')) return cnt diff --git a/Python/beautiful-arrangement-ii.py b/Python/beautiful-arrangement-ii.py index e9617beec..8fe260d8e 100644 --- a/Python/beautiful-arrangement-ii.py +++ b/Python/beautiful-arrangement-ii.py @@ -2,28 +2,31 @@ # Space: O(1) # Given two integers n and k, -# you need to construct a list which contains n different positive integers ranging -# from 1 to n and obeys the following requirement: +# you need to construct a list which contains n different positive integers +# ranging from 1 to n and obeys the following requirement: # Suppose this list is [a1, a2, a3, ... , an], -# then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers. +# then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has +# exactly k distinct integers. # # If there are multiple answers, print any of them. # # Example 1: # Input: n = 3, k = 1 # Output: [1, 2, 3] -# Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, -# and the [1, 1] has exactly 1 distinct integer: 1. +# Explanation: The [1, 2, 3] has three different positive integers ranging +# from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1. # # Example 2: # Input: n = 3, k = 2 # Output: [1, 3, 2] -# Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, +# Explanation: The [1, 3, 2] has three different positive integers ranging +# from 1 to 3, # and the [2, 1] has exactly 2 distinct integers: 1 and 2. # # Note: # The n and k are in the range 1 <= k < n <= 10^4. + class Solution(object): def constructArray(self, n, k): """ diff --git a/Python/beautiful-arrangement.py b/Python/beautiful-arrangement.py index 64327bfcd..8110e4b80 100644 --- a/Python/beautiful-arrangement.py +++ b/Python/beautiful-arrangement.py @@ -2,8 +2,10 @@ # Space: O(n) # Suppose you have N integers from 1 to N. -# We define a beautiful arrangement as an array that is constructed by these N numbers successfully -# if one of the following is true for the ith position (1 <= i <= N) in this array: +# We define a beautiful arrangement as an array that is constructed by +# these N numbers successfully +# if one of the following is true for +# the ith position (1 <= i <= N) in this array: # # The number at the ith position is divisible by i. # i is divisible by the number at the ith position. @@ -28,21 +30,27 @@ # Note: # N is a positive integer and will not exceed 15. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def countArrangement(self, N): """ :type N: int :rtype: int """ - def countArrangementHelper(n, arrangement): + def countArrangementHelper(n, arr): if n <= 0: return 1 count = 0 for i in xrange(n): - if arrangement[i] % n == 0 or n % arrangement[i] == 0: - arrangement[i], arrangement[n-1] = arrangement[n-1], arrangement[i] - count += countArrangementHelper(n - 1, arrangement) - arrangement[i], arrangement[n-1] = arrangement[n-1], arrangement[i] + if arr[i] % n == 0 or n % arr[i] == 0: + arr[i], arr[n-1] = arr[n-1], arr[i] + count += countArrangementHelper(n - 1, arr) + arr[i], arr[n-1] = arr[n-1], arr[i] return count return countArrangementHelper(N, range(1, N+1)) diff --git a/Python/best-meeting-point.py b/Python/best-meeting-point.py index ca5554f63..0a3333eaa 100644 --- a/Python/best-meeting-point.py +++ b/Python/best-meeting-point.py @@ -3,6 +3,12 @@ from random import randint +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def minTotalDistance(self, grid): """ @@ -14,14 +20,16 @@ def minTotalDistance(self, grid): 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 enumerate(grid) for j, v in enumerate(row) if v == 1]) + return sum([abs(mid_x-i) + abs(mid_y-j) + for i, row in enumerate(grid) + for j, v in enumerate(row) if v == 1]) def findKthLargest(self, nums, k): left, right = 0, len(nums) - 1 while left <= right: pivot_idx = randint(left, right) - new_pivot_idx = self.PartitionAroundPivot(left, right, pivot_idx, nums) + new_pivot_idx = self.PartitionAroundPivot(left, right, + pivot_idx, nums) if new_pivot_idx == k - 1: return nums[new_pivot_idx] elif new_pivot_idx > k - 1: @@ -35,7 +43,7 @@ def PartitionAroundPivot(self, left, right, pivot_idx, nums): nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx] for i in xrange(left, right): if nums[i] > pivot_value: - nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i] + nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i] new_pivot_idx += 1 nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right] diff --git a/Python/best-time-to-buy-and-sell-stock-ii.py b/Python/best-time-to-buy-and-sell-stock-ii.py index b0d12c7a9..fcd3ee4d1 100644 --- a/Python/best-time-to-buy-and-sell-stock-ii.py +++ b/Python/best-time-to-buy-and-sell-stock-ii.py @@ -10,6 +10,11 @@ # However, you may not engage in multiple transactions at the same time # (ie, you must sell the stock before you buy again). +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class Solution: # @param prices, a list of integer @@ -21,9 +26,5 @@ def maxProfit(self, prices): return profit def maxProfit2(self, prices): - return sum(map(lambda x: max(prices[x + 1] - prices[x], 0), range(len(prices[:-1])))) - - -if __name__ == "__main__": - result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6]) - print result + return sum(map(lambda x: max(prices[x + 1] - prices[x], 0), + xrange(len(prices[:-1])))) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 89109f853..d7e002f73 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -12,9 +12,13 @@ # (ie, you must sell the stock before you buy again). # -# Time: O(n) -# Space: O(1) -class Solution: +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): # @param prices, a list of integer # @return an integer def maxProfit(self, prices): @@ -22,14 +26,15 @@ def maxProfit(self, prices): release1, release2 = 0, 0 for i in prices: release2 = max(release2, hold2 + i) - hold2 = max(hold2, release1 - i) + hold2 = max(hold2, release1 - i) release1 = max(release1, hold1 + i) - hold1 = max(hold1, -i); + hold1 = max(hold1, -i) return release2 + # Time: O(k * n) # Space: O(k) -class Solution2: +class Solution2(object): # @param prices, a list of integer # @return an integer def maxProfit(self, prices): @@ -46,13 +51,15 @@ def maxAtMostKPairsProfit(self, prices, k): return max_sell[k] + # Time: O(n) # Space: O(n) -class Solution3: +class Solution3(object): # @param prices, a list of integer # @return an integer def maxProfit(self, prices): - min_price, max_profit_from_left, max_profits_from_left = float("inf"), 0, [] + min_price, max_profit_from_left, max_profits_from_left = \ + float("inf"), 0, [] for price in prices: min_price = min(min_price, price) max_profit_from_left = max(max_profit_from_left, price - min_price) @@ -61,15 +68,14 @@ def maxProfit(self, prices): max_price, max_profit_from_right, max_profits_from_right = 0, 0, [] for i in reversed(range(len(prices))): max_price = max(max_price, prices[i]) - max_profit_from_right = max(max_profit_from_right, max_price - prices[i]) + max_profit_from_right = max(max_profit_from_right, + max_price - prices[i]) max_profits_from_right.insert(0, max_profit_from_right) max_profit = 0 for i in range(len(prices)): - max_profit = max(max_profit, max_profits_from_left[i] + max_profits_from_right[i]) + max_profit = max(max_profit, + max_profits_from_left[i] + + max_profits_from_right[i]) return max_profit - -if __name__ == "__main__": - result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6]) - print result diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index 2d0071909..e69119480 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -1,15 +1,24 @@ # Time: O(k * n) # Space: O(k) # -# Say you have an array for which the ith element is the price of a given stock on day i. +# Say you have an array for which the ith element is +# the price of a given stock on day i. # -# Design an algorithm to find the maximum profit. You may complete at most k transactions. +# Design an algorithm to find the maximum profit. +# You may complete at most k transactions. # # Note: -# You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). +# You may not engage in multiple transactions at the same time +# (ie, you must sell the stock before you buy again). # -class Solution: +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): # @return an integer as the maximum profit def maxProfit(self, k, prices): if k >= len(prices) / 2: @@ -33,6 +42,3 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) return max_sell[k] - -if __name__ == "__main__": - print Solution().maxAtMostKPairsProfit([1, 2, 3, 4], 2) diff --git a/Python/best-time-to-buy-and-sell-stock-with-cooldown.py b/Python/best-time-to-buy-and-sell-stock-with-cooldown.py index 2e95e742b..23ecb097e 100644 --- a/Python/best-time-to-buy-and-sell-stock-with-cooldown.py +++ b/Python/best-time-to-buy-and-sell-stock-with-cooldown.py @@ -1,7 +1,8 @@ # Time: O(n) # Space: O(1) -# Say you have an array for which the ith element is the price of a given stock on day i. +# Say you have an array for which the ith element is the price of +# a given stock on day i. # # Design an algorithm to find the maximum profit. You may complete as # many transactions as you like (ie, buy one and sell one share of the @@ -18,6 +19,12 @@ # transactions = [buy, sell, cooldown, buy, sell] # +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def maxProfit(self, prices): """ @@ -30,9 +37,11 @@ def maxProfit(self, prices): buy[0] = -prices[0] for i in xrange(1, len(prices)): # Bought before or buy today. - buy[i % 2] = max(buy[(i - 1) % 2], coolDown[(i - 1) % 2] - prices[i]) + buy[i % 2] = max(buy[(i - 1) % 2], + coolDown[(i - 1) % 2] - prices[i]) # Sell today. sell[i % 2] = buy[(i - 1) % 2] + prices[i] # Sold before yesterday or sold yesterday. coolDown[i % 2] = max(coolDown[(i - 1) % 2], sell[(i - 1) % 2]) - return max(coolDown[(len(prices) - 1) % 2], sell[(len(prices) - 1) % 2]) + return max(coolDown[(len(prices) - 1) % 2], + sell[(len(prices) - 1) % 2]) diff --git a/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py b/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py index 4b622e833..e97c4038f 100644 --- a/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py +++ b/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py @@ -27,6 +27,12 @@ # - 0 < prices[i] < 50000. # - 0 <= fee < 50000. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def maxProfit(self, prices, fee): """ @@ -39,4 +45,3 @@ def maxProfit(self, prices, fee): cash = max(cash, hold+prices[i]-fee) hold = max(hold, cash-prices[i]) return cash - diff --git a/Python/best-time-to-buy-and-sell-stock.py b/Python/best-time-to-buy-and-sell-stock.py index 748b5e638..4d94fa9ae 100644 --- a/Python/best-time-to-buy-and-sell-stock.py +++ b/Python/best-time-to-buy-and-sell-stock.py @@ -9,7 +9,8 @@ # design an algorithm to find the maximum profit. # -class Solution: + +class Solution(object): # @param prices, a list of integer # @return an integer def maxProfit(self, prices): @@ -18,8 +19,3 @@ def maxProfit(self, prices): min_price = min(min_price, price) max_profit = max(max_profit, price - min_price) return max_profit - -if __name__ == "__main__": - result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6]) - print result - diff --git a/Python/binary-number-with-alternating-bits.py b/Python/binary-number-with-alternating-bits.py index e8f06d5b9..cf9d838ed 100644 --- a/Python/binary-number-with-alternating-bits.py +++ b/Python/binary-number-with-alternating-bits.py @@ -28,6 +28,7 @@ # Explanation: # The binary representation of 10 is: 1010. + class Solution(object): def hasAlternatingBits(self, n): """ @@ -36,6 +37,7 @@ def hasAlternatingBits(self, n): """ n, curr = divmod(n, 2) while n > 0: - if curr == n % 2: return False + if curr == n % 2: + return False n, curr = divmod(n, 2) return True diff --git a/Python/binary-search-tree-iterator.py b/Python/binary-search-tree-iterator.py index ae455dea3..525ec44fe 100644 --- a/Python/binary-search-tree-iterator.py +++ b/Python/binary-search-tree-iterator.py @@ -10,14 +10,16 @@ # and uses O(h) memory, where h is the height of the tree. # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class BSTIterator: + +class BSTIterator(object): # @param root, a binary search tree's root node def __init__(self, root): self.stack = [] @@ -38,13 +40,3 @@ def next(self): self.cur = self.cur.right return node.val - -if __name__ == "__main__": - root = TreeNode(2) - root.left = TreeNode(1) - - # Your BSTIterator will be called like this: - i, v = BSTIterator(root), [] - while i.hasNext(): v.append(i.next()) - - print v diff --git a/Python/binary-tree-inorder-traversal.py b/Python/binary-tree-inorder-traversal.py index b82319cfe..05f925fb8 100644 --- a/Python/binary-tree-inorder-traversal.py +++ b/Python/binary-tree-inorder-traversal.py @@ -15,8 +15,9 @@ # Note: Recursive solution is trivial, could you do it iteratively? # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None @@ -72,11 +73,3 @@ def inorderTraversal(self, root): stack.append((root, True)) stack.append((root.left, False)) return result - - -if __name__ == "__main__": - root = TreeNode(1) - root.right = TreeNode(2) - root.right.left = TreeNode(3) - result = Solution().inorderTraversal(root) - print result diff --git a/Python/binary-tree-level-order-traversal-ii.py b/Python/binary-tree-level-order-traversal-ii.py index 0973c82e2..4989e83f8 100644 --- a/Python/binary-tree-level-order-traversal-ii.py +++ b/Python/binary-tree-level-order-traversal-ii.py @@ -1,7 +1,8 @@ # Time: O(n) # Space: O(n) -# Given a binary tree, return the bottom-up level order traversal of its nodes' values. +# Given a binary tree, return the bottom-up level order traversal +# of its nodes' values. # (ie, from left to right, level by level from leaf to root). # # For example: @@ -18,6 +19,7 @@ # [3] # ] + # Definition for a binary tree node class TreeNode(object): def __init__(self, x): @@ -48,13 +50,3 @@ def levelOrderBottom(self, root): result.append(vals) return result[::-1] - - -if __name__ == "__main__": - root = TreeNode(3) - root.left = TreeNode(9) - root.right = TreeNode(20) - root.right.left = TreeNode(15) - root.right.right = TreeNode(7) - result = Solution().levelOrderBottom(root) - print result diff --git a/Python/binary-tree-level-order-traversal.py b/Python/binary-tree-level-order-traversal.py index 8e48c8372..218219e60 100644 --- a/Python/binary-tree-level-order-traversal.py +++ b/Python/binary-tree-level-order-traversal.py @@ -18,14 +18,17 @@ # [15,7] # ] # + + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: + +class Solution(object): # @param root, a tree node # @return a list of lists of integers def levelOrder(self, root): @@ -43,12 +46,3 @@ def levelOrder(self, root): current = next_level result.append(vals) return result - -if __name__ == "__main__": - root = TreeNode(3) - root.left = TreeNode(9) - root.right = TreeNode(20) - root.right.left = TreeNode(15) - root.right.right = TreeNode(7) - result = Solution().levelOrder(root) - print result \ No newline at end of file diff --git a/Python/binary-tree-longest-consecutive-sequence-ii.py b/Python/binary-tree-longest-consecutive-sequence-ii.py index b7c0f7bec..d1c9b3018 100644 --- a/Python/binary-tree-longest-consecutive-sequence-ii.py +++ b/Python/binary-tree-longest-consecutive-sequence-ii.py @@ -8,6 +8,7 @@ # self.left = None # self.right = None + class Solution(object): def longestConsecutive(self, root): """ @@ -36,4 +37,3 @@ def longestConsecutiveHelper(root): self.max_len = 0 longestConsecutiveHelper(root) return self.max_len - diff --git a/Python/binary-tree-longest-consecutive-sequence.py b/Python/binary-tree-longest-consecutive-sequence.py index e9c6c7444..aa75421c2 100644 --- a/Python/binary-tree-longest-consecutive-sequence.py +++ b/Python/binary-tree-longest-consecutive-sequence.py @@ -8,6 +8,7 @@ # self.left = None # self.right = None + class Solution(object): def longestConsecutive(self, root): """ @@ -25,7 +26,7 @@ def longestConsecutiveHelper(root): cur_len = 1 if root.left and root.left.val == root.val + 1: - cur_len = max(cur_len, left_len + 1); + cur_len = max(cur_len, left_len + 1) if root.right and root.right.val == root.val + 1: cur_len = max(cur_len, right_len + 1) diff --git a/Python/binary-tree-maximum-path-sum.py b/Python/binary-tree-maximum-path-sum.py index b3d25e94a..0c3089e4e 100644 --- a/Python/binary-tree-maximum-path-sum.py +++ b/Python/binary-tree-maximum-path-sum.py @@ -13,15 +13,19 @@ # 2 3 # Return 6. # + + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: + +class Solution(object): maxSum = float("-inf") + # @param root, a tree node # @return an integer def maxPathSum(self, root): @@ -35,10 +39,3 @@ def maxPathSumRecu(self, root): right = max(0, self.maxPathSumRecu(root.right)) self.maxSum = max(self.maxSum, root.val + left + right) return root.val + max(left, right) - -if __name__ == "__main__": - root = TreeNode(1) - root.left = TreeNode(2) - root.right = TreeNode(3) - result = Solution().maxPathSum(root) - print result diff --git a/Python/binary-tree-paths.py b/Python/binary-tree-paths.py index 770adfdfb..b32775adc 100644 --- a/Python/binary-tree-paths.py +++ b/Python/binary-tree-paths.py @@ -22,7 +22,8 @@ # self.left = None # self.right = None -class Solution: + +class Solution(object): # @param {TreeNode} root # @return {string[]} def binaryTreePaths(self, root): diff --git a/Python/binary-tree-postorder-traversal.py b/Python/binary-tree-postorder-traversal.py index e0ae110cd..6984e8692 100644 --- a/Python/binary-tree-postorder-traversal.py +++ b/Python/binary-tree-postorder-traversal.py @@ -15,8 +15,9 @@ # Note: Recursive solution is trivial, could you do it iteratively? # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None @@ -82,11 +83,3 @@ def postorderTraversal(self, root): stack.append((root.right, False)) stack.append((root.left, False)) return result - - -if __name__ == "__main__": - root = TreeNode(1) - root.right = TreeNode(2) - root.right.left = TreeNode(3) - result = Solution().postorderTraversal(root) - print result diff --git a/Python/binary-tree-preorder-traversal.py b/Python/binary-tree-preorder-traversal.py index 9cf12ee7a..ed1edbfe1 100644 --- a/Python/binary-tree-preorder-traversal.py +++ b/Python/binary-tree-preorder-traversal.py @@ -15,8 +15,9 @@ # Note: Recursive solution is trivial, could you do it iteratively? # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None @@ -72,11 +73,3 @@ def preorderTraversal(self, root): stack.append((root.left, False)) stack.append((root, True)) return result - - -if __name__ == "__main__": - root = TreeNode(1) - root.right = TreeNode(2) - root.right.left = TreeNode(3) - result = Solution().preorderTraversal(root) - print result diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py index effd0ad13..24e427261 100644 --- a/Python/binary-tree-right-side-view.py +++ b/Python/binary-tree-right-side-view.py @@ -14,14 +14,16 @@ # You should return [1, 3, 4]. # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: + +class Solution(object): # @param root, a tree node # @return a list of integers def rightSideView(self, root): @@ -39,10 +41,11 @@ def rightSideViewDFS(self, node, depth, result): self.rightSideViewDFS(node.right, depth+1, result) self.rightSideViewDFS(node.left, depth+1, result) + # BFS solution # Time: O(n) # Space: O(n) -class Solution2: +class Solution2(object): # @param root, a tree node # @return a list of integers def rightSideView(self, root): @@ -62,12 +65,3 @@ def rightSideView(self, root): current = next_level return result - -if __name__ == "__main__": - root = TreeNode(1) - root.left = TreeNode(2) - root.right = TreeNode(3) - root.left.right = TreeNode(5) - root.right.right = TreeNode(4) - result = Solution().rightSideView(root) - print result diff --git a/Python/binary-tree-tilt.py b/Python/binary-tree-tilt.py index 76ca7e745..4b7de9125 100644 --- a/Python/binary-tree-tilt.py +++ b/Python/binary-tree-tilt.py @@ -22,7 +22,8 @@ # Tilt of binary tree : 0 + 0 + 1 = 1 # Note: # -# The sum of node values in any subtree won't exceed the range of 32-bit integer. +# The sum of node values in any subtree won't exceed +# the range of 32-bit integer. # Definition for a binary tree node. diff --git a/Python/binary-tree-upside-down.py b/Python/binary-tree-upside-down.py index e68f4e923..9f58a714c 100644 --- a/Python/binary-tree-upside-down.py +++ b/Python/binary-tree-upside-down.py @@ -1,9 +1,11 @@ # Time: O(n) # Space: O(1) # -# Given a binary tree where all the right nodes are either leaf nodes with a sibling -# (a left node that shares the same parent node) or empty, flip it upside down and -# turn it into a tree where the original right nodes turned into left leaf nodes. +# Given a binary tree where all the right nodes are +# either leaf nodes with a sibling +# (a left node that shares the same parent node) or empty, +# flip it upside down and turn it into a tree +# where the original right nodes turned into left leaf nodes. # Return the new root. # # For example: @@ -24,14 +26,16 @@ # 3 1 # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: + +class Solution(object): # @param root, a tree node # @return root of the upside down tree def upsideDownBinaryTree(self, root): @@ -47,9 +51,10 @@ def upsideDownBinaryTree(self, root): return parent + # Time: O(n) # Space: O(n) -class Solution2: +class Solution2(object): # @param root, a tree node # @return root of the upside down tree def upsideDownBinaryTree(self, root): @@ -66,4 +71,4 @@ def upsideDownBinaryTreeRecu(self, p, parent): p.left = None p.right = parent - return root \ No newline at end of file + return root diff --git a/Python/binary-tree-vertical-order-traversal.py b/Python/binary-tree-vertical-order-traversal.py index 6790d59fd..b57e04b99 100644 --- a/Python/binary-tree-vertical-order-traversal.py +++ b/Python/binary-tree-vertical-order-traversal.py @@ -10,6 +10,11 @@ import collections +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + # BFS + hash solution. class Solution(object): @@ -24,5 +29,5 @@ def verticalOrder(self, root): if node: cols[i].append(node.val) queue += (node.left, i - 1), (node.right, i + 1) - return [cols[i] for i in xrange(min(cols.keys()), max(cols.keys()) + 1)] \ - if cols else [] + return [cols[i] for i in xrange(min(cols.keys()), + max(cols.keys()) + 1)] if cols else [] diff --git a/Python/binary-tree-zigzag-level-order-traversal.py b/Python/binary-tree-zigzag-level-order-traversal.py index 1a5dac583..2b2261a33 100644 --- a/Python/binary-tree-zigzag-level-order-traversal.py +++ b/Python/binary-tree-zigzag-level-order-traversal.py @@ -1,7 +1,9 @@ # Time: O(n) # Space: O(n) # -# Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). +# Given a binary tree, return the zigzag level order traversal of +# its nodes' values. (ie, from left to right, then right to left +# for the next level and alternate between). # # For example: # Given binary tree {3,9,20,#,#,15,7}, @@ -17,14 +19,17 @@ # [15,7] # ] # + + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: + +class Solution(object): # @param root, a tree node # @return a list of lists of integers def zigzagLevelOrder(self, root): @@ -46,12 +51,3 @@ def zigzagLevelOrder(self, root): level += 1 current = next_level return result - -if __name__ == "__main__": - root = TreeNode(3) - root.left = TreeNode(9) - root.right = TreeNode(20) - root.right.left = TreeNode(15) - root.right.right = TreeNode(7) - result = Solution().zigzagLevelOrder(root) - print result \ No newline at end of file diff --git a/Python/binary-watch.py b/Python/binary-watch.py index eab47e94b..fa988a86e 100644 --- a/Python/binary-watch.py +++ b/Python/binary-watch.py @@ -4,20 +4,29 @@ # A binary watch has 4 LEDs on the top which represent the hours (0-11), # and the 6 LEDs on the bottom represent the minutes (0-59). # -# Each LED represents a zero or one, with the least significant bit on the right. +# Each LED represents a zero or one, with the least significant bit +# on the right. # # For example, the above binary watch reads "3:25". # -# Given a non-negative integer n which represents the number of LEDs that are currently on, +# Given a non-negative integer n which represents the number of LEDs +# that are currently on, # return all possible times the watch could represent. # # Example: # # Input: n = 1 -# Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] +# Return: ["1:00", "2:00", "4:00", "8:00", "0:01", +# "0:02", "0:04", "0:08", "0:16", "0:32"] # Note: # The order of output does not matter. -# The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". +# The hour must not contain a leading zero, for example "01:00" is not valid, +# it should be "1:00". + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 class Solution(object): @@ -33,13 +42,14 @@ def bit_count(bits): count += 1 return count - return ['%d:%02d' % (h, m) - for h in xrange(12) for m in xrange(60) - if bit_count(h) + bit_count(m) == num] + return ['%d:%02d' % (h, m) for h in xrange(12) for m in xrange(60) + if bit_count(h) + bit_count(m) == num] def readBinaryWatch2(self, num): """ :type num: int :rtype: List[str] """ - return ['{0}:{1}'.format(str(h), str(m).zfill(2)) for h in range(12) for m in range(60) if (bin(h) + bin(m)).count('1') == num] + return ['{0}:{1}'.format(str(h), str(m).zfill(2)) + for h in range(12) for m in range(60) + if (bin(h) + bin(m)).count('1') == num] diff --git a/Python/bitwise-and-of-numbers-range.py b/Python/bitwise-and-of-numbers-range.py index 0dc2cad71..418018793 100644 --- a/Python/bitwise-and-of-numbers-range.py +++ b/Python/bitwise-and-of-numbers-range.py @@ -7,7 +7,8 @@ # For example, given the range [5, 7], you should return 4. # -class Solution: + +class Solution(object): # @param m, an integer # @param n, an integer # @return an integer @@ -16,7 +17,8 @@ def rangeBitwiseAnd(self, m, n): n &= n - 1 return n -class Solution2: + +class Solution2(object): # @param m, an integer # @param n, an integer # @return an integer @@ -25,7 +27,4 @@ def rangeBitwiseAnd(self, m, n): while diff: diff >>= 1 i += 1 - return n&m >> i << i - -if __name__ == '__main__': - print Solution().rangeBitwiseAnd(5, 7) + return n & m >> i << i diff --git a/Python/bold-words-in-string.py b/Python/bold-words-in-string.py index 0f794f228..7e08e8a84 100644 --- a/Python/bold-words-in-string.py +++ b/Python/bold-words-in-string.py @@ -2,6 +2,12 @@ # Space: O(t) , t is the size of trie import collections +import functools + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 class Solution(object): @@ -14,7 +20,7 @@ def boldWords(self, words, S): _trie = lambda: collections.defaultdict(_trie) trie = _trie() for i, word in enumerate(words): - reduce(dict.__getitem__, word, trie).setdefault("_end") + functools.reduce(dict.__getitem__, word, trie).setdefault("_end") lookup = [False] * len(S) for i in xrange(len(S)): @@ -35,7 +41,7 @@ def boldWords(self, words, S): result.append("") result.append(S[i]) if lookup[i] and (i == len(S)-1 or not lookup[i+1]): - result.append(""); + result.append("") return "".join(result) @@ -61,5 +67,5 @@ def boldWords(self, words, S): result.append("") result.append(S[i]) if lookup[i] and (i == len(S)-1 or not lookup[i+1]): - result.append(""); + result.append("") return "".join(result) diff --git a/Python/bomb-enemy.py b/Python/bomb-enemy.py index 7da26b0b3..576085c87 100644 --- a/Python/bomb-enemy.py +++ b/Python/bomb-enemy.py @@ -1,6 +1,12 @@ # Time: O(m * n) # Space: O(m * n) +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def maxKilledEnemies(self, grid): """ @@ -34,6 +40,7 @@ def maxKilledEnemies(self, grid): up[j] += 1 left += 1 else: - result = max(result, left + up[j] + right[i][j] + down[i][j]) + result = max(result, + left + up[j] + right[i][j] + down[i][j]) return result diff --git a/Python/boundary-of-binary-tree.py b/Python/boundary-of-binary-tree.py index c71ed0df4..348e2c2c6 100644 --- a/Python/boundary-of-binary-tree.py +++ b/Python/boundary-of-binary-tree.py @@ -8,6 +8,7 @@ # self.left = None # self.right = None + class Solution(object): def boundaryOfBinaryTree(self, root): """ diff --git a/Python/brick-wall.py b/Python/brick-wall.py index 767290085..7124e7469 100644 --- a/Python/brick-wall.py +++ b/Python/brick-wall.py @@ -1,15 +1,20 @@ # Time: O(n), n is the total number of the bricks # Space: O(m), m is the total number different widths -# There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. -# The bricks have the same height but different width. You want to draw a vertical line from +# There is a brick wall in front of you. The wall is rectangular +# and has several rows of bricks. +# The bricks have the same height but different width. +# You want to draw a vertical line from # the top to the bottom and cross the least bricks. # -# The brick wall is represented by a list of rows. Each row is a list of integers representing the +# The brick wall is represented by a list of rows. +# Each row is a list of integers representing the # width of each brick in this row from left to right. # -# If your line go through the edge of a brick, then the brick is not considered as crossed. -# You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks. +# If your line go through the edge of a brick, +# then the brick is not considered as crossed. +# You need to find out how to draw the line to cross the least bricks and +# return the number of crossed bricks. # # You cannot draw a line just along one of the two vertical edges of the wall, # in which case the line will obviously cross no bricks. @@ -25,13 +30,19 @@ # Output: 2 # # Note: -# The width sum of bricks in different rows are the same and won't exceed INT_MAX. +# The width sum of bricks in different rows are the same and +# won't exceed INT_MAX. # The number of bricks in each row is in range [1,10,000]. # The height of wall is in range [1,10,000]. # Total number of bricks of the wall won't exceed 20,000. import collections +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class Solution(object): def leastBricks(self, wall): @@ -46,5 +57,5 @@ def leastBricks(self, wall): for i in xrange(len(row)-1): width += row[i] widths[width] += 1 - result = min(result, len(wall) - widths[width]); + result = min(result, len(wall) - widths[width]) return result diff --git a/Python/bricks-falling-when-hit.py b/Python/bricks-falling-when-hit.py index 9901572c7..2d568ee0c 100644 --- a/Python/bricks-falling-when-hit.py +++ b/Python/bricks-falling-when-hit.py @@ -2,14 +2,17 @@ # Space: O(r * c) # We have a grid of 1s and 0s; the 1s in a cell represent bricks. -# A brick will not drop if and only if it is directly connected to the top of the grid, +# A brick will not drop if and +# only if it is directly connected to the top of the grid, # or at least one of its (4-way) adjacent bricks will not drop. # -# We will do some erasures sequentially. Each time we want to do the erasure at the location (i, j), +# We will do some erasures sequentially. +# Each time we want to do the erasure at the location (i, j), # the brick (if it exists) on that location will disappear, # and then some other bricks may drop because of that erasure. # -# Return an array representing the number of bricks that will drop after each erasure in sequence. +# Return an array representing the number of bricks that +# will drop after each erasure in sequence. # # Example 1: # Input: @@ -17,7 +20,8 @@ # hits = [[1,0]] # Output: [2] # Explanation: -# If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. So we should return 2. +# If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. +# So we should return 2. # # Example 2: # Input: @@ -25,17 +29,21 @@ # hits = [[1,1],[1,0]] # Output: [0,0] # Explanation: -# When we erase the brick at (1, 0), the brick at (1, 1) has already disappeared due to the last move. +# When we erase the brick at (1, 0), the brick at (1, 1) +# has already disappeared due to the last move. # So each erasure will cause no bricks dropping. # Note that the erased brick (1, 0) will not be counted as a dropped brick. # # Note: # - The number of rows and columns in the grid will be in the range [1, 200]. # - The number of erasures will not exceed the area of the grid. -# - It is guaranteed that each erasure will be different from any other erasure, and located inside the grid. -# - An erasure may refer to a location with no brick - if it does, no bricks drop. +# - It is guaranteed that each erasure will be different from +# any other erasure, and located inside the grid. +# - An erasure may refer to a location with no brick - +# if it does, no bricks drop. -class UnionFind: + +class UnionFind(object): def __init__(self, n): self.set = range(n+1) self.size = [1]*(n+1) @@ -78,7 +86,8 @@ def index(C, r, c): union_find = UnionFind(R*C) for r, row in enumerate(hit_grid): for c, val in enumerate(row): - if not val: continue + if not val: + continue if r == 0: union_find.union_set(index(C, r, c), R*C) if r and hit_grid[r-1][c]: diff --git a/Python/bulb-switcher-ii.py b/Python/bulb-switcher-ii.py index 3bb37192d..e41844686 100644 --- a/Python/bulb-switcher-ii.py +++ b/Python/bulb-switcher-ii.py @@ -1,11 +1,14 @@ # Time: O(1) # Space: O(1) -# There is a room with n lights which are turned on initially and 4 buttons on the wall. +# There is a room with n lights which are turned on initially and +# 4 buttons on the wall. # After performing exactly m unknown operations towards buttons, -# you need to return how many different kinds of status of the n lights could be. +# you need to return how many different kinds of status of +# the n lights could be. # -# Suppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below: +# Suppose n lights are labeled as number [1, 2, 3 ..., n], +# function of these 4 buttons are given below: # 1. Flip all the lights. # 3. Flip lights with even numbers. # 3. Flip lights with odd numbers. @@ -22,9 +25,11 @@ # Example 3: # Input: n = 3, m = 1. # Output: 4 -# Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on]. +# Explanation: Status can be: [off, on, off], [on, off, on], +# [off, off, off], [off, on, on]. # Note: n and m both fit in range [0, 1000]. + class Solution(object): def flipLights(self, n, m): """ @@ -32,9 +37,14 @@ def flipLights(self, n, m): :type m: int :rtype: int """ - if m == 0: return 1 - if n == 1: return 2 - if m == 1 and n == 2: return 3 - if m == 1 or n == 2: return 4 - if m == 2: return 7 + if m == 0: + return 1 + if n == 1: + return 2 + if m == 1 and n == 2: + return 3 + if m == 1 or n == 2: + return 4 + if m == 2: + return 7 return 8 diff --git a/Python/bulls-and-cows.py b/Python/bulls-and-cows.py index ead89679c..b9c0b5cc6 100644 --- a/Python/bulls-and-cows.py +++ b/Python/bulls-and-cows.py @@ -33,8 +33,9 @@ # One pass solution. -from collections import defaultdict -from itertools import izip +from collections import defaultdict, Counter +from itertools import izip, imap + class Solution(object): def getHint(self, secret, guess): @@ -64,9 +65,6 @@ def getHint(self, secret, guess): # Two pass solution. -from collections import Counter -from itertools import imap - class Solution2(object): def getHint(self, secret, guess): """ diff --git a/Python/burst-balloons.py b/Python/burst-balloons.py index 4cb6ebd9c..ef84fff11 100644 --- a/Python/burst-balloons.py +++ b/Python/burst-balloons.py @@ -29,6 +29,12 @@ # coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 # +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def maxCoins(self, nums): """ @@ -43,9 +49,10 @@ def maxCoins(self, nums): for left in xrange(n - k): right = left + k for i in xrange(left + 1, right): - max_coins[left][right] = max(max_coins[left][right], \ - coins[left] * coins[i] * coins[right] + \ - max_coins[left][i] + max_coins[i][right]) + max_coins[left][right] = \ + max(max_coins[left][right], + coins[left] * coins[i] * coins[right] + + max_coins[left][i] + + max_coins[i][right]) return max_coins[0][-1] -