我正在尝试编写一个python程序,该程序检查给定字符串是否为pangram-包含字母表中的所有字母。
因此,"We promptly judged antique ivory buckles for the next prize"
应该返回True
,而任何不包含字母表中每个字母至少一次的字符串都应该返回False
。
我相信我应该用RegEx来做这个,但我不确定怎么做。它应该看起来像这样:
import sys
import re
input_string_array = sys.stdin.readlines()
input_string = input_string_array[0]
if (re.search('string contains every letter of the alphabet',input_string):
return True
else:
return False
这不是我用正则表达式来解决的问题,no。创建一组小写字符串,并检查它是否是字母表中字母的超集:
import string
alphabet = set(string.ascii_lowercase)
def ispangram(input_string):
return set(input_string.lower()) >= alphabet
只有当字母表中的每个字母都在根据输入文本创建的集合中时,它才会是超集;通过使用超集而不是相等,除了(ASCII)字母之外,还可以使用标点符号、数字和空白。
演示:
>>> import string
>>> alphabet = set(string.ascii_lowercase)
>>> input_string = 'We promptly judged antique ivory buckles for the next prize'
>>> set(input_string.lower()) >= alphabet
True
>>> set(input_string[:15].lower()) >= alphabet
False
这是我在python中的解决方案:
alphabet = "abcdefghijklmnopqrstuvwxyz"
sentence = input()
sentence = sentence.lower()
missing = ''
for letter in alphabet:
if letter not in sentence:
missing = missing+letter
if (len(missing) != 0):
print("missing", missing)
else:
print("pangram")
您不需要regex。您想要的东西可以在两行中完成,具有良好的空间效率。
ms = itertools.chain(range(ord("a"),ord("z")),range(ord("A"),ord("Z")))
flag = all(chr(o) in string for o in ms)
就是这样。string
是您要检查的字符串。flag
将是True
或False
,这取决于是否所有字符都在string
中。
pangram是一个至少包含字母表中每个字母的函数。我尝试过这种方式:
def pangram():
n = str(input('give me a word to check if it is a pangram:n'))
n = n.lower()
n = n.replace(' ','')
if not isinstance(n, str):
return n, False
elif set(n) >= set('abcdefghijklmnopqrstuvxywz'):
return n, True
else:
return n, False
函数isinstance(n,str)检查n是否为字符串。函数set()给了我们一个集合。例如,set('penny')返回{'y','e','p','n'}。。。正如你所看到的,这是一个没有重复字母的集合。
我今天也在做同样的练习,也许这不是最好的方法,但我认为它很容易理解。
def ispangram(s):
stringy = ''
flag = True
validLetters = "abcdefghijklmnopqrstuvwxyz"
#transform the given string in simple string with no symbols only letters
for char in s.lower():
if(char in validLetters):
stringy += char
#check if all the letters of the alphabet exist on the string
for char in validLetters:
if(char in stringy):
pass
else:
flag = False
break
return flag
if(ispangram("We promptly judged antique ivory buckles for the next prize")):
print("It's PANGRAM!")
else:
print("It's not Pangram :(")
import string
def ispangram(str1, alphabet=string.ascii_lowercase):
return ''.join(sorted(set(str1.lower().replace(" ","")))) == alphabet
首先将所有字母改为小写,然后使用替换删除所有空格。然后转换为具有唯一字符的集合,然后使用排序函数按字母顺序排序。由于排序后的函数会给出一个列表,所以join func会在没有空格的情况下连接它,然后将它与所有小写字符进行比较。
这是我的解决方案:
def isaPangrams(s):
alph = list(string.ascii_lowercase)
s = s.lower()
s = list(s)
for letter in alph:
if letter not in s:
print('not pangram')
present='false'
break
if letter in s:
present = 'true'
if present == 'true':
print('pangram')
if __name__ == '__main__':
s = input()
answer = isaPangrams(s)