shiff desta
shiff desta

Reputation: 31

Python for-loop won't iterate past first character in stirng

My python function is supposed to take an input that is a string (of only letters and only lowercase letters). The function should output true if there are no repeating letters ( regardless of whether they are consecutive letters or not) and it's suppose to return false if there are repeating letters. My code only checks if the first letter is repeating or not, but doesn't check any other letter in the string. What is the issue?

my code

Upvotes: 0

Views: 1102

Answers (4)

alexgids
alexgids

Reputation: 406

My solution

def is_isogram(x): 
    if len(str(x)) > len(set(x)): 
        return False 
    else: 
        return True

Upvotes: 0

dimitris_ps
dimitris_ps

Reputation: 5951

Try this

def is_isogram(string):
    for x in string:
        if string.count(x) > 1:
            return False
    return True

You want to return True only if you pass through all the for loop

Upvotes: 1

Tommy Orok
Tommy Orok

Reputation: 31

You're not making it past the first character because in the first iteration of the for loop, your "else" exits the function if the if statement returns false.

Upvotes: 0

Mensch
Mensch

Reputation: 700

the following should rectify.

def is_isogram(s: str):

    # loop through all unique chars
    for x in set(s):
        if s.count(x) > 1:
            return True

    # terminate after looping through all chars
    return False

additionally convert string to a set to eliminate iterating over same char twice.

Upvotes: 0

Related Questions