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.
JavaScript
x
15
15
1
firststring = input() #ahhellllloou
2
to_find = "hello"
3
4
def check_string(firststring, to_find):
5
c = 0
6
for i in firststring:
7
#print(i)
8
if i == to_find[c]:
9
c += 1
10
if c == len(to_find):
11
return "YES"
12
return "NO"
13
14
print(check_string(firststring, to_find))
15
but I don’t want to use a def
to solve the problem.
JavaScript
1
15
15
1
hello = "hello"
2
counter_hello = 0
3
bool_hello = False
4
5
for letter in string:
6
if letter == hello[counter_hello]:
7
counter_hello += 1
8
if counter_hello == len(hello):
9
bool_hello = True
10
11
if bool_hello == True:
12
print("YES")
13
else:
14
print("NO")
15
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
JavaScript
1
13
13
1
string = "ahhellllloou"
2
to_find = "hello"
3
4
match = False
5
c = 0
6
for i in string:
7
if i == to_find[c]:
8
c += 1
9
if c == len(to_find):
10
match = True
11
break
12
print("YES" if match else "NO")
13
Note that a loop isn’t needed
JavaScript
1
8
1
>>> import re
2
>>> m = re.search('.*'.join('hello'), 'ahhellllloou')
3
>>> m is not None
4
True
5
>>> m = re.search('.*'.join('hello'), 'ahhellllliu')
6
>>> m is None
7
True
8