Skip to content

Commit 722cc13

Browse files
committed
idiomatic Python
1 parent 3240193 commit 722cc13

File tree

75 files changed

+926
-522
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

75 files changed

+926
-522
lines changed

.gitignore

Lines changed: 0 additions & 1 deletion
This file was deleted.

Add Binary.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,35 @@
11
class Solution:
22
def addBinary(self, a, b):
3-
return bin(int(a, 2) + int(b, 2)).split('b')[1]
3+
return bin(int(a, 2) + int(b, 2)).split('b')[1]
4+
5+
def addBinary(self, a, b):
6+
"""Sometimes built-in function cheats too much.
7+
"""
8+
res, carry, len_a, len_b, i = "", 0, len(a), len(b), 0
9+
for i in range(max(len_a, len_b)):
10+
sum = carry
11+
if i < len_a:
12+
sum += int(a[-(i + 1)])
13+
if i < len_b:
14+
sum += int(b[-(i + 1)])
15+
carry = sum / 2
16+
sum = sum % 2
17+
res = "{0}{1}".format(sum, res)
18+
if carry == 1:
19+
res = "1" + res
20+
return res
21+
22+
# def addBinary(self, a, b):
23+
# """Using carry without sum is also fine. But the readability sucks.
24+
# """
25+
# res, carry, len_a, len_b, i = "", 0, len(a), len(b), 0
26+
# for i in range(max(len_a, len_b)):
27+
# if i < len_a:
28+
# carry += int(a[-(i + 1)])
29+
# if i < len_b:
30+
# carry += int(b[-(i + 1)])
31+
# res = "{0}{1}".format(carry % 2, res)
32+
# carry = carry / 2
33+
# if carry == 1:
34+
# res = "1" + res
35+
# return res

Anagrams.py

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,25 @@
11
class Solution:
22
def anagrams(self, strs):
3-
map, result = {}, []
4-
if len(strs) >= 1:
5-
for str in strs:
6-
sorted_str = "".join(sorted(str))
7-
if sorted_str not in map:
8-
map[sorted_str] = [str]
9-
else:
10-
map[sorted_str].append(str)
11-
for word in map:
12-
if len(map[word]) > 1:
13-
result += map[word]
14-
return result
3+
anagram_map, res = {}, []
4+
for str in strs:
5+
sorted_str = ("").join(sorted(str))
6+
if sorted_str in anagram_map:
7+
anagram_map[sorted_str].append(str)
8+
else:
9+
anagram_map[sorted_str] = [str]
10+
for anagrams in anagram_map.values():
11+
if len(anagrams) > 1:
12+
res += anagrams
13+
return res
14+
15+
# def anagrams(self, strs):
16+
# """List comprehension may be more elegant but less readable here.
17+
# """
18+
# anagram_map = {}
19+
# for str in strs:
20+
# sorted_str = ("").join(sorted(str))
21+
# if sorted_str in anagram_map:
22+
# anagram_map[sorted_str].append(str)
23+
# else:
24+
# anagram_map[sorted_str] = [str]
25+
# return [anagram for anagrams in anagram_map.values() if len(anagrams) > 1 for anagram in anagrams]

Best Time to Buy and Sell Stock II.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,5 @@ class Solution:
22
def maxProfit(self, prices):
33
profit = 0
44
for i in range(len(prices) - 1):
5-
if (prices[i] < prices[i+1]):
6-
profit += prices[i+1] - prices[i]
5+
profit += max(0, prices[i + 1] - prices[i])
76
return profit
Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
class Solution:
22
def maxProfit(self, prices):
3-
min_price, max_profit = 9223372036854775807, 0
4-
profits_before = [0 for i in range(len(prices))]
5-
for i in range(len(prices)):
6-
min_price = min(prices[i], min_price)
7-
max_profit = max(prices[i] - min_price, max_profit)
8-
profits_before[i] = max_profit
9-
max_price, max_profit = -9223372036854775808, 0
10-
profits_after = [0 for i in range(len(prices))]
3+
min_price, max_profit, max_profits = 9223372036854775807, 0, []
4+
for price in prices:
5+
min_price = min(min_price, price)
6+
max_profit = max(max_profit, price - min_price)
7+
max_profits.append(max_profit)
8+
max_price, max_profit_after, max_combined_profit = 0, 0, 0
119
for i in reversed(range(len(prices))):
12-
max_price = max(prices[i], max_price)
13-
max_profit = max(max_price - prices[i], max_profit)
14-
profits_after[i] = max_profit
15-
return reduce(lambda acc, i: max(profits_before[i] + profits_after[i], acc), range(len(prices)), 0)
10+
max_price = max(max_price, prices[i])
11+
max_profit_after = max(max_profit_after, max_price - prices[i])
12+
max_combined_profit = max(max_combined_profit, max_profit_after + max_profits[i])
13+
return max_combined_profit

