Reputation: 47
I am having some difficulty figuring this out. The question in my assignment asks that we:
Print the elements in the
nmrls
list that have more than or equal to 7 letters and has either the letter 'o' or the letter 'g'.
and the results should be three (eighteen
, fourteen
and twenty-one
) but I only get twenty-one.
What am I doing wrong?
Also unrelated question, do we always have to run the entire code every time we open Jupyter notebook (for a sophisticated language it seems very cumbersome)?
nmrls = inflect.engine()
x=[]
for i in range (0,22):
x.append(nmrls.number_to_words(i))
for nmrls in x:
count=0
for letter in nmrls:
count+=1
if count>=7 and "o" or "g" :
print(nmrls)
Upvotes: 0
Views: 110
Reputation: 628
This occurs because your if
statement doesn't actually check if 'o' or 'g' is in the string, but whether 'o' or 'g' exists, due to the inherent true boolean value of non-zero length strings in Python.
I would recommend reimplementing this using len():
for nmrls in x:
if len(nmrls) >= 7 and ('o' in nmrls or 'g' in nmrls):
print(nmrls)
Something similar could also be achieved using list comprehension:
x = [word for word in x if len(word) >= 7 and ('o' in word or 'g' in word)]
Upvotes: 2
Reputation: 77837
I suspect that what you need is a loop body that actually checks the word in question:
for word in x:
if len(word) >= 7 and ('o' in word or 'g' in word):
...
Upvotes: 2