Reputation: 75
I'm supposed to:
"Write a function search(words, start_chs)
that returns a list of all words in the list words whose first letter is in the list start_chs
.
If either words or start_chs
is empty, return an empty list.
Since the returned list can have many words in it, the words should be arranged in the order that they originally appeared in."
e.g.
words = ['green', 'grasses', 'frolicking', 'cats', '', 'kittens', 'playful']
start_chs = ['a', 'c', 'g']
new_words = search(words, start_chs) # ['green', 'grasses', 'cats']
My code thus far is below, however, it doesn't return all the correct outputs, only some of them.
def search(words, start_chs):
k=0
p=[]
if (len(words)== 0) or (len(start_chs)== 0):
return ([])
while k < len(start_chs):
if start_chs[k][0] == words[k][0]:
p.append(words[k])
k+=1
return(p)
Upvotes: 0
Views: 81
Reputation: 9051
Try this:
def search(words, start_chs):
start_chs = tuple(start_chs)
return [word for word in words if word.startswith(start_chs)]
words = ['green', 'grasses', 'frolicking', 'cats', '', 'kittens', 'playful']
start_chs = ['a', 'c', 'g']
new_words = search(words, start_chs)
#['green', 'grasses', 'cats']
Upvotes: 0
Reputation: 41
The problem with the code that you wrote is that you are only checking with the character at the corresponding index of the word. So you can use in
in place of this.
def search(words, start_chs):
k=0
p=[]
if (len(words)== 0) or (len(start_chs)== 0):
return []
for i in words:
if i[0] in start_chs:
p.append(i)
k+=1
return p
Upvotes: 1
Reputation: 131
It should looks like that. It's bad practice to use iterate list with index, use for element in list
instead.
About your code, why it's not working. It's because you should iterate over whole list. In this example you only check if 'a'
equal first letter in 'green'
, 'c'
in 'grasses'
and 'g'
in 'frolicking'
.
words = ['green', 'grasses', 'frolicking', 'cats', '', 'kittens', 'playful']
start_chs = ['a', 'c', 'g']
def search(words, start_chs):
result = []
if len(words)== 0 or len(start_chs)== 0:
return []
for word in words:
if word and word[0] in start_chs:
result.append(word)
return result
print(search(words, start_chs))
Upvotes: 1
Reputation: 1672
You can try this:-
def search(words, start_chs):
res = []
for word in words:
if word!='' and word[0] in start_chs:
res.append(word)
return res
search(words, start_chs)
output:
['green', 'grasses', 'cats']
Upvotes: 1