做一个练习CheckIO
,我想知道为什么这不起作用。给定一组字符串,如果任何字符串是集合中任何其他字符串的后缀,我将尝试返回 True。否则为假。使用 itertools 我首先在元组中生成必要的排列。然后对于每个元组(每个 i),我想看看第二个元组是否在第一个元组的末尾(选项 1)。另一种方法是使用 .endwith 函数(选项2),但两者都不适合我。为什么这两个选项有缺陷?
import itertools
def checkio(words_set):
for i in itertools.permutations(words_set, 2):
#option1 ---- if i[1] in i[0][-len(i[1]):]:
#option2 ---- if i[0].endswith(i[1]):
return True
else:
return False
例子:
checkio({"hello", "lo", "he"}) == True
checkio({"hello", "la", "hellow", "cow"}) == False
我知道这可以作为答案。但只是想知道为什么我原来的方法不会采用。
def checkio(words_set):
for w1 in words_set:
for w2 in words_set:
if w1.endswith(w2) and w1 != w2:
return True
return False