acclivity

pyComputeStringHash

Aug 8th, 2022 (edited)
919
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. # hash =  (total number of consonants*24 + summation of the digits) %9.
  2.  
  3. cons = "BCDFGHJKLMNPQRSTVWXYZ"
  4. strings = ["ST1E89B8A32", "ABCD1234", "Python!"]
  5.  
  6. # define an empty table to hold the strings
  7. hashtable = [""] * 9
  8.  
  9. for s in strings:
  10.     # initialise total of integers, and count of consonants
  11.     totnum, totcons = 0, 0
  12.  
  13.     for a in s:             # examine each character of the given string
  14.         if a.isdigit():
  15.             totnum += int(a)    # compute sum of integers
  16.         if a.upper() in cons:
  17.             totcons += 1        # count number of consonants (upper or lower case)
  18.  
  19.  
  20.     # Compute the hash.
  21.     # This will be the default position to store the string in the table
  22.     hashpos = (totcons * 24 + totnum) % 9
  23.  
  24.     # find an empty hash table slot, cycling forwards from hashpos
  25.     # I presume this is what they mean by "linear probing"
  26.     while hashtable[hashpos]:   # loop while indexed slot is occupied
  27.         hashpos = (hashpos + 1) % 9
  28.  
  29.     hashtable[hashpos] = s      # store the given string in the computed slot
  30.  
  31.     print(f"String {s} goes in slot index {hashpos}")
  32.  
  33. for i, h in enumerate(hashtable):
  34.     print(f"index: {i}: contents: {h}")
  35.    
  36. # Output:
  37. # String ST1E89B8A32 goes in slot index 4
  38. # String ABCD1234 goes in slot index 1
  39. # String Python! goes in slot index 3
  40. # index: 0: contents:
  41. # index: 1: contents: ABCD1234
  42. # index: 2: contents:
  43. # index: 3: contents: Python!
  44. # index: 4: contents: ST1E89B8A32
  45. # index: 5: contents:
  46. # index: 6: contents:
  47. # index: 7: contents:
  48. # index: 8: contents:
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
Advertisement
Add Comment
Please, Sign In to add comment