Skip to content

Commit 6b90e92

Browse files
committed
add graph.py
1 parent 5c6a5b3 commit 6b90e92

7 files changed

+317
-2
lines changed

README.md

+4-2
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
This repository contains the Python source code for the algorithms in the textbook
44
<a href = "http://amzn.to/13VNJi7">Algorithms, 4th Edition</a> by Robert Sedgewick and Kevin Wayne.
55

6+
The official Java source code is <a href="https://github.com/kevin-wayne/algs4">here</a>.
7+
68
The programs are organized in the package <code>algs4</code>.
79

810
## Goals
911

1012
Make a Python implementation of the library so that a Python programmer can learn this book easily.
1113

12-
Try to keep the interface and variable name consistent with the original book without violating the Python coding standards.
14+
Try to keep the interface and variable name consistent with the original book while not violating Python coding standards.
1315

1416
## Installing
1517

@@ -29,5 +31,5 @@ This code is released under MIT.
2931

3032
## Contribute to this repository
3133

32-
Issue reports and code fixes are welcome. please follow the same style as the code in the repository and thoroughly test your
34+
Issue reports and code fixes are welcome. please follow the same style as the code in the repository and add test for your
3335
code.

algs4/binary_search_st.py

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
from algs4.utils.st import Node, STKeyIterator
2+
3+
4+
class BinarySearchST:
5+
6+
def __init__(self):
7+
self.keys = []
8+
self.vals = []
9+
self.size = 0
10+
11+
def contains(self, key):
12+
x = self.first
13+
while x:
14+
if key == x.key:
15+
return True
16+
x = x.next
17+
return False
18+
19+
def rank(self, key):
20+
lo = 0
21+
hi = self.size - 1
22+
while lo <= hi:
23+
mid = lo + (hi - lo) / 2
24+
if key < self.keys[mid]:
25+
hi = mid - 1
26+
elif key > self.keys[mid]:
27+
lo = lo + 1
28+
else:
29+
return mid
30+
return lo
31+
32+
def get(self, key):
33+
i = self.rank(key)
34+
if i < self.size and self.keys[i] == key:
35+
return self.vals[i]
36+
else:
37+
return None
38+
39+
def put(self, key, val):
40+
i = self.rank(key)
41+
if i < self.size and self.keys[i] == key:
42+
self.vals[i] = val
43+
return
44+
45+
self.keys.append(key)
46+
self.vals.append(val)
47+
j = self.size - 1
48+
while j > i:
49+
self.keys[j] = self.keys[j - 1]
50+
self.vals[j] = self.vals[j - 1]
51+
self.keys[i] = key
52+
self.vals[i] = val
53+
self.size += 1
54+
55+
def delete(self, key):
56+
i = self.rank(key)
57+
if i < self.size and self.keys[i] == key:
58+
self.size -= 1
59+
for j in range(i, self.size):
60+
self.keys[j] = self.keys[j + 1]
61+
self.vals[j] = self.vals[j + 1]
62+
self.keys[-1] = None
63+
self.vals[-1] = None
64+
65+
def is_empty(self):
66+
return self.size == 0
67+
68+
def min(self):
69+
return self.keys[0]
70+
71+
def max(self):
72+
return self.keys[-1]
73+
74+
def select(self, k):
75+
return self.keys[k]
76+
77+
def ceiling(self, key):
78+
i = self.rank(key)
79+
if i == self.size:
80+
return None
81+
82+
return self.keys[i]
83+
84+
def floor(self, key):
85+
i = self.rank(key)
86+
if i == 0:
87+
return None
88+
return self.keys[i - 1]

