Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hash #33

Open
kostyria opened this issue Apr 16, 2023 · 0 comments
Open

Hash #33

kostyria opened this issue Apr 16, 2023 · 0 comments

Comments

@kostyria
Copy link
Owner

kostyria commented Apr 16, 2023

class HashTable:
def init(self, size):
self.elems = [None] * size
self.size = size

def hash(self, key):
    return key % self.size

def add(self, value):
    hash = self.hash(value)
    if self.elems[hash] is None:
        self.elems[hash] = value
    else:
        i = 1
        while True:
            index = (hash + i) % self.size
            if self.elems[index] is None:
                self.elems[index] = value
                break
            i += 1

def print_ht(self):
    output = []
    for i in range(self.size):
        if self.elems[i] is not None:
            output.append(f"{i} -> {self.elems[i]}")
        else:
            output.append(f"{i} -> ")
    print("\n".join(output))

ht = HashTable(10)
ht.add(13)
ht.add(73)
ht.add(23)
ht.add(14)
ht.print_ht()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant