4. 算法编程练习:Highest Scoring Word

本文介绍了一种算法,用于在一个字符串中找到得分最高的单词。通过计算每个字母的分数并累加,找出总分最高的单词,同时考虑分数相同时的原始顺序。该算法涉及字符串拆分、字符编码求和以及返回最高分单词的索引字符。
摘要由CSDN通过智能技术生成

Highest Scoring Word

Given a string of words, you need to find the highest scoring word.
Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
You need to return the highest scoring word as a string.
If two words score the same, return the word that appears earliest in the original string.
All letters will be lowercase and all inputs will be valid.

For example

test.assert_equals(high(‘man i need a taxi up to ubud’), ‘taxi’)
test.assert_equals(high(‘what time are we climbing up the volcano’), ‘volcano’)
test.assert_equals(high(‘take me to semynak’), ‘semynak’)
test.assert_equals(high(‘aa b’), ‘aa’)
test.assert_equals(high(‘b aa’), ‘b’)
test.assert_equals(high(‘bb d’), ‘bb’)
test.assert_equals(high(‘d bb’), ‘d’)
test.assert_equals(high(“aaa b”), “aaa”)

Algorithm analysis

输入字符串,得到其中一个字符串的一个数据元素。需要得到每一个数据元素对应的分数。分数利用ord(c)-96(注意:这里的c的长度只能为1,即只能是一个字符),得到A到Z对应的分数。需要先拆分字符串用split(),for循环可能需要用到两次。

Algorithm details

  1. 拆分字符串;
  2. 再拆分每一个数据元素,转码并求对应的和;
  3. 选最大的数;
  4. 返回最大数索引对应的字符

code

def high(x):
    words=x.split(' ')
    list = []
    for i in words:
        scores = [sum([ord(char) - 96 for char in i])]
        list.append(scores)
    return words[list.index(max(list))]

Thanks for reading

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值