0

okay this is the question that ive got

write a function search_word(sentence, word) that takes in two parameters. The function searches the sentence for that word and returns the number of occurrence which the word appears in it

Ive already tried all sorts, sorry im new to python and im tryna solve a problem statement however from the problem statement i dont get why

def search_word(sentence, word):
    sentence = sentence.split()
    count = 0
    for words in sentence:
        if word == words:
            count += 1
            return count


print(search_word("sunny rainy sunny windy", "sunny"))

the following outputs should show like this

>>>search_word("sunny rainy sunny windy", "sunny")
   2
>>>search_word("school holiday is over", "weekend")
   0

but what i got was

>>>search_word("sunny rainy sunny windy", "sunny")
   1
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
Rafie Suib
  • 79
  • 1
  • 5

3 Answers3

1

You're putting return count inside the for loop - the very first time "sunny" is found in the sentence, it increments the count and immediately returns that (so it'll always return 1). To fix, just de-indent that line:

def search_word(sentence, word):
    sentence = sentence.split()
    count = 0
    for words in sentence:
        if word == words:
            count += 1
    return count

This makes it so that the return statement will only execute after all the words in sentence have been examined, and not before.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • wow thats amazing i posted this question and 5 minutes late i found the problem and the answer to my problem thank you guys so much – Rafie Suib Jul 29 '19 at 15:24
0

Try this:

def search_word(sentence, word_to_search):
    return len([word for word in sentence.split(' ') if word_to_search in word])
Carsten
  • 2,765
  • 1
  • 13
  • 28
  • 1
    I wonder why this has been downvoted... voted up! Please add some comment to explain why... – Hitmands Jul 29 '19 at 15:23
  • Thank you guys so much for helping:)! – Rafie Suib Jul 29 '19 at 15:25
  • @Hitmands while this answer does provide a working solution to the surface-level problem, it provides no explanation of *why* it works, and takes an entirely different approach to OP's code without actually fixing the underlying problem if it happens in the future. – Green Cloak Guy Jul 29 '19 at 15:25
  • I agree on spending some more effort in describing the solution, we should do the same for downvoting though. This perfectly answers the questions and SO is not a fixing-the-code community... array comp is a different approach, but still represent a great info for the OP and future readers. – Hitmands Jul 29 '19 at 15:29
0

something as easy as this could work:

sentence = "sunny rainy sunny windy"
sunny = list(filter(lambda w: w == "sunny", sentence.split()))
count = len(sunny);

print(count)
Hitmands
  • 13,491
  • 4
  • 34
  • 69