Advertisement
BenTibnam

Summation of ASCII Codes Hash Function

Aug 5th, 2023 (edited)
1,407
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | Software | 0 0
  1. def hash(st):
  2.     st_len = len(st)
  3.    
  4.     # if there is no text we can return -1 since that's an invalid hash
  5.     if st_len == 0:
  6.         return -1
  7.    
  8.     # dif has is used to offset the has so input like 'a' would go into bucket 0
  9.     dif_hash = ord('a')
  10.  
  11.     # if the length is only one we don't need to get the summation of characters 1 to st_len
  12.     if st_len == 1:
  13.         return ord(st) - dif_hash
  14.     else:
  15.         # calculating the summation of the strings ascii values
  16.         #  word[0] + Σ i=1, i < st_len - 'a' ascii value
  17.         summation = 0
  18.         for i in range(1, st_len):
  19.             summation += ord(st[i])
  20.         return ord(st[0]) + summation - dif_hash
  21.  
  22. while True:
  23.     st = input(">>> ")
  24.     hash_code = (hash(st))
  25.     print(hash_code)
  26.    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement