Just starting learning python and trying to use loop to write codes checking unique letters as follows:
def has_unique_letters(x):
count = 0
letters = set(x)
while count < len(x):
if x[count] in letters:
return False
count += 1
return True
However no matter what I input in x, it returns false. What's wrong with the code? Thanks!
Every letter of x
will always be contained in the set(letters of x)
, therefore your function will always return False
To solve your problem, you could verify that the length of set(x)
is equal to the length of x
:
here is why:
def has_unique_letters(x):
return len(set(x)) == len(x)
it returns True
if x contains only unique letters, and False
otherwise
If upper & lower case letters in the pw are equivalent, it is necessary to transform the input parameter to lower (or upper) case, prior to processing:
def has_unique_letters(x):
lower_x = x.lower()
return len(set(lower_x)) == len(lower_x)
[edit] placing a unique letter constraint on a password reduces the domain space; maybe it is not such a great idea.
Here is another approach:
def has_unique_letters(string):
return not bool([x for x in __import__('collections').Counter(string).values() if x > 1])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.