查找拼字游戏的价值 [英] Find value of scrabble word

查看:62
本文介绍了查找拼字游戏的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对任何高级语言的经验都很少.我小时候玩弄基础和剂量批处理.

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)

推荐答案

您将直接遍历word并使用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.

这篇关于查找拼字游戏的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