我想创建一个将字符串作为输入并检查字符串是否为pangram的函数(pangram是一段包含字母表中每个字母的文本)。

我编写了下面的代码,该代码有效,但是我正在寻找一种替代方法,希望是一种简化的方法。

import string

def is_pangram (gram):
    gram = gram.lower()
    gram_list_old = sorted([c for c in gram if c != ' '])
    gram_list = []
    for c in gram_list_old:
        if c not in gram_list:
            gram_list.append(c)
    if gram_list == list(string.ascii_lowercase): return True
    else: return False

我觉得这个问题可能违反了本网站的规定,但希望并非如此。我只是很好奇,希望看到其他方法来做到这一点。

最佳答案

is_pangram = lambda s: not set('abcdefghijklmnopqrstuvwxyz') - set(s.lower())

>>> is_pangram('abc')
False
>>> is_pangram('the quick brown fox jumps over the lazy dog')
True
>>> is_pangram('Does the quick brown fox jump over the lazy dog?')
True
>>> is_pangram('Do big jackdaws love my sphinx of quartz?')
True



说明

使用“lambda”是创建函数的一种方式,因此它相当于写一行def的一行,例如:
 def is_pangram(s):
     return not set('abcdefghijklmnopqrstuvwxyz') - set(s.lower())
set()创建一个数据结构,该数据结构中不能包含任何重复项,这里:
  • 第一组是(英文)字母,小写
  • 第二组是测试字符串中的字符,也是小写。而且所有重复项也都消失了。

  • 减去set(..) - set(..)之类的东西将返回第一组的内容,减去第二组的内容。 set('abcde') - set('ace') == set('bd')

    在此pangram测试中:
  • 我们使测试字符串中的字符远离字母
  • 如果什么都没有了,则测试字符串包含字母表中的所有字母,并且必须是字母缩写。
  • 如果有剩余的东西,则测试字符串不会包含所有字母,因此它一定不能是字符集。
  • 任何空格,测试字符串集中的标点符号都不会出现在字母集中,因此它们无关紧要。
  • set(..) - set(..)将返回一个空集或一个包含内容的集。如果我们在Python中将集合强制设置为最简单的True/False值,则具有内容的容器为“True”,而空容器为“False”。

    因此,我们正在使用not来检查“是否还有剩余?”通过将结果强制为True/False值,具体取决于是否有剩余物。
    not也会更改True-> False和False-> True。这在这里很有用,因为(用完了字母)->一个空集False,但是在这种情况下,我们希望is_pangram返回True。反之亦然,(字母有一些剩余)->一组字母,即True,但是我们希望is_pangram为此返回False

    然后返回该正确/错误结果。
    is_pangram = lambda s: not set('abcdefghijklmnopqrstuvwxyz') - set(s.lower())
    #      Test string `s`
    #is a pangram if
    #                           the alphabet letters
    #                                                             minus
    #                                                               the test string letters
    #                   has NO leftovers
    

    10-07 12:16
    查看更多