首页 > 解决方案 > exorcism.io 中的 pangram 问题,python 跟踪,为什么我的解决方案不起作用?

问题描述

def is_pangram(sentence):
    alf = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    sentence = sentence.lower()
    for x in alf:
        if x not in sentence:
            return False
        else:
            return True

我的代码在每种情况下都没有返回 True 。

我在 exercism.io 上使用指导模式,但 python 轨道被超额订阅,只提供主要练习的反馈。

我希望这里的 python 向导可以指出我的错误。非常感谢....

标签: pythonpangram

解决方案


任务是检查句子是否包含字母表中的所有字母。因此,当您找到不在句子中的第一个字母时,您可以确定情况并非如此(即),但在您检查所有字母 之前,您不能说出相反的情况(即)。return falsereturn true

def is_pangram(sentence):
    alf = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    sentence = sentence.lower()
    for x in alf:
        if x not in sentence:
            return False
    return True

附录:还有一个仅限 python、鲜为人知且很少使用的for/else语言功能,请参阅文档for循环可能有一个else子句,当循环“正常”退出时调用(即不会由于 a 或异常而提前停止breakreturn。这使得以下代码成为可行的替代方案。else与 OP 代码相比,请注意该子句的不同缩进。

def is_pangram(sentence):
    alf = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    sentence = sentence.lower()
    for x in alf:
        if x not in sentence:
            return False
    else:
        return True

推荐阅读