algs4/frequency_counter.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
Execution:
3+
python frequency_counter L < input.txt
4+
Data files:
5+
https://algs4.cs.princeton.edu/31elementary/tnyTale.txt
6+
https://algs4.cs.princeton.edu/31elementary/tale.txt
7+
https://algs4.cs.princeton.edu/31elementary/leipzig100K.txt
8+
https://algs4.cs.princeton.edu/31elementary/leipzig300K.txt
9+
https://algs4.cs.princeton.edu/31elementary/leipzig1M.txt
10+
11+
Read in a list of words from standard input and print out
12+
the most frequently occurring word that has length greater than
13+
a given threshold.
14+
15+
% python frequency_counter 1 < tinyTale.txt
16+
it 10
17+
18+
% python frequency_counter 8 < tale.txt
19+
business 122
20+
21+
% python frequency_counter 10 < leipzig1M.txt
22+
government 24763
23+
"""
24+
25+
#from algs4.st import ST
26+
from algs4.sequential_search_st import SequentialSearchST
27+
28+
29+
class FrequencyCounter:
30+
pass
31+
32+
if __name__ == "__main__":
33+
import sys
34+
minlen = int(sys.argv[1])
35+
st = SequentialSearchST()
36+
for line in sys.stdin:
37+
words = line.split()
38+
for word in words:
39+
40+
if len(word) < minlen:
41+
continue
42+
if not st.contains(word):
43+
st.put(word, 1)
44+
else:
45+
st.put(word, st.get(word) + 1)
46+
maxstr = ""
47+
st.put(maxstr, 0)
48+
for word in st.keys():
49+
if st.get(word) > st.get(maxstr):
50+
maxstr = word
51+
print(maxstr, " ", st.get(maxstr))

algs4/graph.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Graph:
2+
3+
def __init__(self, v):
4+
self.V = v
5+
self.E = 0
6+
self.adj = {}
7+
for v in range(self.V):
8+
self.adj[v] = []
9+
10+
def __str__(self):
11+
s = "%d vertices, %d edges\n" % (self.V, self.E)
12+
s += "\n".join("%d: %s" % (v, " ".join(str(w)
13+
for w in self.adj[v])) for v in range(self.V))
14+
return s
15+
16+
def add_edge(self, v, w):
17+
v, w = int(v), int(w)
18+
self.adj[v].append(w)
19+
self.adj[w].append(v)
20+
self.E += 1
21+
22+
def degree(self, v):
23+
return len(self.adj[v])
24+
25+
def max_degree(self):
26+
max_deg = 0
27+
for v in self.V:
28+
max_deg = max(max_deg, self.degree(v))
29+
return max_deg
30+
31+
def avg_degree(self):
32+
return 2 * self.E / self.V
33+
34+
def number_of_self_loops(self):
35+
count = 0
36+
for v in range(self.V):
37+
for w in self.adj[v]:
38+
if w == v:
39+
count += 1
40+
return count
41+
42+
if __name__ == '__main__':
43+
import sys
44+
45+
V = int(sys.stdin.readline())
46+
E = int(sys.stdin.readline())
47+
g = Graph(V)
48+
for i in range(E):
49+
v, w = sys.stdin.readline().split()
50+
g.add_edge(v, w)
51+
print(g)

algs4/sequential_search_st.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from algs4.utils.st import Node, STKeyIterator
2+
3+
4+
class SequentialSearchST:
5+
6+
def __init__(self):
7+
self.first = None
8+
self.size = 0
9+
10+
def contains(self, key):
11+
x = self.first
12+
while x:
13+
if key == x.key:
14+
return True
15+
x = x.next
16+
return False
17+
18+
def get(self, key):
19+
x = self.first
20+
while x:
21+
if key == x.key:
22+
return x.val
23+
x = x.next
24+
return None
25+
26+
def put(self, key, val):
27+
x = self.first
28+
while x:
29+
if key == x.key:
30+
x.val = val
31+
return
32+
x = x.next
33+
self.first = Node(key, val, self.first)
34+
self.size += 1
35+
36+
def delete(self, key):
37+
prev = None
38+
curr = self.first
39+
while curr:
40+
if key == curr.key:
41+
if prev:
42+
prev.next = curr.next
43+
else:
44+
self.first = curr.ext
45+
self.size -= 1
46+
prev = curr
47+
curr = curr.next
48+
49+
def keys(self):
50+
return STKeyIterator(self.first)
51+
52+
def is_empty(self):
53+
return self.size == 0

algs4/st.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
Execution: python st < input.txt
3+
Data files: https://algs4.cs.princeton.edu/35applications/tinyST.txt
4+
5+
Does not allow duplicates.
6+
"""
7+
8+
9+
class ST:
10+
11+
def put(self, key, value):
12+
pass
13+
14+
def get(self, key):
15+
pass
16+
17+
def delete(self, key):
18+
pass
19+
20+
def contains(self, key):
21+
pass
22+
23+
def is_empty(self):
24+
pass
25+
26+
def size(self):
27+
pass
28+
29+
def keys(self):
30+
pass

algs4/utils/st.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Node:
2+
3+
def __init__(self, key, val, nextItem):
4+
self.key = key
5+
self.val = val
6+
self.next = nextItem
7+
8+
9+
class STKeyIterator:
10+
11+
def __init__(self, current):
12+
self.current = current
13+
14+
def __iter__(self):
15+
return self
16+
17+
def __next__(self):
18+
if self.current is None:
19+
raise StopIteration()
20+
else:
21+
key = self.current.key
22+
self.current = self.current.next
23+
return key
24+
25+
26+
class STValueIterator:
27+
28+
def __init__(self, current):
29+
self.current = current
30+
31+
def __iter__(self):
32+
return self
33+
34+
def __next__(self):
35+
if self.current is None:
36+
raise StopIteration()
37+
else:
38+
val = self.current.val
39+
self.current = self.current.next
40+
return val

0 commit comments

Comments
 (0)