python拼字游戏单词得分手

时间:2014-10-24 20:17:10

标签: python

我被要求编写一个程序,允许用户输入单词并计算该单词的值。因此,'Hello'的值为8.如果用户需要输入双字母或三字母分数,则在字母后面输入值,例如如果'你好'的第一个'L'是双字母得分,他们就会进入'hel2lo'。

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}
到目前为止,这就是我所拥有的一切。我不知道怎么做:(

2 个答案:

答案 0 :(得分:0)

def score(word, points):
    counts26555731 = {}
    for iGotThisFromStackOverflow,char in enumerate(word):
        if char.isdigit():
            counts26555731[word[iGotThisFromStackOverflow-1]] += int(char)-1
            continue
        if char not in counts26555731:
            counts26555731[char] = 0
        counts26555731[char] += 1
    return sum(points[char]*count for char,count in counts26555731.items())

用法:

points = {"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}

word = 'hel2lo'
print(word, "is worth", score(word, points), "points")

打印:

hel2lo is worth 9 points

答案 1 :(得分:0)

我有一个使用try/except KeyError 的替代方案:

# by the way, you missed the { 
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 check_score(word):
    total = 0
    for n, letter in enumerate(word):
        try:
            # look up dictionary and add paired score to total
            total += score[letter]
        # if letter is digit, above will throw KeyError
        except KeyError:
            # as previous letter score is added, add (int(letter) - 1) times of score
            total += score[word[n-1]] * (int(letter) - 1)
    print "Total scores for {}: {}".format(word, total)

check_score('hel2lo')
Total scores for hel2lo: 9