【问题标题】:Why is another nested for loop required to to search the dictionary?为什么搜索字典需要另一个嵌套的 for 循环?
【发布时间】:2019-01-08 15:23:42
【问题描述】:

所以有问题的代码是一个非常基本的拼字游戏分数计算器。这是 CodeCademy 网站上的一项挑战。

他们定义的正确代码如下,你可以看到有一个嵌套的for循环在整个字典中搜索word中的每个字母:

    score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, 
         "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, 
         "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, 
         "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, 
         "x": 8, "z": 10}

def scrabble_score(word):
  word = word.lower()
  total = 0
  for letter in word:
    for leter in score:
      if letter == leter:
        total = total + score[leter]
  return total

我对 Python 比较陌生,但据我了解,for 循环应该能够如下工作,它循环遍历 word 变量中的每个字母,将其用作键入 score 字典,然后将其添加到 total。如您所见,它会返回 total

def scrabble_score(word):
  word = word.lower()
  total = 0
  for letter in word:
    total = total + score[letter]
  return total

但是,CodeCademy 说这是错误的。有人可以解释一下我在这里缺少什么吗?

干杯

【问题讨论】:

    标签: python python-2.7 dictionary for-loop nested-loops


    【解决方案1】:

    您的代码似乎正确且优化了很多,添加 try/catch 块以防万一!

    def scrabble_score(word):
        word = word.lower()
        total = 0
        for letter in word:
          try:
            total += score[letter]
          except KeyError, e:
            print "Error: Letter {} is missing from the score".format(e)
        return total
    

    【讨论】:

    • 干杯阿米特,非常感谢。
    【解决方案2】:

    您的答案似乎没有错。它按预期执行。在这种情况下,CodeAcademy 接受的答案可能过于严格。

    【讨论】:

    • 干杯本,感谢您的帮助。
    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    相关资源
    最近更新 更多