1

I am trying to make a function that takes a string(key) and returns the slot number the hash table. Such that:

for key_word in ["John","Jane"]:
    print(key_word, special_hash(key_word, 13)) 
>>> John 8 
    Jane 4

The function needs to convert each letter of the string to number form using alphabet position(eg. a=1, b= 2, c=3, etc). So the hash will be: John = 10+15+8+14= 47 -----> = 47 % tablesize(13)

6
  • What is tablesize? Commented Oct 10, 2014 at 5:28
  • do "J" and "j" hash the same? Commented Oct 10, 2014 at 5:28
  • @thefourtheye -- I think that tablesize is 13. Commented Oct 10, 2014 at 5:28
  • @mgilson But it looks like a function call. But based on the output, tablesize is 13 only I guess Commented Oct 10, 2014 at 5:29
  • no, the function needs to convert the string to lowercase, convert each letter of the string to ASCII - 96, sum those numbers up and get the remainder of the sum % table_size. I just dont know how to format it all. Commented Oct 10, 2014 at 5:30

2 Answers 2

3

You can convert the string to lowercase with lower function and iterate through the characters in the word, with a for loop, like this

def special_hash(word, tablesize):
    for char in word.lower():
        ...

Then, you can get the character code corresponding to the character with ord function.

def special_hash(word, tablesize):
    total_value = 0
    for char in word.lower():
        total_value += ord(char) - ord('a') + 1

Since we need to get the offset of the character in the alphabets, you can subtract the first value from the current value. Then finally, you can use modulo operator % to get the remainder of the division by tablesize

def special_hash(word, tablesize):
    total_value = 0
    for char in word.lower():
        total_value += ord(char) - ord('a') + 1
    return total_value % tablesize

The same can be written succintly with a generator expression and built-in sum function, like this

def special_hash(word, tablesize):
    return sum(ord(char) - ord('a') + 1 for char in word.lower()) % tablesize
Sign up to request clarification or add additional context in comments.

Comments

0

Use ord function and substract the ascii offset (a letter is 97 code, b is 98, and so on)

>>> ascii_offset = ord('a')-1 #http://www.asciitable.com/
>>> def special_hash(word, tablesize):
...     return sum([ord(c) - ascii_offset for c in word.lower() ]) % tablesize
... 
>>> special_hash('John',13)
8
>>> ##47%13 -> 8

1 Comment

Thank you. I got so many errors trying to get the structure right but that works.

Your Answer

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.