返回得分最高的单词

时间:2018-06-07 17:58:53

标签: python python-3.x

我一直试图定义一个返回得分最高的单词的函数。首先,我制作了一本字典(因为有些字母没有标点符号而其他字母则相同)。所以,想象一下我最好([" Babel"," Xadrez"])。它应该返回" Xadrez",因为它对另一个单词的10分有21分,但我没有得到它。 这是我现在的代码:

def best(lista):

  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}

 for i in range(len(lista)):
     if lista[i] >= 'A' and lista[i] <= 'Z':
        lista.append(lista[i])
 return lista

 txt = lista

 soma1 = 0
 soma2 = 0
 soma3 = 0
 for palavra in txt:
     soma1 = soma1 + dic.get(palavra, 0)

 for palavra in txt:
     soma2 = soma2 + dic.get(palavra, 0)

 for palavra in txt:
     soma3 = soma3 + dic.get(palavra, 0)

#I think the problem starts here, because we don't know where the next
 #word starts neither how many words there are
 if soma1 > soma2 and soma1 > soma3:
   return soma1
 elif soma2 > soma1 and soma2 > soma3:
   return soma2
 else:
   return soma3
#I know that this returns the punctuation of the word instead of the 
 #word itself, but I did it for just a reason: if the code was right
 #it would be easy to return the word
 #Thanks.

1 个答案:

答案 0 :(得分:1)

您可以通过将代码分解为一个单词来简化此best函数。我不确定你到底想要做什么,所以这对于你的实际问题可能过于简单,但它应该足以让你前进:

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

现在,如果您有一个单词列表,则可以将score函数用作key function,然后将其传递给max

def best(lista):
    return max(lista, key=score)