Finding a ‘hello’ word in a different string, which it has ‘hello’ in it I should find a ‘hello’ word in a string, which I gave it from input too .I wrote this code by looking at the answer that someone gave to the below link’s question.
firststring = input() #ahhellllloou to_find = "hello" def check_string(firststring, to_find): c = 0 for i in firststring: #print(i) if i == to_find[c]: c += 1 if c == len(to_find): return "YES" return "NO" print(check_string(firststring, to_find))
but I don’t want to use a def
to solve the problem.
hello = "hello" counter_hello = 0 bool_hello = False for letter in string: if letter == hello[counter_hello]: counter_hello += 1 if counter_hello == len(hello): bool_hello = True if bool_hello == True: print("YES") else: print("NO")
for hello
string it works correct. also for pnnepelqomhhheollvlo
.
but when I give it ahhellllloou
it doesn’t work.
I can’t see where the bug is.
Advertisement
Answer
Your code is not the same. The return statement needs to be accounted for by breaking the loop
string = "ahhellllloou" to_find = "hello" match = False c = 0 for i in string: if i == to_find[c]: c += 1 if c == len(to_find): match = True break print("YES" if match else "NO")
Note that a loop isn’t needed
>>> import re >>> m = re.search('.*'.join('hello'), 'ahhellllloou') >>> m is not None True >>> m = re.search('.*'.join('hello'), 'ahhellllliu') >>> m is None True