返回信息流楼主小白,最近在上MIT6.00.1x那个入门课。中期考试有一道题是根据给出的功能描述实现函数。
```Python
def score(word, f):
"""
word, a string of length > 1 of alphabetical
characters (upper and lowercase)
f, a function that takes in two int arguments and returns an int
Returns the score of word as defined by the method:
1) Score for each letter is its location in the alphabet (a=1 ... z=26)
times its distance from start of word.
Ex. the scores for the letters in 'adD' are 1*0, 4*1, and 4*2.
2) The score for a word is the result of applying f to the
scores of the word's two highest scoring letters.
The first parameter to f is the highest letter score,
and the second parameter is the second highest letter score.
Ex. If f returns the sum of its arguments, then the
score for 'adD' is 12
"""
```
然后,我就这样写了
```Python
def score(word, f):
word = str.lower(word)
highest1 = ord(word[1]) - 96
highest2 = 0
for i, l in enumerate(word):
l_score = i * (ord(l) - 96)
if highest2 < l_score <= highest1:
highest2 = l_score
elif l_score > highest1:
highest2 = highest1
highest1 = l_score
return f(highest1, highest2)
```
但总是有部分测试过不了,代码有什么问题吗?
在网上搜了一下,有人是这样写的,但我感觉没什么区别啊。但是这份代码强调不能将字符串小写。。
```
def score(word, f):
# first need to calculate the score of each letter in word, store it in a list
import string
scorelist=[0]*len(word)
# cannot convert to all lower case or all upper case!!!
loop_tracker=0
for char in word:
loop_tracker+=1
if char.islower():
alphabet_location=string.ascii_lowercase.find(char)+1
#index=word.find(char) # note here cannot use find() to get the index of the char, otherwise only return the index of 1st char
index=loop_tracker-1
scorelist.extend([alphabet_location*index])
else:
alphabet_location=string.ascii_uppercase.find(char)+1
index=loop_tracker-1
scorelist.extend([alphabet_location*index])
max_score=max(scorelist)
scorelist.remove(max_score)
next_max=max(scorelist)
#print(max_score,next_max)
return f(max_score,next_max)
```
这是一条镜像帖。来源:北邮人论坛 / python / #20383同步于 2018/1/4
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
【已解决】【问题】这两份代码的区别在哪?
youdianer
2018/1/4镜像同步4 回复
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
我的想法是,因为单词长度至少为2,而第一个字母的分数肯定是为0的,所以把0作为次大分数的初始值,把第二个字母的分数作为最大分数的初始值。然后遍历整个单词。
懂了。前两个数直接用于初始化了,后面遍历的时候就应该从第三个开始。谢谢[ema3]
【 在 wk1948 的大作中提到: 】
: 考虑这样一组数。1 2 1。按照你的算法最大的两个数会是 2 2