Reputation: 13
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)
Upvotes: 1
Views: 3241
Reputation: 251
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())
Upvotes: -1
Reputation: 1123410
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.
Upvotes: 5
Reputation: 115
def find_value(word):
return sum(map(lambda x:value_list[x], list(word)))
Upvotes: 0
Reputation: 12467
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
.
Upvotes: 1