Find value of scrabble word

只谈情不闲聊 提交于 2020-01-05 08:35:30

问题


I have little experience in any higher level language. Fiddled with basic and dos-batch when I was a kid.

I'm trying to find the point value of a word in scrabble. This kind of recursive structure seems slow and inefficient. What would be a better way to address this problem in terms of program structure/concept?

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)

回答1:


You'd loop over word directly and use sum():

def find_value(word):
    return sum(value_list[char] for char in word)

There is no need to use recursion here; the above needs no globals either. Try to avoid global state, as that easily leads to hard-to-debug problems when you start using functions in multiple locations.




回答2:


First of all, you can use list of values instead of dict, and just count index for the letter x in this list as ord(x) - ord('a')

Second, don't use global, it is a bad programming habit. You should accumulate your value in local variable and then return this value from the function.

And third, use loop instead of recursion or, even better, functions like sum.




回答3:


def find_value(word):

    return sum(map(lambda x:value_list[x], list(word)))





回答4:


Yeah, function call is expensive is Python.

Martijn Pieters's method is a good example for beginners to understand list-comprehensions.

If you want a more simple and readable way, try this:

sum(value_list.values())


来源:https://stackoverflow.com/questions/20223922/find-value-of-scrabble-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!