我正在进行代码大战katahttps://www.codewars.com/kata/57eb8fcdf670e99d9b000272/train/python
你必须返回字符串中得分最高的单词。字母根据字母表中的位置进行评分
a =1, z= 26
我创建了一个列表:
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
我想迭代单词,这些单词将在作为参数传递的字符串(x(中,如果被检查的字母在字母表列表中,当然也会在字母表中,那么我想迭代到一个sperate变量:score,通过当前被检查的信号在字母表表中索引的数字来增加score。
可以用这种方式使用列表索引吗?
这是我目前的代码:
def high(x):
alphabet = []
scores = [] # ignore
score = 0
for letter in range(97,123):
alphabet.append(chr(letter))
word_list = x.split()
for word in word_list:
for letter in word:
if letter in alphabet:
score += # find way to use alphabet list index number as integer here
谢谢。
根据我所看到的,根本不需要字母列表:
import string
def high(x):
score = 0
for word in x.split():
for letter in word:
if letter in string.ascii_lowercase:
score += ord(letter)-96
return score
或者更简单:
import string
def high(x):
# Sum expression on multiple lines for clarity
return sum( ord(letter)-96
for word in x.split()
for letter in word
if letter in string.ascii_lowercase)
使用列表理解和字典score
来跟踪每个字母及其分数。请注意,输入字符串是小写的——我假设大写字母和小写字母的分数相同。
alphabet = 'abcdefghijklmnopqrstuvwxyz'
score = dict(zip(list(alphabet), [i + 1 for i in range(len(alphabet))]))
x = 'aB, c'
score = sum([score[c] for c in list(x.lower()) if c in score])
print(score)
# 6
@AlanJP,你想试试这个程序吗:
# simple word scoring program
import string
characters = string.ascii_lowercase
ranking = {c: i for i, c in enumerate(characters, 1)}
#print(ranking)
word_list = 'abba is great'.split()
for word in word_list:
score = 0 # reset the score for each incoming word
for char in word:
score += ranking[char]
print(word, score)
输出:
abba 6
is 28
great 51
>>>
是。alphabet.index(letter) + 1
会给你想要的。
index((您还需要+1来说明index[0]
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)