简体   繁体   中英

Ensuring that each letter appears only once in the password

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:

  1. A set is a collection of unique objects.
  2. The set of the elements of x, is the collection of the unique elements composing x.
  3. Therefore, if x is composed exclusively of unique elements, the cardinality of the set of the elements of x will be equal to the total number of elements composing x.

def has_unique_letters(x):
    return len(set(x)) == len(x)

it returns True if x contains only unique letters, and False otherwise

[edit] - question about indifference to lower/upper case:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM