Detecting if a string is a pangram in Python
这是怎么工作的?它检查一个字符串是否至少包含一次a-z中的每个字符?
1 2 3 4 5 | import string def ispangram(str1, alphabet=string.ascii_lowercase): alphaset = set(alphabet) return alphaset <= set(str1.lower()) |
这将返回true,例如:
1 | ispangram("The quick brown fox jumps over the lazy dog") |
号
我只能假设它与此处所述的lexographical排序有关,但仍然有点困惑。
使用大于或小于运算符比较两个列表
当我阅读这个问题的链接时:
https://docs.python.org/3/tutorial/datastructures.html比较序列和其他类型
上面写着:
Sequence objects may be compared to other objects with the same
sequence type. The comparison uses lexicographical ordering: first the
first two items are compared, and if they differ this determines the
outcome of the comparison; if they are equal, the next two items are
compared, and so on, until either sequence is exhausted. If two items
to be compared are themselves sequences of the same type, the
lexicographical comparison is carried out recursively. If all items of
two sequences compare equal, the sequences are considered equal. If
one sequence is an initial sub-sequence of the other, the shorter
sequence is the smaller (lesser) one. Lexicographical ordering for
strings uses the Unicode code point number to order individual
characters. Some examples of comparisons between sequences of the same
type.
号
但我不清楚。
它是一个
1 | alphaset.issubset(set(str1.lower())) |
s <= t
s.issubset(t)
Test whether every element in s is in t.
号
请参见此处:https://docs.python.org/2/library/sets.html网站
编辑:有关集合的当前版本,请参见此处。虽然旧版本中给出了更简单的解释(用于比较)。
不,这是比较两组。所以它将输入字符串转换为小写,然后使用python的set类型将其与小写字母集进行比较。
这是一种非常有用的(快速)技术,用于比较两个列表,以了解它们有哪些共同/不同的成员。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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) |
号