【问题标题】:Detecting if a string is a pangram in Python在 Python 中检测字符串是否为 pangram
【发布时间】:2017-10-30 22:42:54
【问题描述】:

这是如何工作的?它检查一个字符串是否至少包含一次从 a-z 开始的每个字符?

import string

def ispangram(str1, alphabet=string.ascii_lowercase):  
    alphaset = set(alphabet)  
    return alphaset <= set(str1.lower()) 

这会返回 True 例如:

ispangram("The quick brown fox jumps over the lazy dog")

我只能假设这与此处所述的字典顺序有关,但仍然有点困惑。

Comparing two lists using the greater than or less than operator

当我阅读此 SO 问题中的链接时:

https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types

上面写着:

序列对象可以与其他具有相同特征的对象进行比较 序列类型。比较使用字典顺序:首先 比较前两项,如果它们不同,则确定 比较结果;如果它们相等,则接下来的两项是 比较,依此类推,直到任一序列用完。如果两个项目 要比较的是它们本身的相同类型的序列, 字典比较是递归进行的。如果所有项目 两个序列比较相等,则认为序列相等。如果 一个序列是另一个序列的初始子序列,越短 序列是较小的(较小的)。字典顺序 字符串使用 Unicode 代码点编号来排序单个 人物。相同序列之间比较的一些示例 输入。

但这一点我不清楚。

【问题讨论】:

标签: python


【解决方案1】:

这是一个set 操作,而不是list。相当于,

alphaset.issubset(set(str1.lower()))

s

s.issubset(t)

测试s中的每个元素是否都在t中。

请看这里: https://docs.python.org/2/library/sets.html

编辑:请参阅此处了解Set 的当前版本。虽然在旧版本中给出了更简单的解释(用于比较)。

【讨论】:

【解决方案2】:

没有。它比较两个sets。因此,它将输入字符串转换为小写字母,然后使用 Python 的集合类型将其与小写字母集合进行比较。

这是一种非常有用(且快速)的技术,用于比较两个列表以查看它们有哪些共同/不同的成员。

【讨论】:

    【解决方案3】:
    def pangram(s):
    alphabet = set('abcdefghijklmnopqrstuvwxyz')
    s = s.replace(' ','').lower()
    s= sorted(s)
    
    count = {}
    
        #alphabet could be one sting within '' later sorted, but I just went straight to the point. 
        #After initializing my dictionary at null, we start the count    
    
    for letter in s:
        if letter in count:
            count[letter] =[]
        else:
            count[letter] = 1
    
    for letter in alphabet:
        if letter in count:
            count[letter] =[]
        else:
            count[letter] = 0
    for letter in count:
        if count[letter]== 0:
            print (letter +' missing!')
    print (count[letter]!= 0)
    

    【讨论】:

      猜你喜欢
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多