Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit aed475a

Browse files
pep8 style
1 parent 35232a4 commit aed475a

22 files changed

+524
-404
lines changed

‎anagrams.py‎

Lines changed: 44 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,55 @@
11
'''
2-
Two strings are said to be anagrams of one another if you can turn the first string into
3-
the second by rearranging its letters. For example, "table" and "bleat" are anagrams, as
4-
are "tear" and "rate." Your job is to write a function that takes in two strings as input and
2+
Two strings are said to be anagrams of one another if you can turn the
3+
first string into the second by rearranging its letters.
4+
5+
For example, "table" and "bleat" are anagrams, as are "tear" and "rate."
6+
Your job is to write a function that takes in two strings as input and
57
determines whether they're anagrams of one another.
68
79
Solution should run in O(n1 + n2)
810
There are two solutions:
9-
one is using counter
10-
another one is also using dictionary, but slightly faster.
11+
one is using counter
12+
another one is also using dictionary, but slightly faster.
1113
'''
1214
from collections import Counter
1315

16+
1417
def are_anagrams(str1, str2):
15-
if len(str1) != len(str2):
16-
return False
17-
dict1 = Counter(list(str1))
18-
dict2 = Counter(list(str2))
19-
for char in dict1:
20-
if not char in dict2 or dict2[char] != dict1[char]:
21-
return False
22-
return True
23-
24-
assert are_anagrams('table', 'bleat') == True
25-
assert are_anagrams('table', 'bleate') == False
26-
assert are_anagrams('honey', 'eyhon') == True
27-
assert are_anagrams('area', 'are') == False
28-
assert are_anagrams('', '') == True
18+
if len(str1) != len(str2):
19+
return False
20+
dict1 = Counter(list(str1))
21+
dict2 = Counter(list(str2))
22+
for char in dict1:
23+
if char not in dict2 or dict2[char] != dict1[char]:
24+
return False
25+
return True
26+
2927

3028
def are_anagrams_fast(str1, str2):
31-
if len(str1) != len(str2):
32-
return False
33-
34-
char_dict = {}
35-
for char in str1:
36-
if not char in char_dict:
37-
char_dict[char] = 0
38-
char_dict[char] += 1
39-
40-
for char in str2:
41-
if char not in char_dict or char_dict[char] <= 0:
42-
return False
43-
char_dict[char] -= 1
44-
return True
45-
46-
assert are_anagrams_fast('table', 'bleat') == True
47-
assert are_anagrams_fast('table', 'bleate') == False
48-
assert are_anagrams_fast('honey', 'eyhon') == True
49-
assert are_anagrams_fast('area', 'are') == False
50-
assert are_anagrams_fast('', '') == True
29+
if len(str1) != len(str2):
30+
return False
31+
32+
char_dict = {}
33+
for char in str1:
34+
if char not in char_dict:
35+
char_dict[char] = 0
36+
char_dict[char] += 1
37+
38+
for char in str2:
39+
if char not in char_dict or char_dict[char] <= 0:
40+
return False
41+
char_dict[char] -= 1
42+
return True
43+
44+
45+
def test(anagram_fn):
46+
print('Testing ', anagram_fn)
47+
assert anagram_fn('table', 'bleat')
48+
assert not anagram_fn('table', 'bleate')
49+
assert anagram_fn('honey', 'eyhon')
50+
assert not anagram_fn('area', 'are3')
51+
assert not anagram_fn('', ' ')
52+
53+
54+
test(are_anagrams)
55+
test(are_anagrams_fast)

‎binary_heap.py‎

