Skip to content

Commit

Permalink
idiomatic Python
Browse files Browse the repository at this point in the history
  • Loading branch information
SocialfiPanda committed Sep 7, 2014
1 parent 3240193 commit 722cc13
Show file tree
Hide file tree
Showing 75 changed files with 926 additions and 522 deletions.
1 change: 0 additions & 1 deletion .gitignore

This file was deleted.

34 changes: 33 additions & 1 deletion Add Binary.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,35 @@
class Solution:
def addBinary(self, a, b):
return bin(int(a, 2) + int(b, 2)).split('b')[1]
return bin(int(a, 2) + int(b, 2)).split('b')[1]

def addBinary(self, a, b):
"""Sometimes built-in function cheats too much.
"""
res, carry, len_a, len_b, i = "", 0, len(a), len(b), 0
for i in range(max(len_a, len_b)):
sum = carry
if i < len_a:
sum += int(a[-(i + 1)])
if i < len_b:
sum += int(b[-(i + 1)])
carry = sum / 2
sum = sum % 2
res = "{0}{1}".format(sum, res)
if carry == 1:
res = "1" + res
return res

# def addBinary(self, a, b):
# """Using carry without sum is also fine. But the readability sucks.
# """
# res, carry, len_a, len_b, i = "", 0, len(a), len(b), 0
# for i in range(max(len_a, len_b)):
# if i < len_a:
# carry += int(a[-(i + 1)])
# if i < len_b:
# carry += int(b[-(i + 1)])
# res = "{0}{1}".format(carry % 2, res)
# carry = carry / 2
# if carry == 1:
# res = "1" + res
# return res
35 changes: 23 additions & 12 deletions Anagrams.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
class Solution:
def anagrams(self, strs):
map, result = {}, []
if len(strs) >= 1:
for str in strs:
sorted_str = "".join(sorted(str))
if sorted_str not in map:
map[sorted_str] = [str]
else:
map[sorted_str].append(str)
for word in map:
if len(map[word]) > 1:
result += map[word]
return result
anagram_map, res = {}, []
for str in strs:
sorted_str = ("").join(sorted(str))
if sorted_str in anagram_map:
anagram_map[sorted_str].append(str)
else:
anagram_map[sorted_str] = [str]
for anagrams in anagram_map.values():
if len(anagrams) > 1:
res += anagrams
return res

# def anagrams(self, strs):
# """List comprehension may be more elegant but less readable here.
# """
# anagram_map = {}
# for str in strs:
# sorted_str = ("").join(sorted(str))
# if sorted_str in anagram_map:
# anagram_map[sorted_str].append(str)
# else:
# anagram_map[sorted_str] = [str]
# return [anagram for anagrams in anagram_map.values() if len(anagrams) > 1 for anagram in anagrams]
3 changes: 1 addition & 2 deletions Best Time to Buy and Sell Stock II.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,5 @@ class Solution:
def maxProfit(self, prices):
profit = 0
for i in range(len(prices) - 1):
if (prices[i] < prices[i+1]):
profit += prices[i+1] - prices[i]
profit += max(0, prices[i + 1] - prices[i])
return profit
22 changes: 10 additions & 12 deletions Best Time to Buy and Sell Stock III.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
class Solution:
def maxProfit(self, prices):
min_price, max_profit = 9223372036854775807, 0
profits_before = [0 for i in range(len(prices))]
for i in range(len(prices)):
min_price = min(prices[i], min_price)
max_profit = max(prices[i] - min_price, max_profit)
profits_before[i] = max_profit
max_price, max_profit = -9223372036854775808, 0
profits_after = [0 for i in range(len(prices))]
min_price, max_profit, max_profits = 9223372036854775807, 0, []
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
max_profits.append(max_profit)
max_price, max_profit_after, max_combined_profit = 0, 0, 0
for i in reversed(range(len(prices))):
max_price = max(prices[i], max_price)
max_profit = max(max_price - prices[i], max_profit)
profits_after[i] = max_profit
return reduce(lambda acc, i: max(profits_before[i] + profits_after[i], acc), range(len(prices)), 0)
max_price = max(max_price, prices[i])
max_profit_after = max(max_profit_after, max_price - prices[i])
max_combined_profit = max(max_combined_profit, max_profit_after + max_profits[i])
return max_combined_profit
8 changes: 4 additions & 4 deletions Best Time to Buy and Sell Stock.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
class Solution:
def maxProfit(self, prices):
min_price = 9223372036854775807
max_profit = 0
for i in range(len(prices)):
min_price = min(prices[i], min_price)
max_profit = max(prices[i] - min_price, max_profit)
min_price = 9223372036854775807
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
20 changes: 10 additions & 10 deletions Binary Tree Inorder Traversal.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
class Solution:
def inorderTraversal(self, root):
result = []
self.recur(root, result)
return result

