返回具有最高s的单词

2024-09-28 23:40:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试定义一个函数,它返回得分最高的单词。首先,我做了一本字典(因为有些字母没有标点符号,其他字母也有相同的标点符号)。所以,想象一下我有最好的([“巴贝尔”,“萨德雷斯”])。它应该返回“Xadrez”,因为它有21分对另一个词的10分,但我没有得到它。 现在我的代码是:

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.

Tags: andtheintxtforgetreturnif
1条回答
网友
1楼 · 发布于 2024-09-28 23:40:47

您可以简化这个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并将其传递给^{}

^{pr2}$

相关问题 更多 >