python - 该函数需要接收一个字符串并使用字母变量和直方图函数来输出字符串中缺少的字母
问题描述
我创建了一个名为的函数missing_letters
,它接受一个字符串作为参数并在其上循环以查看输入字符串中缺少哪些字母。该函数需要按字母顺序返回缺失的字母。函数应该使用histogram
函数。
alphabet = "abcdefghijklmnopqrstuvwxyz"
我需要使用的直方图函数是:
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
我尝试'hello'
在函数中输入字符串并尝试打印丢失的字母,但似乎我的循环无法正常工作。
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
def missing_letters(string):
global alphabet
h = histogram(string)
missing = []
for k in alphabet:
for l in h:
if l not in k:
missing.append(l)
return missing
print(missing_letters('hello'))
如果我aaa
作为参数传递给函数,输出应该aaa
是缺少字母bcdefghijklmnopqrstuvwxyz
我的输出类似于['h', 'e', 'l', 'o', 'h', 'e', 'l', 'o', 'h', 'e', 'l', 'o', 'h', 'e', 'l', 'o'........]
解决方案
if l not in k
k
是字母表中的一个字母。
missing.append(l)
您将直方图中确实存在的字母附加到直方图中不存在的字母列表中。
def missing_letters(string):
global alphabet
h = histogram(string)
missing = []
for letter in alphabet:
if letter not in h:
missing.append(letter)
return missing
推荐阅读
- spring - Jackson模块kotlin中的泛型类转换异常
- yaml - 追加或替换由外部文件定义的字段 serverless.yml
- firebase - 注册用户时的Firebase Auth问题,注册时自动登录?
- laravel - Laravel Sail:致命:用户“sail”的密码验证失败
- python - 如何从多维 NumPy 数组中选择和阈值 x% 的值?
- python - 有没有办法在 tkinter 中破坏从一个类到另一个类的函数标签?
- python - Django Admin 反复注销。可能是因为DB损坏了。如何解决这种情况?
- node.js - 带有 lerna 的 Docker(Next.js 和 Graphql)
- javascript - Tensorflow.js 在运行线性回归模型时返回“NaN”值
- javascript - 打字稿 - 面临的问题属性不能分配给基本类型中的相同属性