1

做一个练习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
4

3 回答 3

1

return False应该在 for 循环的末尾,否则该函数将在每次第一次比较时返回 True/False,并将忽略所有后续比较:

import itertools

def checkio(words_set):
    for i in itertools.permutations(words_set, 2):
        if i[0].endswith(i[1]):
            return True

    return False
于 2015-04-23T19:40:42.707 回答
0

这是因为您return False在第一次检查之后。如果它失败了,它会返回False,你需要把它从你的for循环中拿出来!

但是作为一种更 Pythonic 的方式,您可以combinations在函数中使用和生成器表达式any

>>> from itertools import combinations
>>> s={"hello", "lo", "he"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s,2)))
True
>>> s2={"hello", "la", "hellow", "cow"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s2,2)))
False
于 2015-04-23T19:39:25.840 回答
0

既然是练习题,我就不给你完整的答案了,但是你确定你真的要return Falseelse子句中加入吗?

于 2015-04-23T19:39:40.977 回答