我应该做的是
Write a function top_k that takes a list of students and an integer k and returns a list of the names of the k students with the highest scores in alphabetical order. If there are students in the range (k + 1, · · · k + i) who have the same score as the kth student, include them in the list as well.
当我输入
top_k(student_list1, 5)
>>> [('eugene', 'A', 21), ('simon', 'A', 21), ('john', 'A', 15), ('tiffany', 'A', 15), ('dave', 'B', 12)]
top_k(student_list2, 3)
>>>[('eugene', 'A', 21), ('simon', 'A', 21), ('john', 'A', 15), ('tiffany', 'A', 15)]
在哪里
^{pr2}$我的代码是
def top_k(students, k):
toptobottom = sorted(students, key = lambda x: x[2], reverse = True)
takeout= toptobottom[:k+1]
result = []
for takethat in takeout:
if takethat[2] == 21:
result.append(takethat)
result.sort( key= lambda x: x[0])
elif takethat[2] ==15:
result.append(takethat)
return result
我不知道该放在哪里结果.排序(键..)。它应该和elif在同一行,还是应该有一个缩进? 谢谢!在
您可以只对输入数组排序一次,然后选择正确的学生。在
除了你的缩进问题,你的代码是专门为输入数据编写的(即在你的函数中硬编码的最高分)。虽然这可能会让你完成练习,但这不是一个好的实践,你应该更全面地思考你要解决的问题。在
在伪代码中:
这绝不是一个答案,所以我真的不想把它标记成这样,但是我想插上几句话,它们太长了,不能发表评论,从长远来看可能对你有帮助。在
关于你的问题:
我想我帮你解决了你的问题,但我还没有分析你的逻辑。我看到了硬编码的分数,就停止了阅读,因为这真是个坏主意。永远不要那样做,永远不要。尤其是当你在为算法课做作业的时候。在
第二件事是,我不认为你应该完全忽略一些python资源,python's standard library resource for sorting is enormous而且有很多库可以帮助你。在
第三,我们花了大量的精力为python的库和built in types that I really think you should check out提供某种完整性
第四,我根据你的例子准备了一些小片段。当然,我并没有把它变成一个函数,因为我想让你想想你在做什么。不管怎样,我想你会发现这个很有帮助的。在
^{pr2}$输出如下:
你认为你可以综合所有这些,并以更好的理解完成你的任务?这里有一些复杂的事情在进行,比如dict、list和list理解,但是我认为这是一个很好的特性汇编,允许python将几乎所有的list问题切碎。在
相关问题 更多 >
编程相关推荐