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 d9422c7

Browse files
cleanup
1 parent ccc905d commit d9422c7

File tree

1 file changed

+29
-17
lines changed

1 file changed

+29
-17
lines changed

‎Searching-and-sorting/hashing.py‎

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,52 @@
11

22
class HashTable(object):
3-
def __init__(self, size):
4-
self.size = size
3+
def __init__(self):
4+
self.size = 8
55
self.slots = [None] * self.size
6-
self.data = [None] * self.size
76

8-
def put(self, key, data):
7+
def put(self, key):
98
hashvalue = self.hashfunction(key, len(self.slots))
109

1110
if self.slots[hashvalue] == None:
1211
self.slots[hashvalue] = key
13-
self.data[hashvalue] = data
1412
else:
1513
if self.slots[hashvalue] == key:
16-
self.slots[hashvalue] =data
14+
pass
1715
else:
1816
nextslot = self.rehash(hashvalue, len(self.slots))
1917
while self.slots[nextslot] != None and self.slots[nextslot] != key:
2018
nextslot = self.rehash(nextslot, len(self.slots))
2119
if self.slots[nextslot] == None:
2220
self.slots[nextslot] = key
23-
self.data[nextslot] =data
21+
2422
else:
25-
self.data[nextslot] =data
23+
pass
2624

2725

2826
def hashfunction(self, key, size):
29-
return key % size
27+
consonants = 0
28+
digits = 0
29+
for x in key:
30+
if x.isdigit():
31+
digits += int(x)
32+
else:
33+
consonants += ord(x)
34+
35+
return (consonants - digits) % 8
3036

3137
def rehash(self, oldhash, size):
3238
return (oldhash + 1) % size
3339

3440
def get(self, key):
3541
startslot = self.hashfunction(key, len(self.slots))
36-
data = None
3742
stop = False
3843
found = False
3944
position = startslot
4045

4146
while self.slots[position] != None and not found and not stop:
4247
if self.slots[position] == key:
4348
found = True
44-
data = self.data[position]
49+
data = position
4550

4651
else:
4752
position = self.rehash(position, len(self.slots))
@@ -51,9 +56,16 @@ def get(self, key):
5156
return data
5257

5358
if __name__ == "__main__":
54-
h = HashTable(5)
55-
for i in range(5):
56-
h.put(i, i * 2)
57-
58-
for i in range(5):
59-
print(h.get(i))
59+
h = HashTable()
60+
h.put("3C2SE11")
61+
h.put("8B41")
62+
h.put("DE4Z23DA")
63+
h.put("J4")
64+
h.put("6GOJE45")
65+
print("Position of 3C2SE11:",h.get("3C2SE11"))
66+
print("Position of 8B41:",h.get("8B41"))
67+
print("Position of DE4Z23DA:",h.get("DE4Z23DA"))
68+
print("Position of J4:",h.get("J4"))
69+
print("Position of 6GOJE45:",h.get("6GOJE45"))
70+
71+

0 commit comments

Comments
(0)

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