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

Python: print the longest word in a sentence that contains the letter "a" or "A"

If there is no word contains "a" or "A" in a sentence, print -1.

Here is my code, I can print the words if they contain "a" or "A", but if not I can’t manage to print -1 out.

Where should I change?

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

def newsentence ():
    letters = set('aA')
    new_ls = [word for word in sentence if letters & set(word)]
    return new_ls

def findlongest ():
    if 'a' or 'A' in sentence: 
        longest = max(newsentence(), key=len)
    else:
        longest== -1
    return(longest)
    
sentence = list(input().split())
print(findlongest())

>Solution :

The newsentence will return an empty array if there is no a or A. Please change the code to below. It should work. As @Tomer said, you also need to change == to = as well

def newsentence ():
    letters = set('aA')
    new_ls = [word for word in sentence if letters & set(word)]
    return new_ls

def findlongest ():
    if 'a' or 'A' in sentence: 
        if newsentence():
            longest = max(newsentence(), key=len)
        else:
            longest = -1
    return(longest)

sentence = list(input().split())
print(findlongest())

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