You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The same is true for a set. To avoid this, you should convert the key to an immutable type (i.e., a string).
defhas_duplicates(t):
"""Checks whether any element appears more than once in a sequence. Simple version using a for loop. t: sequence """d= {}
forxint:
ifstr(x) ind:
returnTrued[str(x)] =TruereturnFalse
I don't even know if there is a fix for the second version has_duplicates2.
The text was updated successfully, but these errors were encountered:
Good point. As you said, this function will only work if the items in the sequence are hashable. Converting them to strings is not a bad idea, but it introduces the unexpected behavior that the integer 1 and the string '1' would be considered duplicates. So it might be best to change the specification of the function to indicate that it is only expected to work if the items are hashable.
The two implementations of has_duplicates (https://github.com/AllenDowney/ThinkPython2/blob/master/code/has_duplicates.py) contain a bug when called with specific arguments. Since dictionary keys must be immutable (hashable types), if we pass a nested list as an argument, both functions will crash:
The same is true for a
set.
To avoid this, you should convert the key to an immutable type (i.e., a string).I don't even know if there is a fix for the second version
has_duplicates2.
The text was updated successfully, but these errors were encountered: