1
\$\begingroup\$

I just want your opinion about that code! :)

import random
class Error(Exception):
 def __init__(self, error=None):
 self.error = error
 def __str__(self):
 return str(self.error)
class HashTable(object):
 def __init__(self):
 self.length = 20
 self.keys = []
 self.table = [[] for _ in range(self.length)]
 def __len__(self):
 return self.length
 def __setitem__(self, key, value):
 self.keys.append(key)
 hashed_key = self._hash(key)
 self.table[hashed_key].append((value)) #Wartosc jest dodawana do listy pod hashowanym indeksem
 
 def _hash(self, key) :
 return hash(key) % self.length
 
 def show_list(self):
 return self.table
 
 def __getitem__(self, key):
 for el in self.table[self._hash(key)]:
 if el[0] == key:
 return el[1]
 
 def __delitem__(self, key):
 for el in self.table[self._hash(key)]:
 if el[0] == key:
 self.table[self._hash(key)].remove(el)
 
 def __iter__(self):
 def Generator(data):
 mylist = [_ for _ in data]
 for i in mylist:
 yield i
 return Generator(self.table)
 
L = HashTable()
content = []
with open("song.txt", 'r', encoding = 'utf8') as travis:
 for line in travis:
 for word in line.split():
 content.append(word)
for c in content:
 L[c] = c
 
for x in L:
 print(x)

I've also will be really greateful for any tips and how to improve this one! :D

Reinderien
70.9k5 gold badges76 silver badges256 bronze badges
asked Jun 28, 2021 at 13:39
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I'm going to assume that you're not using a built-in dictionary for learning purposes etc., but that would greatly simplify this code. \$\endgroup\$ Commented Jun 29, 2021 at 14:40

1 Answer 1

1
\$\begingroup\$

My opinion is that you should test better, before asking for code review.

line = " #Wartosc jest dodawana do listy pod hashowanym indeksem"
for word in line.split():
 content.append(word)
for c in content:
 L[c] = c
print(L["jest"])

Put a print statement inside each of your functions, for example print('__getitem__ ran'). Then keep modifying your test code until you see all of them. Right now you are not using all your methods.

Edit: Also, this is not really something I will code review once tested. The correct review is to replace it with:

HashTable = dict

Both the readability and efficiency are miles better than yours!

answered Sep 1, 2021 at 9:18
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.