Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning empty list

Hi I have problem with my program, I try to check which letters in alphabet doesn’t appear in list, unluckily it returns empty list I don’t know why

I tried many ways but it still doesn’t work…

import string
def get_missing_letters(s):
    missing =[]
    alphabet = list(string.ascii_lowercase)
    s = list(s)
    for letter in s:
        if letter not in alphabet:
            missing.append(letter)
        return missing
print(get_missing_letters("abcdefgpqrstuvwxyz"))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have two issues, the return happens after the first iteration and you are actually checking if the letters in your string exists in ascii_lowercase instead of the opposite

def get_missing_letters(s):
    missing = []
    s = list(s)
    for letter in list(string.ascii_lowercase):
        if letter not in s:
            missing.append(letter)
    return missing


print(get_missing_letters("abcdefgpqrstuvwxyz"))
# ['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']

Another way to find the diff is to use set

def get_missing_letters(s):
    return set(string.ascii_lowercase).difference(s)
    # or
    return set(string.ascii_lowercase) - set(s)

print(get_missing_letters("abcdefgpqrstuvwxyz"))
# {'j', 'n', 'k', 'l', 'i', 'm', 'o', 'h'}

You can sort it if the order is important to you

def get_missing_letters(s):
    missing = set(string.ascii_lowercase).difference(s)
    return sorted(missing)


print(get_missing_letters("abcdefgpqrstuvwxyz"))
# ['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading