Hri*_*ngh 4 python algorithm if-statement
为什么True
每次都对 if 语句进行评估,即使我故意为我的代码提供有偏见的输入。这是我的代码:
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')
Run Code Online (Sandbox Code Playgroud)
它打印YES
6 次。这是为什么?
无论何时i >= j
,您都会得到一个空字符串 for s1[i:j]
。True
检查in
另一个字符串时总是返回一个空字符串,因此您的打印语句。
相反,你应该开始j
为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')
Run Code Online (Sandbox Code Playgroud)
这没有输出。
空字符串总是被认为是任何其他字符串的子字符串,所以 "abc" 中的 "" 将返回 True。