+ 4

The "search engine" in Python for beginners"

Good evening (in my time zone 😁). Has anyone an idea why my code doesn't work? It should recognize if the input word1 is within the input text1, where len(text1) >= len(word1). Thank you. def search(text,word): txt = len(text) wrd = len(word) ret = "Word not found" for i in range(txt - wrd): if word == text[i:i + wrd - 1]: ret = "Word found" return ret # main: text1 = input() word1 = input() print(search(text1, word1))

7th Aug 2021, 6:16 PM
Martin
7 Answers
+ 2
The way you are solving works fine but there are some logical errors like the range should be (txt-wrd+1) and "if word==text[i:i+wrd]". And i just used print statement to understand what was wrong with it .
7th Aug 2021, 6:59 PM
Abhay
Abhay - avatar
+ 2
I post easier solutions. Using lambdas: text = input() word = input() search = lambda text, word : 'Word found' if word in text else 'Word not found' print(search(text, word)) Without lambdas: text = input() word = input() def search(text,word): return 'Word found' if word in text else 'Word not found' print(search(text, word))
20th Aug 2021, 10:16 AM
David GarcĂ­a Prados
+ 1
Wow, it seems to be pretty easy and more handsome than my code. Anyway, immagine I must use the string slicing way for solving the problem for some reason (just immagine this, in reality I don't have to) - is it solvable my way?
7th Aug 2021, 6:33 PM
Martin
+ 1
To Abhay: yes, this is the answer I was looking for - it points at the errors in the logic of my idea. Thank you so much. M.
10th Aug 2021, 6:10 PM
Martin
+ 1
Hi David! Yes, when I did my walkrhrough of the topic last week, I came to the same conclusion. It is funny that what I felt like studying 'quantum physics' 3 weeks ago I consider an easy high school home work only a week ago 😊. My gratitude to 'SoloLearn' and all its users willing to help.
26th Aug 2021, 12:21 PM
Martin
+ 1
U know, the result I keep getting is Word found none, Word not found none
23rd Jul 2022, 5:26 PM
George Ajuwa