概述
Excel can sort records according to any column. Now you are supposed to imitate this function.
Input Specification:
Each input file contains one test case. For each case, the first line contains two integers N (≤105) and C, where N is the number of records and C is the column that you are supposed to sort the records with. Then N lines follow, each contains a record of a student. A student's record consists of his or her distinct ID (a 6-digit number), name (a string with no more than 8 characters without space), and grade (an integer between 0 and 100, inclusive).
Output Specification:
For each test case, output the sorting result in N lines. That is, if C = 1 then the records must be sorted in increasing order according to ID's; if C = 2 then the records must be sorted in non-decreasing order according to names; and if C = 3 then the records must be sorted in non-decreasing order according to grades. If there are several students who have the same name or grade, they must be sorted according to their ID's in increasing order.
Sample Input 1:
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60
Sample Output 1:
000001 Zoe 60
000007 James 85
000010 Amy 90
Sample Input 2:
4 2
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 98
Sample Output 2:
000010 Amy 90
000002 James 98
000007 James 85
000001 Zoe 60
Sample Input 3:
4 3
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 90
Sample Output 3:
000001 Zoe 60
000007 James 85
000002 James 90
000010 Amy 90
题目大意
给定一些学生的ID、姓名以及成绩,按照给定的c对学生进行排名。如果根据分数和名字排名出现了相同名次,则按照ID排名,所有的排序都是升序。
分析
使用sorted()函数,配合lambda匿名函数进行排序,应该是挺简单的,但是最后一个测试点会超时。
我一开始使用的是在读取时读取完使用str.split(” “)进行分裂字符串,将ID、姓名和成绩保存在数组中,然后在排序的时候根据每一个数组索引进行排序,输出的时候使用print(*x)输出每个数组中所有内容。
后来我尝试了1、使用heapq模块用堆排序的方法来进行排序。2、导入operator模块,使用模块中operator.itemgetter()函数加速排序,然而模块导入耗时就已经完美抵消模块带来的略微性能提升。
用cProfile分析了一下,真的python的input()好慢,非常想吐槽。
最后,采取了获取字符串,不进行分裂,直接使用字符串进行保存信息的方法。因为最后一个测试点的C为1,而且刚好字符串中ID排在首位且每个ID都固定6个字符,所以直接放给sorted()函数排序就OK了。
其他的当C为2或者3的时候,切片一下就好了,最后输出的时候也省略了使用*操作符取出数组中所有元素的步骤,直接输出字符串一步到位。
惯性思维害死人,有时候灵光一闪还是贼机智的。(^-^)V
def main():
line = input().split(" ")
n = int(line[0])
c =line[1]
records = []
for x in range(n):
line = input()
records.append(line)
if c == '1':
records = sorted(records)
elif c == '2':
records = sorted(records, key = lambda x : (x[7:-3], x[:6]))
elif c== '3':
records = sorted(records, key = lambda x : (x[-2:], x[:6]))
for x in records:
print(x)
if __name__ == "__main__":
main()
用python写PAT甲级,答案都在这了
最后
以上就是大意电灯胆为你收集整理的[PYTHON](PAT)1028 LIST SORTING(25 分)的全部内容,希望文章能够帮你解决[PYTHON](PAT)1028 LIST SORTING(25 分)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复