Exercism: High Scores (Python)

很简单,主要是看list的用法。第三个方法有点意思,返回list中最大的n个值。开始想用heapq来写一个min heap的方法,但后来发现heapq自带这样一个nlargest,nsmallest的方法。之前在面试中用过类似的题,我从来没有看过一个人直接用过这个方法。看来真的应该好好了解一下Python的文档。

import heapq

def latest(scores):
    return scores[-1] 

def personal_best(scores):
    return max(scores)

def personal_top_three(scores):
    return heapq.nlargest(3, scores)

评论

此博客中的热门博文

拜厄练习曲44, 45

Exercism: Word Count (Python)

pygame Alevel 项目