Why the if statement being evaluated to True
each time, even if I am deliberately giving biased inputs to my code . Here is my code:
s1 = 'efgh'
s2 = 'abcd'
for i in range(0, len(s1)):
for j in range(1, len(s1)+1):
if s1[i:j] in s2:
print('YES')
It print YES
, 6 times. Why is that?
Whenever you have i >= j
, you will get an empty string for s1[i:j]
. An empty string always returns True
when checking in
another string, hence your print statements.
Instead you should start j
as i + 1
:
s1 = 'efgh'
s2 = 'abcd'
for i in range(0,len(s1)):
for j in range(i + 1,len(s1)+1):
if s1[i:j] in s2:
print('YES')
Which gives no output.
Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.
Docs source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With