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

Viewed 64

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?

3 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

Because some combinations produce the empty string:

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', i, j, repr(s1[i:j]))

Output:

YES 1 1 ''
YES 2 1 ''
YES 2 2 ''
YES 3 1 ''
YES 3 2 ''
YES 3 3 ''

It can also be helpful to see all cases - there are plenty of times when the if condition doesn't pass:

s1 = 'efgh'
s2 = 'abcd'

for i in range(0, len(s1)):
    for j in range(1, len(s1) + 1):
        print(s1[i:j] in s2, i, j, repr(s1[i:j]))

Output:

False 0 1 'e'
False 0 2 'ef'
False 0 3 'efg'
False 0 4 'efgh'
True 1 1 ''
False 1 2 'f'
False 1 3 'fg'
False 1 4 'fgh'
True 2 1 ''
True 2 2 ''
False 2 3 'g'
False 2 4 'gh'
True 3 1 ''
True 3 2 ''
True 3 3 ''
False 3 4 'h'

The IF condition is not being evaluated to True, all the time. This happens because in some of your loops, i >= j. And when this happens, s1[i:j] would return an empty string as ''.

In your if condition, you check whether, s1[i:j] is contained in s2. According the above scenario, you will be checking whether s1[i:j] (which is an empty String), is contained in s2.

By default, every String has an empty string in it. This is like checking the following,

if '' in s2: # this is always true

According to your code s1 does not contain any characters, that is also contained in s2. Hence, this would only happen when i >= j.

Related