The new level from the Hashing series: Hashing Magic
Complete and use a hash function to place soldiers for the Magic!
The new level from the Hashing series: Hashing Magic
Complete and use a hash function to place soldiers for the Magic!
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])
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.
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.
Thanks. Iāve changed the sample code.
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?
Sorry, there is a typo: should be āmodulo operationā.
O_o maybe hash % 135
will be enough?