Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the IF condition being evaluated to True all the time

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?

like image 966
DrDoggo Avatar asked Jan 25 '23 01:01

DrDoggo


1 Answers

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

like image 195
Joe Iddon Avatar answered Jan 28 '23 12:01

Joe Iddon