Best Time to Buy and Sell Stock.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
class Solution:
22
def maxProfit(self, prices):
3-
min_price = 9223372036854775807
43
max_profit = 0
5-
for i in range(len(prices)):
6-
min_price = min(prices[i], min_price)
7-
max_profit = max(prices[i] - min_price, max_profit)
4+
min_price = 9223372036854775807
5+
for price in prices:
6+
min_price = min(min_price, price)
7+
max_profit = max(max_profit, price - min_price)
88
return max_profit

Binary Tree Inorder Traversal.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
class Solution:
22
def inorderTraversal(self, root):
3-
result = []
4-
self.recur(root, result)
5-
return result
6-
7-
def recur(self, root, result):
8-
if(root == None):
9-
return
10-
self.recur(root.left, result)
11-
result.append(root.val)
12-
self.recur(root.right, result)
3+
res, stack, current = [], [], root
4+
while stack or current:
5+
if current:
6+
stack.append(current)
7+
current = current.left
8+
else:
9+
parent = stack.pop()
10+
res.append(parent.val)
11+
current = parent.right
12+
return res
Lines changed: 33 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,35 @@
11
class Solution:
22
def levelOrderBottom(self, root):
3-
result = []
4-
if root == None:
5-
return result
6-
current = [root]
7-
while len(current) > 0:
8-
# Python is just so slow, but who I can complain? I have to write following code to optimize for skewed tree
9-
# -- None of the code from this tag to the next tag is actually needed -- #
10-
if len(current) == 1 and (current[0].left == None or current[0].right== None):
11-
this_node = current[0]
12-
result.insert(0, [this_node.val])
13-
if this_node.left == None and this_node.right != None:
14-
current = [this_node.right]
15-
elif this_node.left != None and this_node.right == None:
16-
current = [this_node.left]
17-
else:
18-
current.pop(0)
19-
else:
20-
# -- None of the code above this tag up to the previous tag is actually needed -- #
21-
vals = []
22-
size = len(current)
23-
for i in range(size):
24-
this_node = current[0]
25-
vals.append(this_node.val)
26-
if i < len(current) - 1:
27-
this_node.next = current[i+1]
28-
if this_node.left != None:
29-
current.append(this_node.left)
30-
if this_node.right != None:
31-
current.append(this_node.right)
32-
current.pop(0)
33-
result.insert(0, vals)
34-
return result
3+
if root is None:
4+
return []
5+
res, current = [], [root]
6+
while current:
7+
next, vals = [], []
8+
for node in current:
9+
vals.append(node.val)
10+
if node.left:
11+
next.append(node.left)
12+
if node.right:
13+
next.append(node.right)
14+
current = next
15+
res.insert(0, vals)
16+
return res
17+
18+
# def levelOrderBottom(self, root):
19+
# """ Using a queue is also fine.
20+
# """
21+
# if root is None:
22+
# return []
23+
# current, res = [root], []
24+
# while current:
25+
# vals, length = [], len(current)
26+
# for i in range(length):
27+
# node = current[0]
28+
# vals.append(node.val)
29+
# if node.left:
30+
# current.append(node.left)
31+
# if node.right:
32+
# current.append(node.right)
33+
# current.pop(0)
34+
# res.insert(0, vals)
35+
# return res

Binary Tree Level Order Traversal.py

