Search code examples
pythonfor-loopduplicatesboolean-expression

How to find duplicates in a string


I am working on creating a world game, and I do not want my game to accept duplicate input's by the user, ex: 'mirror'.

I tried finding the duplicates one way but it didn't work, and I do not know how to make my program realize that the inout is a duplicate.

this is my non working code:

def checkForDuplicates(userWord):
 


    duplicates=[]

    
            return True
        

I tried setting this statement to true, if any duplicates where found but it didn't work, I was expecting the function to check the users word for duplicate letters, and If there are duplicates the function returns True if not the function returns False.

this is also python programming language



Solution

  • The issue here is your return statement is nested inside of your for loop so it will always return after checking the first letter. You could move the return into an else statement so that it returns True after the first duplicate letter is found and then put return False after it gets all the way through the for loop without hitting any duplicates. (without the return False it would return None which also is a falsey value)

    • note: I changed the capitalization to fit Python standards

    Here is a working runnable example

    #!/usr/bin/env python
    
    def check_for_duplicates(user_word):
        duplicates=[]
        for dup in user_word:
            if dup not in duplicates:
                duplicates.append(dup)
            else:
                return True
        return False
    
    print(f'{check_for_duplicates("mirror")=}')
    print(f'{check_for_duplicates("marine")=}')
    <script src="https://modularizer.github.io/pyprez/pyprez.min.js" theme="darcula"></script>