你好,我有下面的代码,但是它没有按预期工作,我看不到我在哪里出错了,我正在使用python 3 missing_letters方法无法正常工作,因为第二个输出错误,我需要它接受输入并使用字母字符串作为比较来返回缺少的字母
alphabet = "abcdefghijklmnopqrstuvwxyz" test_miss = ["zzz","subdermatoglyphic","the quick brown fox jumps over the def missing_letters(string): compare = histogram(string) for key in sorted(compare): if key in alphabet: result = alphabet.replace(key,'') return result # print result else: return None for letters in test_miss: if missing_letters(letters) == None: print(letters, 'uses all the letters') else: print(letters , 'is missing letters', missing_letters(letters)) # output: zzz is missing letters abcdefghijklmnopqrstuvwxy # subdermatoglyphic is missing letters bcdefghijklmnopqrstuvwxyz # the quick brown fox jumps over the lazy dog uses all the letters
答案 0 :(得分:1)
您不需要计算字母的数量,可以直接使用一组字母(输入string
中每个字母仅出现一次)。一旦有了该集合,就可以从字母表中减去该集合,最后得到一个包含缺少字母的集合:
from string import ascii_lowercase
alphabet = set(ascii_lowercase)
def missing_letters(string):
return alphabet - set(string.lower())
print(missing_letters("abcdefghijklmnopqrstuv"))
将输出{'w', 'y', 'x', 'z'}
。请注意,ascii_lowercase
只是一个包含所有小写字母的字符串。
答案 1 :(得分:0)
主要问题是您return
在内部,即在检查了第一个字母之后。另外,似乎您正在迭代单词中的字母并检查它们是否在字母中,而不是反过来,这会产生更多感觉。另外,似乎不必创建字母频率的直方图。
您可以尝试以下操作:
def missing_letters(string):
missing = []
for key in alphabet:
if key not in string:
missing.append(key)
return ''.join(missing) or None
或者您也可以将字母和字符串都转换为set
,并使用设置差异-
:
def missing_letters(string):
return ''.join(sorted(set(alphabet) - set(string))) or None
答案 2 :(得分:0)
使用集进行会员资格测试:首先将alphabet
设置为一个集
In [10]: alphabet = "abcdefghijklmnopqrstuvwxyz"
In [11]: alphabet = set(alphabet)
对于字符串“ ab”,“直方图返回”
In [12]: compare = {'a':1,'b':1}
使用设置方法确定差异
In [13]: alphabet.difference(compare.keys())
Out[13]:
{'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z'}
答案 3 :(得分:0)
您的方法'def missing_letters(string):'是错误的。 我已经更正了,下面的代码/方法将起作用,请尝试
alphabet = "abcdefghijklmnopqrstuvwxyz"
test_miss = ["zzz","subdermatoglyphic","the quick brown fox jumps over the lazy dog"]
def missing_letters(string):
result = alphabet
compare = set(string)# use histogram to make a dictionary
compare=sorted(compare)
for key in compare: # iterate and sort in alphabetical order
if key in alphabet: # check if the key in alphabet
result = result.replace(key,'')# remove it from alphabet
return result
# Test the function
print(missing_letters("ab")) # output: bcdefghijklmnopqrstuvwxyz
##### test_miss for loop #####
for letters in test_miss:
if len( missing_letters(letters) ) == 0:
print(letters, 'uses all the letters')
else:
print(letters , 'is missing letters', missing_letters(letters))
# output: zzz is missing letters abcdefghijklmnopqrstuvwxy
# subdermatoglyphic is missing letters bcdefghijklmnopqrstuvwxyz
# the quick brown fox jumps over the lazy dog uses all the letters