-
Notifications
You must be signed in to change notification settings - Fork 0
/
L18Q26_AddingKeywords.py
51 lines (45 loc) · 1.39 KB
/
L18Q26_AddingKeywords.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Define a procedure,
#
# hashtable_add(htable,key,value)
#
# that adds the key to the hashtable (in
# the correct bucket), with the correct
# value and returns the new hashtable.
#
# (Note that the video question and answer
# do not return the hashtable, but your code
# should do this to pass the test cases.)
def hashtable_add(htable,key,value):
bucket = hash_string(key,len(table))
#print 'bucket number', bucket
htable[bucket].append([key,value])
return htable
def hashtable_get_bucket(htable,keyword):
return htable[hash_string(keyword,len(htable))]
def hash_string(keyword,buckets):
out = 0
for s in keyword:
out = (out + ord(s)) % buckets
return out
def make_hashtable(nbuckets):
table = []
for unused in range(0,nbuckets):
table.append([])
return table
table = make_hashtable(3)
hashtable_add(table,'udacity',23)
hashtable_add(table,'udacious',24)
print hashtable_get_bucket(table,'udacious')
#table = make_hashtable(5)
'''
hashtable_add(table,'Bill', 17)
hashtable_add(table,'Coach', 4)
hashtable_add(table,'Ellis', 11)
hashtable_add(table,'Francis', 13)
hashtable_add(table,'Louis', 29)
hashtable_add(table,'Nick', 2)
hashtable_add(table,'Rochelle', 4)
hashtable_add(table,'Zoe', 14)'''
print table
#>>> [[['Ellis', 11], ['Francis', 13]], [], [['Bill', 17], ['Zoe', 14]],
#>>> [['Coach', 4]], [['Louis', 29], ['Nick', 2], ['Rochelle', 4]]]