Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # hash = (total number of consonants*24 + summation of the digits) %9.
- cons = "BCDFGHJKLMNPQRSTVWXYZ"
- strings = ["ST1E89B8A32", "ABCD1234", "Python!"]
- # define an empty table to hold the strings
- hashtable = [""] * 9
- for s in strings:
- # initialise total of integers, and count of consonants
- totnum, totcons = 0, 0
- for a in s: # examine each character of the given string
- if a.isdigit():
- totnum += int(a) # compute sum of integers
- if a.upper() in cons:
- totcons += 1 # count number of consonants (upper or lower case)
- # Compute the hash.
- # This will be the default position to store the string in the table
- hashpos = (totcons * 24 + totnum) % 9
- # find an empty hash table slot, cycling forwards from hashpos
- # I presume this is what they mean by "linear probing"
- while hashtable[hashpos]: # loop while indexed slot is occupied
- hashpos = (hashpos + 1) % 9
- hashtable[hashpos] = s # store the given string in the computed slot
- print(f"String {s} goes in slot index {hashpos}")
- for i, h in enumerate(hashtable):
- print(f"index: {i}: contents: {h}")
- # Output:
- # String ST1E89B8A32 goes in slot index 4
- # String ABCD1234 goes in slot index 1
- # String Python! goes in slot index 3
- # index: 0: contents:
- # index: 1: contents: ABCD1234
- # index: 2: contents:
- # index: 3: contents: Python!
- # index: 4: contents: ST1E89B8A32
- # index: 5: contents:
- # index: 6: contents:
- # index: 7: contents:
- # index: 8: contents:
Advertisement
Add Comment
Please, Sign In to add comment