首页 > 解决方案 > 从 k 个字母的字符串中构建一个函数,该函数从有效单词列表中输出单词列表,并找到拼字游戏得分最高的单词

问题描述

所以我有一个函数可以输出字符串中的所有单词

但是,我正在努力将其整合到一个列表中,目前,它在单独的列表中输出单词

def scrabble_score(word):
    total = 0 # Create score var
    for i in word: # Loop through given word
        total += score[i.lower()] #Lookup in dict, add total
    return total

def charCount(word): 
    dict = {} 
    for i in word: 
        dict[i] = dict.get(i, 0) + 1
    return dict
  
  
def possible_words(lwords, charSet): 
    for word in lwords: 
        flag = 1
        chars = charCount(word) 
        for key in chars: 
            if key not in charSet: 
                flag = 0
            elif charSet.count(key) != chars[key]: 
                    flag = 0

        #for word in word_list:
        if flag == 1: 
            #word_value_dict = {}
            firstList = []
            #word_value_dict[word] = get_word_value(word, letter_values)
            firstList.append(word)
            #return word_value_dict
            print(scrabble_score(word), (word))
            print(firstList)
  
if __name__ == "__main__": 
    input = ['goo', 'bat', 'me', 'eat', 'goal', 'boy', 'run'] 
    charSet = ['e', 'o', 'b', 'a', 'm', 'g', 'l', 'b'] 
    possible_words(input, charSet) 

我还有一个单独的函数,可以从列表中找到得分最高的单词

def score(word):
    dic = {'D':2, 'C':2, 'L':2, 'P':2, 'B':3, 'N':3, 'F':4, 'G':4, 'H':4, 'V':4, 'J':5, 'Q':6, 'X':8, 'Y':8, 'Z':8}
    total = 0
    for char in word:
        total += dic.get(char.upper(), 0)
    return total
#return highest score
def best(lista):
    return max(lista, key=score)

best(['goo', 'bat', 'me', 'eat', 'run'])

输出:

4 me
['me']
5 goal
['goal']

期望的输出:所有可能单词的列表

['me', 'goal']

或者一个字典(或类似结构),可能的词作为键,分数作为值

{'me':4, 'goal':5]

我需要一种从第一个函数返回 lsit 的方法,并将两者结合起来以找到该列表中的最高分

第二部分:

我需要扩展它来计算字母长度为 2-8 的所有字母组合组合的最高分,以及我们可以产生这样一个分数的组合数量

标签: pythonlistfunctionfor-loopscrabble

解决方案


推荐阅读