Well, you could use len(word)
to get the length of the word, right?
Also, a set is a container of unique values. That is, you can’t have the same value in a set more than once.
You can also pass a string into a set to fill the set with unique characters in the string.
Finally, you can take len(set)
to get the number of unique items in the set.
So, if you add that all together:
>>> word = “CATT”
>>> len(word)
4
>>> my_set = set(word)
>>> my_set # Sets aren’t ordered, so it will probably come back in a different order
{‘T’, ‘A’, ‘C’}
>>> len(my_set)
3
Huh, 3 != 4
, right? It looks like in taking the unique values in “CATT”, you had to throw one of them away because it was duplicated. Hey, convenient! So the short version is:
word = “CATT”
if len(word) != len(set(word)):
print(word, “has duplicate letters”)
Oh, and because this might answer your next question:
If you have two sets A
and B
, A <= B
is True if and only if every item in A
is also in B
. For example:
>>> {1,2,3} <= {1,2,3,4}
True
>>> {1,2,3,4} <= {1,2,3}
False
Well, that’s handy, because you can spell a word with a list of letters if and only if every letter in the word is also in the list of letters, right? And that looks a whole lot like the definition of A <= B
! And indeed, it is:
>>> letters = [‘a’, ‘b’, ‘c’, ‘t’]
>>> set('cat') <= set(letters)
True
>>> set('dog') <= set(letters)
False
Convenient, isn’t it?