Checking repeated character in Python list

Asked

Viewed 248 times

0

Hello!

I’m trying to develop a program that reads a string and returns a boolean if there are repeated characters.

I need enough on that score:

("") // False  
("oo") // False  
("po") // True
("EEEttOo") // False  
("PoiX2@op") // False  
("PoiX2@aP") // False
("PoiX2@p@") // False
("PoiX2@2pa") // False
("PoiX2@pa") // True

I thought it would be easier to work with string, passing it to a list and doing a check with for and if however, I’m not able to develop a valid logic.

s = 'Banana'

listastr = list(s)
out = True

Could someone give me a light on how to solve?

I am basing that "p" is different from "P" and the fact that " has given False, is due to the system requiring an entry.

In my system, I’m using Regex, so it searches for the characters [a-z],[A-Z],[0-9] and some special characters.

  • Implies that if a string has no duplicates it returns Trueand if you have duplicates returns False. In "" the empty string does not contain duplicates and returns False and in "PoiX2@pa" the string has a repeat of p, one uppercase and one lowercase, and return True. These results are correct?

  • Yes, I am basing that "p" is different from "P" and the fact that " has given False, is due to the system requiring an input. In my system, I’m using Regex, so it searches for the characters [a-z],[A-Z],[0-9] and some special characters. Since I haven’t found any regular expression that doesn’t accept character repetition that works, I’m looking for an alternative by for and if.

2 answers

1

To search for the occurrence of a character pattern in a string use a regular expression.

The pattern (?P<char>.).*?(?P=char) means:

  • (?P<char>.) setting up a catch group, identified as char, corresponding to any character.
  • .*? corresponds to zero or more of any characters.
  • (?P=char) matches the first character matched by the capture group char.

The algorithm is simple it uses the method re.compile() to compile the pattern (?P<char>.).*?(?P=char). Defines the function permitido(s) that accepts a string s as a parameter, this function first tests whether s is empty or composed of returning spaces Fase if the test is affirmative and then make a search with search() by the first occurrence of the pattern returns a Boolean based on the search result compared to equality with None.

Example:

import re                                              #Importa o módulo re para trabalhar com regex.

regex = re.compile(r'(?P<char>.).*?(?P=char)', re.I)   #Compila uma expressão regular para servir como padrão de busca.

def permitido(s):
    if s.strip() == "": return False                   #Se a string for vazia ou composta por espaços retorna False.
    return regex.search(s) == None                     #Busca por correspondência do padrão em s e testa igualdade com None e retorna o resultado desse teste. 
    
print(permitido('Banana'))   # False
print(permitido(""))         # False  
print(permitido("oo"))       # False  
print(permitido("po"))       # True
print(permitido("EEEttOo"))  # False  
print(permitido("PoiX2@op")) # False  
print(permitido("PoiX2@aP")) # False
print(permitido("PoiX2@p@")) # False
print(permitido("PoiX2@2pa"))# False
print(permitido("PoiX2@pa")) # True
  • Very interesting!!! what I really needed, is to use Regex, because my system has a password check. Requiring a minimum of characters, 1 upper case, 1 lower case, 1 number and 1 special character. These characters should not be repeated. I found a regular expression that meets these requirements, with the exception of character repetition. ^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[!@#$%^&()+-])[A-Za-z d!@#$%^&()+-]{9,}$ Do you know how I insert in this regular expression, not to repeat characters? In this case I consider that "p" is different from "P".

  • @Alanbertoldo I suggest you use the 2 things: first you check if you have a repeated character (using what was proposed here or in my reply), and then, if it is ok, you use this other regex p/ check the password. Doing everything the same is enough, but I think it’s complicated enough :-) Anyway, if one of the answers solved your problem, you can choose the one that best solved it and accept it, see here how and pq do it. It is not mandatory, but it is a good practice of the site, p/ indicate to future visitors that it solved

  • Another alternative is to use "normal" groups (no name): re.compile(r'(.).*?\1')

  • @Alanbertoldo, always make the simplest, in this case the simplest is to have a function for each activity. A function that checks if password is allowed, another function that checks if it meets the requirements, a function that checks the resilience of the password and another function to then know if it is valid. In my view testing if the password has 1 uppercase, 1 lowercase, 1 number and 1 special character is already another activity so another question. If you ask this new question do not hesitate to mark me there that I leave for sure a specific answer to this other problem.

  • 1

    @Augustovasques thanks for the explanation!!! Once I’m done, I’ll post the result! Gratitude

1


An alternative is to create a set from the string. As a set does not allow duplicated elements, its size will be smaller if the string has some repeated character:

def permitido(s):
    if not s: # se a string é vazia, retorna False
        return False
    return len(s) == len(set(s))
 
print(permitido('Banana'))   # False
print(permitido(""))         # False  
print(permitido("oo"))       # False  
print(permitido("po"))       # True
print(permitido("EEEttOo"))  # False  
print(permitido("PoiX2@op")) # False  
print(permitido("PoiX2@aP")) # False
print(permitido("PoiX2@p@")) # False
print(permitido("PoiX2@2pa"))# False
print(permitido("PoiX2@pa")) # True

I only had to include a check at the beginning for the empty casyde string. If it is not empty, then create the set, and if it is the same size as the string it is because there are no repeat characters.

  • Show! I was not able to develop a logic that arrived at it, as I am beginner in python, I get lost sometimes. I saw that there is a lot about repetition checking for integer numbers, where an input is added and checks for an if, but I did not find about characters that worked as desired!

Browser other questions tagged

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