找到拼字游戏单词的价值

1 python recursion loops

我对任何更高级别的语言都没有什么经验.在我小时候摆弄基本和dos批次.

我试图在拼字游戏中找到一个单词的点值.这种递归结构似乎缓慢且低效.在程序结构/概念方面,解决这个问题的更好方法是什么?

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

word_index = 0
total = 0

def find_value(word):
     global word_index
     global total
     x = word[word_index]
     total = total + value_list[x]
     if len(word) > word_index + 1:
         word_index = word_index + 1
         find_value(word)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

word直接循环并使用sum():

def find_value(word):
    return sum(value_list[char] for char in word)
Run Code Online (Sandbox Code Playgroud)

这里不需要使用递归; 以上也不需要全局变量.尽量避免全局状态,因为当您开始在多个位置使用函数时,这很容易导致难以调试的问题.