LeetCode练习<六> 相关排序

# Given scores of N athletes, find their relative ranks and the people with the top three highest scores,
# who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".
# Input: [5, 4, 3, 2, 1]
# Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
# Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal".
# For the left two athletes, you just need to output their relative ranks according to their scores.
# 题意是输入一个列表,列表中的是运动员的得分, 我们根据得分为每一个人发奖牌, 得分最高的前三名分别获得金银铜牌,
# 剩下的运动员输出他们拍第几名(4, 5, 6...), 输出仍然按照输入的排列顺序输出
# 基本思路如下:
# 1 先将分数排序,也就是nums由大到小排序
# 2 生成新的列表,包括金银铜牌, 以及剩余运动员的排名, [, , , 4(第四名), 5(第五名), 6(第六名)]
# 需要注意的是map之后是一个函数,转换成list时需要加上list(map(...))
# 3 利用zip函数生成由元祖组成的列表, zip函数,http://www.runoob.com/python/python-func-zip.html
# zip(iterable, iterable2) iterable中的对应数据组成元祖,多个元组组成列表
# [(7, 'Gold Medal'),(6, 'Silver Medal'),(5, 'Bronze Medal'),(4, '4'),(3, '5'),(1, '6')]
# 然后生成字典,目的是为了下一步的查询 {1: '6', 3: '5', 4: '4', 5: 'Bronze Medal', 6: 'Silver Medal', 7: 'Gold Medal'}
# map(dict(zip(sort, rank)).get, nums), map中第一个参数为一个函数, nums为传入函数中的参数. dict.get是获得字典中对应
# keyvalue, nums中的每一个值就是传入get()中的key, 按照key的顺序查找保存至map,并转换成list输出.
# 字典用法 http://www.runoob.com/python/att-dictionary-get.html
# #greg 20170516

class Soulution(object):
    def findRelativeRanks(self, nums):
        sort = sorted(nums)[::-1]
        rank = ['Gold Medal', 'Silver Medal', 'Bronze Medal'] + list(map(str, range(4, len(nums) + 1)))
        return list(map(dict(zip(sort, rank)).get, nums))

if __name__ == '__main__':
    nums = [7, 3, 9, 2, 5, 8]
    s = Soulution()
    print(s.findRelativeRanks(nums))

结果:







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值