首页 > 解决方案 > 该函数需要接收一个字符串并使用字母变量和直方图函数来输出字符串中缺少的字母

问题描述

我创建了一个名为的函数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'........]

标签: pythonpython-3.x

解决方案


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

推荐阅读