[Adventurer] Hashing Magic

The new level from the Hashing series: Hashing Magic

Complete and use a hash function to place soldiers for the Magic!

2 Likes

I donā€™t know why, but I canā€™t iterate string in python

Š”трŠ¾ŠŗŠ° 8: TypeError (Š¾ŃˆŠøŠ±ŠŗŠ° тŠøŠæŠ° Š“Š°Š½Š½Ń‹Ń…): Need an object

So I change default code to

for i in range(0, len(name)):
        hash += ord(name[i])
1 Like

Iā€™ve got the same problem as @RobAnybody with the code:

# Use the hash function to find places for soldiers.
totalCells = 135

# This function hashes a string value to an integer.
def hashName(name):
    hash = 0
    for letter in name:
        hash += ord(letter)
    # The hash value should be from 0 to 134.
    # Use modulus operation to "cut" the hash value.
    hash = hash.mod(135)
    return hash

soldiers = hero.findByType("soldier")
# For each soldier say his/her name (id) and hash of it.
# The name and the number should be splitted by whitespace.
for soldier in soldiers:
    hashedName = hashName(soldier.id)
    hero.say(soldier.id + hashedName)

The error is:
Fix Your Code
Line 8: TypeError: need an object
The weird thing is that when I debug with hero.say(name) in the hashName Function it says the name of the soldier correctly.

1 Like

This code doesnā€™t even work (it produces the same ā€œNeed an objectā€ error):

for letter in "this is a string":
    hero.say(letter)

It looks like a transpiler problemā€¦


ā€¦Soon later, I found this comment inside the python-to-javascript transpiler on GitHub:

// TODO: for/in on a string should go through items, not indexes. String obj and string literal.
2 Likes

Thanks. Iā€™ve changed the sample code.

3 Likes

My apologies if this is supposed to be obvious, but I donā€™t understand what Iā€™m supposed to do when you say (line 11):

# Use modulus operation to "cut" the hash value.

I understand that there are only 135 total cells, but how am I supposed to know how high the sums from the hash function are, in order to modulus them into something in between 1 and 135? I can hack it, but I understand that thereā€™s something thatā€™s supposed to be intuitive that I missed here.

Remove 135 from hash until it will be less than 135.

For example
136 - 135 = 1 (remove once)
272 - 135 - 135 = 2 (remove twice)

Why would that be % 135 though? Shouldnā€™t % 135 be the remainder after dividing by 135?

1 Like

Sorry, there is a typo: should be ā€œmodulo operationā€.

O_o maybe hash % 135 will be enough? :wink:

1 Like