Lines changed: 33 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,35 @@
11
class Solution:
22
def levelOrder(self, root):
3-
result = []
4-
if root == None:
5-
return result
6-
current = [root]
7-
while len(current) > 0:
8-
# Python is just so slow, but who I can complain? I have to write following code to optimize for skewed tree
9-
# -- None of the code from this tag to the next tag is actually needed -- #
10-
if len(current) == 1 and (current[0].left == None or current[0].right== None):
11-
this_node = current[0]
12-
result.append([this_node.val])
13-
if this_node.left == None and this_node.right != None:
14-
current = [this_node.right]
15-
elif this_node.left != None and this_node.right == None:
16-
current = [this_node.left]
17-
else:
18-
current.pop(0)
19-
else:
20-
# -- None of the code above this tag up to the previous tag is actually needed -- #
21-
vals = []
22-
size = len(current)
23-
for i in range(size):
24-
this_node = current[0]
25-
vals.append(this_node.val)
26-
if i < len(current) - 1:
27-
this_node.next = current[i+1]
28-
if this_node.left != None:
29-
current.append(this_node.left)
30-
if this_node.right != None:
31-
current.append(this_node.right)
32-
current.pop(0)
33-
result.append(vals)
34-
return result
3+
if root is None:
4+
return []
5+
current, res = [root], []
6+
while current:
7+
next, vals = [], []
8+
for node in current:
9+
vals.append(node.val)
10+
if node.left:
11+
next.append(node.left)
12+
if node.right:
13+
next.append(node.right)
14+
res.append(vals)
15+
current = next
16+
return res
17+
18+
# def levelOrder(self, root):
19+
# """ Using a queue is also fine.
20+
# """
21+
# if root is None:
22+
# return []
23+
# current, res = [root], []
24+
# while current:
25+
# vals, length = [], len(current)
26+
# for i in range(length):
27+
# node = current[0]
28+
# vals.append(node.val)
29+
# if node.left:
30+
# current.append(node.left)
31+
# if node.right:
32+
# current.append(node.right)
33+
# current.pop(0)
34+
# res.append(vals)
35+
# return res

Binary Tree Postorder Traversal.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
class Solution:
22
def postorderTraversal(self, root):
3-
result = []
4-
self.recur(root, result)
5-
return result
6-
7-
def recur(self, root, result):
8-
if(root == None):
9-
return
10-
self.recur(root.left, result)
11-
self.recur(root.right, result)
12-
result.append(root.val)
3+
res, stack, current, prev = [], [], root, None
4+
while stack or current:
5+
if current:
6+
stack.append(current)
7+
current = current.left
8+
else:
9+
parent = stack[-1]
10+
if parent.right in (None, prev):
11+
prev = stack.pop()
12+
res.append(prev.val)
13+
else:
14+
current = parent.right
15+
return res

Binary Tree Preorder Traversal.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
class Solution:
22
def preorderTraversal(self, root):
3-
result = []
4-
self.recur(root, result)
5-
return result
6-
7-
def recur(self, root, result):
8-
if(root == None):
9-
return
10-
result.append(root.val)
11-
self.recur(root.left, result)
12-
self.recur(root.right, result)
3+
res, stack = [], [root]
4+
if root is None:
5+
return res
6+
while stack:
7+
current = stack.pop()
8+
if current.right:
9+
stack.append(current.right)
10+
if current.left:
11+
stack.append(current.left)
12+
res.append(current.val)
13+
return res

Climbing Stairs.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
class Solution:
22
def climbStairs(self, n):
3-
prev, current = 1, 0
4-
for i in range(n + 1):
5-
prev, current = current, prev + current
3+
prev, current = 0, 1
4+
for i in range(n):
5+
prev, current = current, current + prev
66
return current

Container With Most Water.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
class Solution:
22
def maxArea(self, height):
3-
i, j, maxArea = 0, len(height) - 1, 0
3+
i, j, max_area = 0, len(height) - 1, 0
44
while i < j:
5+
max_area = max(max_area, (j - i) * min(height[i], height[j]))
56
if height[i] < height[j]:
6-
maxArea = max(maxArea, (j - i) * height[i])
77
i += 1
88
else:
9-
maxArea = max(maxArea, (j - i) * height[j])
109
j -= 1
11-
return maxArea
10+
return max_area
Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
11
class Solution:
22
def sortedArrayToBST(self, num):
3-
return self.buildBST(num, 0, len(num) - 1)
4-
5-
def buildBST(self, num, left, right):
6-
if left > right:
3+
if len(num) == 0:
74
return None
8-
mid = (left + right) / 2
5+
mid = len(num) / 2
96
current = TreeNode(num[mid])
10-
current.left = self.buildBST(num, left, mid - 1)
11-
current.right = self.buildBST(num, mid + 1, right)
7+
current.left = self.sortedArrayToBST(num[:mid])
8+
current.right = self.sortedArrayToBST(num[mid + 1:])
129
return current

0 commit comments

Comments
 (0)