def recur(self, root, result):
if(root == None):
return
self.recur(root.left, result)
result.append(root.val)
self.recur(root.right, result)
res, stack, current = [], [], root
while stack or current:
if current:
stack.append(current)
current = current.left
else:
parent = stack.pop()
res.append(parent.val)
current = parent.right
return res
65 changes: 33 additions & 32 deletions Binary Tree Level Order Traversal II.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
class Solution:
def levelOrderBottom(self, root):
result = []
if root == None:
return result
current = [root]
while len(current) > 0:
# Python is just so slow, but who I can complain? I have to write following code to optimize for skewed tree
# -- None of the code from this tag to the next tag is actually needed -- #
if len(current) == 1 and (current[0].left == None or current[0].right== None):
this_node = current[0]
result.insert(0, [this_node.val])
if this_node.left == None and this_node.right != None:
current = [this_node.right]
elif this_node.left != None and this_node.right == None:
current = [this_node.left]
else:
current.pop(0)
else:
# -- None of the code above this tag up to the previous tag is actually needed -- #
vals = []
size = len(current)
for i in range(size):
this_node = current[0]
vals.append(this_node.val)
if i < len(current) - 1:
this_node.next = current[i+1]
if this_node.left != None:
current.append(this_node.left)
if this_node.right != None:
current.append(this_node.right)
current.pop(0)
result.insert(0, vals)
return result
if root is None:
return []
res, current = [], [root]
while current:
next, vals = [], []
for node in current:
vals.append(node.val)
if node.left:
next.append(node.left)
if node.right:
next.append(node.right)
current = next
res.insert(0, vals)
return res

# def levelOrderBottom(self, root):
# """ Using a queue is also fine.
# """
# if root is None:
# return []
# current, res = [root], []
# while current:
# vals, length = [], len(current)
# for i in range(length):
# node = current[0]
# vals.append(node.val)
# if node.left:
# current.append(node.left)
# if node.right:
# current.append(node.right)
# current.pop(0)
# res.insert(0, vals)
# return res
65 changes: 33 additions & 32 deletions Binary Tree Level Order Traversal.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
class Solution:
def levelOrder(self, root):
result = []
if root == None:
return result
current = [root]
while len(current) > 0:
# Python is just so slow, but who I can complain? I have to write following code to optimize for skewed tree
# -- None of the code from this tag to the next tag is actually needed -- #
if len(current) == 1 and (current[0].left == None or current[0].right== None):
this_node = current[0]
result.append([this_node.val])
if this_node.left == None and this_node.right != None:
current = [this_node.right]
elif this_node.left != None and this_node.right == None:
current = [this_node.left]
else:
current.pop(0)
else:
# -- None of the code above this tag up to the previous tag is actually needed -- #
vals = []
size = len(current)
for i in range(size):
this_node = current[0]
vals.append(this_node.val)
if i < len(current) - 1:
this_node.next = current[i+1]
if this_node.left != None:
current.append(this_node.left)
if this_node.right != None:
current.append(this_node.right)
current.pop(0)
result.append(vals)
return result
if root is None:
return []
current, res = [root], []
while current:
next, vals = [], []
for node in current:
vals.append(node.val)
if node.left:
next.append(node.left)
if node.right:
next.append(node.right)
res.append(vals)
current = next
return res

# def levelOrder(self, root):
# """ Using a queue is also fine.
# """
# if root is None:
# return []
# current, res = [root], []
# while current:
# vals, length = [], len(current)
# for i in range(length):
# node = current[0]
# vals.append(node.val)
# if node.left:
# current.append(node.left)
# if node.right:
# current.append(node.right)
# current.pop(0)
# res.append(vals)
# return res
23 changes: 13 additions & 10 deletions Binary Tree Postorder Traversal.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
class Solution:
def postorderTraversal(self, root):
result = []
self.recur(root, result)
return result

def recur(self, root, result):
if(root == None):
return
self.recur(root.left, result)
self.recur(root.right, result)
result.append(root.val)
res, stack, current, prev = [], [], root, None
while stack or current:
if current:
stack.append(current)
current = current.left
else:
parent = stack[-1]
if parent.right in (None, prev):
prev = stack.pop()
res.append(prev.val)
else:
current = parent.right
return res
21 changes: 11 additions & 10 deletions Binary Tree Preorder Traversal.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
class Solution:
def preorderTraversal(self, root):
result = []
self.recur(root, result)
return result

def recur(self, root, result):
if(root == None):
return
result.append(root.val)
self.recur(root.left, result)
self.recur(root.right, result)
res, stack = [], [root]
if root is None:
return res
while stack:
current = stack.pop()
if current.right:
stack.append(current.right)
if current.left:
stack.append(current.left)
res.append(current.val)
return res
6 changes: 3 additions & 3 deletions Climbing Stairs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
class Solution:
def climbStairs(self, n):
prev, current = 1, 0
for i in range(n + 1):
prev, current = current, prev + current
prev, current = 0, 1
for i in range(n):
prev, current = current, current + prev
return current
7 changes: 3 additions & 4 deletions Container With Most Water.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
class Solution:
def maxArea(self, height):
i, j, maxArea = 0, len(height) - 1, 0
i, j, max_area = 0, len(height) - 1, 0
while i < j:
max_area = max(max_area, (j - i) * min(height[i], height[j]))
if height[i] < height[j]:
maxArea = max(maxArea, (j - i) * height[i])
i += 1
else:
maxArea = max(maxArea, (j - i) * height[j])
j -= 1
return maxArea
return max_area
11 changes: 4 additions & 7 deletions Convert Sorted Array to Binary Search Tree.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
class Solution:
def sortedArrayToBST(self, num):
return self.buildBST(num, 0, len(num) - 1)

def buildBST(self, num, left, right):
if left > right:
if len(num) == 0:
return None
mid = (left + right) / 2
mid = len(num) / 2
current = TreeNode(num[mid])
current.left = self.buildBST(num, left, mid - 1)
current.right = self.buildBST(num, mid + 1, right)
current.left = self.sortedArrayToBST(num[:mid])
current.right = self.sortedArrayToBST(num[mid + 1:])
return current
Loading

0 comments on commit 722cc13

Please sign in to comment.