更一般的帮助,我相信我应该使用“ map(lambda ....)”-

时间:2018-12-02 22:56:41

标签: python string lambda

# check if string is panagram (phrase which contains every letter of the
# alphabet)

def panagram_check(str0, alphabet=string.ascii.lowercase):

        alltrues = [True,True,True,True,True,True,True,True,True,True,
                    True,True,True,True,True,True,True,True,True,True,
                    True,True,True,True,True]

        # so let's build this list...

        list_of_bools = []

        for achar in alphabet:

            for bchar in str0:
                if achar != bchar:
                    zerocheck = False

                else:  zerocheck = True

            list_of_bools = list_of_bools+zerocheck

        return (list_of_bools==alltrues)

这将返回错误“未定义名称字符串”,这也使我感到困惑 但是,如果lambda表达式可以帮助您实现这一目标并不难看,那么有什么线索吗?

2 个答案:

答案 0 :(得分:0)

import string

def panagram_check(str0, alphabet=string.ascii.lowercase):
    return set(str0.lower()) & set(alphabet) == set(alphabet)

答案 1 :(得分:0)

您可以使用ascii_lowercase检查短语中每个字母(all)是否都在短语中:

import string


def panagram_check(phrase, alphabet=string.ascii_lowercase):
    uniques_letters_in_phrase = set(phrase.lower())
    return all(letter in uniques_letters_in_phrase for letter in alphabet)


print(panagram_check("Two driven jocks help fax my big quiz.​"))
print(panagram_check("Not a panagram"))

输出

True
False

语句:uniques_letters_in_phrase = set(phrase.lower())将短语转换为集合,目的是加快可容纳性检查。请注意,您必须导入字符串才能访问ascii_lowercase