Skip to content

Instantly share code, notes, and snippets.

@feulf
Created October 29, 2019 21:06
Show Gist options
  • Select an option

  • Save feulf/8217c58dc6439f4cd4712ba3e197637a to your computer and use it in GitHub Desktop.

Select an option

Save feulf/8217c58dc6439f4cd4712ba3e197637a to your computer and use it in GitHub Desktop.

Revisions

  1. feulf created this gist Oct 29, 2019.
    30 changes: 30 additions & 0 deletions hash-table.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    import hashlib

    hashed_list = [None] * 10 # create an array of None


    def key_position(key):
    string = key.encode() # convert to bytes
    hashed_key = hashlib.sha256(string) # hash the string
    hex_digest = hashed_key.hexdigest() # get the hex value
    int_digest = int(hex_digest, 16) # convert to int
    return int_digest % len(hashed_list) # run the modulo of the length of the array


    def insert(key, value):
    index = key_position(key)
    hashed_list[index] = value


    def read(key):
    index = key_position(key)
    return hashed_list[index]


    insert("Satoshi Nakamoto", "Unknown")
    insert("Federico", "5.7")
    insert("Joe", "6.1")

    print(read("Satoshi Nakamoto"))
    print(read("Federico"))
    print(read("Joe"))