Lines changed: 73 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,91 +1,97 @@
11
'''
2-
A binary heap is a complete binary tree which satisfies the min-heap ordering property.
2+
A binary heap is a complete binary tree which satisfies
3+
the min-heap ordering property.
34
The value of each node is greater than or equal to the value of its parent,
45
with the minimum-value element at the root.
56
67
Methods available:
78
insert(value): insert a value into the binary heap
89
peek_min(): peek the next smallest value
910
extract_min(): return the next smallest value and remove it from the heap.
10-
Raise ValueError if that value doesn't exist
11+
Raise ValueError if that value doesn't exist
1112
is_empty(): returns True if the heap is empty, False otherwise
12-
13+
1314
Extra usage:
1415
iter(bh): return iteration to bh
1516
list(bh): list all values in the heap
16-
in a pre-order traversal (root, left, right)
17+
in a pre-order traversal (root, left, right)
1718
1819
BinaryHeap can be used to build a priority queue and to do heap sort algorithm
1920
20-
insert extract_min peek_min
21-
binary heapO(log n)O(log n) O(1)
21+
insert extract_min peek_min
22+
binary heapO(log n)O(log n) O(1)
2223
'''
2324
import random
2425

26+
2527
class BinaryHeap(object):
26-
def __init__(self, arr=None):
27-
self._list = [0]
28-
if arr:
29-
for value in arr:
30-
self.insert(value)
31-
32-
def insert(self, value):
33-
self._list.append(value)
34-
self._bubble_up(len(self._list) - 1)
35-
36-
def peek_min(self):
37-
if len(self._list) == 1:
38-
raise ValueError('Empty')
39-
return self._list[1]
40-
41-
def extract_min(self):
42-
if len(self._list) == 1:
43-
raise ValueError('Empty')
44-
value = self._list[1]
45-
self._swap(1, -1)
46-
self._list = self._list[:-1]
47-
self._bubble_down(1)
48-
return value
49-
50-
def is_empty(self):
51-
return len(self._list) == 1
52-
53-
def __len__(self):
54-
return len(self._list) - 1
55-
56-
def __iter__(self):
57-
yield from iter(self._list[1:])
58-
59-
def _swap(self, idx1, idx2):
60-
temp = self._list[idx1]
61-
self._list[idx1] = self._list[idx2]
62-
self._list[idx2] = temp
63-
64-
def _bubble_down(self, idx):
65-
while 2 * idx < len(self._list): # has at least one child
66-
if len(self._list) == 2 * idx + 1:
67-
min_child = 2 * idx
68-
else:
69-
min_child = 2 * idx if self._list[2 * idx] < self._list[2 * idx + 1] else 2 * idx + 1
70-
self._swap(min_child, idx)
71-
idx = min_child
72-
73-
def _bubble_up(self, idx):
74-
parent = idx // 2
75-
while idx > 1 and self._list[idx] < self._list[parent]:
76-
self._swap(parent, idx)
77-
idx = parent
78-
parent = idx // 2
28+
def __init__(self, arr=None):
29+
self._list = [0]
30+
if arr:
31+
for value in arr:
32+
self.insert(value)
33+
34+
def insert(self, value):
35+
self._list.append(value)
36+
self._bubble_up(len(self._list) - 1)
37+
38+
def peek_min(self):
39+
if len(self._list) == 1:
40+
raise ValueError('Empty')
41+
return self._list[1]
42+
43+
def extract_min(self):
44+
if len(self._list) == 1:
45+
raise ValueError('Empty')
46+
value = self._list[1]
47+
self._swap(1, -1)
48+
self._list = self._list[:-1]
49+
self._bubble_down(1)
50+
return value
51+
52+
def is_empty(self):
53+
return len(self._list) == 1
54+
55+
def __len__(self):
56+
return len(self._list) - 1
57+
58+
def __iter__(self):
59+
yield from iter(self._list[1:])
60+
61+
def _swap(self, idx1, idx2):
62+
temp = self._list[idx1]
63+
self._list[idx1] = self._list[idx2]
64+
self._list[idx2] = temp
65+
66+
def _bubble_down(self, idx):
67+
while 2 * idx < len(self._list): # has at least one child
68+
if len(self._list) == 2 * idx + 1:
69+
min_child = 2 * idx
70+
else:
71+
if self._list[2 * idx] < self._list[2 * idx + 1]:
72+
min_child = 2 * idx
73+
else:
74+
min_child = 2 * idx + 1
75+
self._swap(min_child, idx)
76+
idx = min_child
77+
78+
def _bubble_up(self, idx):
79+
parent = idx // 2
80+
while idx > 1 and self._list[idx] < self._list[parent]:
81+
self._swap(parent, idx)
82+
idx = parent
83+
parent = idx // 2
84+
7985

8086
def test_heap():
81-
bh = BinaryHeap()
82-
values = random.sample(range(-15, 15), 30)
83-
for v in values:
84-
bh.insert(v)
85-
print(list(bh))
87+
bh = BinaryHeap()
88+
values = random.sample(range(-15, 15), 30)
89+
for v in values:
90+
bh.insert(v)
91+
print(list(bh))
8692

87-
for v in iter(bh):
88-
print(v)
93+
for v in iter(bh):
94+
print(v)
8995

90-
# test_heap()
9196

97+
test_heap()

‎binary_search_tree.py‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
list(bst): list all values of the tree in an in-order traversal
1414
'''
1515

16-
import random
16+
import random
17+
1718

1819
class Node(object):
1920
__slots__ = ('value', 'left', 'right')
@@ -23,6 +24,7 @@ def __init__(self, value, left=None, right=None):
2324
self.left = left
2425
self.right = right
2526

27+
2628
class BST(object):
2729
def __init__(self):
2830
self._root = None
@@ -43,7 +45,7 @@ def remove(self, value):
4345
curr, parent = self._find_parent(self._root, None, value, True)
4446
if (not curr or curr.value != value):
4547
raise ValueError()
46-
if not parent: # it's the root
48+
if not parent: # it's the root
4749
self._root = self._remove_root(self._root, True)
4850
else:
4951
if parent.left and parent.left.value == value:
@@ -108,12 +110,13 @@ def _find_parent(self, node, prev, value, to_remove=False):
108110

109111
if value <= node.value:
110112
if node.left:
111-
node, prev = self._find_parent(node.left, node, value, to_remove)
113+
node, prev = self._find_parent(
114+
node.left, node, value, to_remove)
112115
return node, prev
113-
116+
114117
if node.right:
115118
node, prev = self._find_parent(node.right, node, value, to_remove)
116-
119+
117120
return node, prev
118121

119122
def _iter(self, node):
@@ -122,6 +125,7 @@ def _iter(self, node):
122125
yield node.value
123126
yield from self._iter(node.right)
124127

128+
125129
def test_bst():
126130
bst = BST()
127131
values = []
@@ -140,8 +144,5 @@ def test_bst():
140144

141145
assert list(bst) == sorted(values)
142146

143-
test_bst()
144-
145-
146-
147147

148+
test_bst()

‎binary_tree_algos.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,19 @@
44
input: root of a binary tree
55
output: True if the binary tree is a binary search tree.
66
False otherwise
7-
The idea is that if it's a binary search tree, when you traverse
7+
The idea is that if it's a binary search tree, when you traverse
88
the tree in-order, the values will always be non-decreasing.
9-
10-
Note that there are two versions of this function.
9+
10+
Note that there are two versions of this function.
1111
The first one is how it should be.
1212
The second one is the one accepted by HackerRank.
1313
'''
1414

15+
1516
def is_bst(root):
1617
return _is_bst_helper(root, None)
1718

19+
1820
def _is_bst_helper(node, prev):
1921
if not node:
2022
return True
@@ -24,6 +26,7 @@ def _is_bst_helper(node, prev):
2426
return False
2527
return _is_bst_helper(node.right, node)
2628

29+
2730
def is_bst_hr(root):
2831
''' The solution accepted by HackerRank'''
2932
nodes = _in_order_traversal(root, [])
@@ -36,10 +39,11 @@ def is_bst_hr(root):
3639
return False
3740
seen.add(node.data)
3841

42+
3943
def _in_order_traversal(root, nodes):
4044
if not root:
4145
return nodes
4246
new_nodes = _in_order_traversal(root.left, nodes)
4347
new_nodes.append(root)
4448
new_nodes = _in_order_traversal(root.right, new_nodes)
45-
return new_nodes
49+
return new_nodes

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /