Home > Net >  Why does python return None in this instance?
Why does python return None in this instance?

Time:11-21

I have this python practice question which is to return True if a word is an isogram (word with nonrepeating characters). It is also supposed to return True if the isogram is a blank string. My answer didn't work out.

from string import ascii_lowercase
def is_isogram(iso):
    for x in iso:
        return False if (iso.count(x) > 1) and (x in ascii_lowercase) else True

#None

While another answered:

def is_isogram(word):
    word = str(word).lower()
    alphabet_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    for i in word:
        if word.count(i) > 1 and i in alphabet_list:
            return False
    return True

#True

I'm not sure why the return value is different with just a slightly different structure or is it how to return statement is defined?

CodePudding user response:

I would use a set operation. Using str.count repeatedly is expensive as you need to read the whole string over and over.

If your string only has unique characters, then its length equals that of its set of characters.

def is_isogram(iso):
    return len(set(iso)) == len(iso)

print(is_isogram('abc'))
print(is_isogram('abac'))
print(is_isogram(''))
print(is_isogram(' '))

Output:

True
False
True
True

You can easily implement additional checks. For instance, convert to unique case if the case doesn't matter. If you want to exclude some characters (e.g. spaces), pre-filter the characters iso = [x for x in iso if x not in excluded_set].

CodePudding user response:

I think the difference is that in the other code they are looping the letters in the word and return false if a false condition is met and only if they get to the end of the letters in the word without meeting a false condition they are returning true.

In your code because the return statement for any condition is in the for loop it will only check the first letter, not the rest of the world.

I tried your code and I am getting a true output unless the first letter is repeating.

Edit: I didn't cover the none type output, someone else has already commented saying that it's happening because you never enter your for loop

  • Related