Check if all items in a string are different?

Asked

Viewed 660 times

4

How can I check if all the items in a string are different ?

For example:

x:"abcdefga" = False
y:"abcdefg" = True 

Since x[0] == x[7], soon would be False.

But in case I would use that condition on a if.

Is there a function for this in python?

1 answer

7


By set theory, a data structure set does not allow repetition of elements. Therefore:

>>> x = "abcdefga"
>>> conjunto = set(x)
>>> conjunto
{'f', 'c', 'g', 'b', 'd', 'e', 'a'}

That is, if the comparison of len is equal between the string and the set, there are no repeated elements. Otherwise (set has fewer elements), there is some repetition:

len(x) == len(conjunto) # True se não há elementos repetidos. False caso contrário.
len(x) > len(conjunto) # True se há elementos repetidos. False caso contrário.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.