Python 涡轮排序-超出时间限制
我正在尝试解决Codechef问题()。问题是 给定数字列表,您需要按非递减顺序对它们进行排序 秩序 输入 t–列表中的数字数量,然后t行跟随[tMy accepted solutions:Python 涡轮排序-超出时间限制,python,algorithm,sorting,Python,Algorithm,Sorting,我正在尝试解决Codechef问题()。问题是 给定数字列表,您需要按非递减顺序对它们进行排序 秩序 输入 t–列表中的数字数量,然后t行跟随[tMy accepted solutions: import sys from itertools import imap T = int(raw_input()) lines = sys.stdin.readlines() lis = imap(str, sorted(imap(int, lines))) print "\n".join(lis) 可
import sys
from itertools import imap
T = int(raw_input())
lines = sys.stdin.readlines()
lis = imap(str, sorted(imap(int, lines)))
print "\n".join(lis)
可读版本(可接受的解决方案):
应该支持readlines之类的功能。我刚刚尝试了一下,并将其作为一个公认的解决方案:
import sys
print '\n'.join(map(str, sorted(map(int, sys.stdin.read().split()[1:]))))
不是很漂亮,但是很实用。我花了一点时间才发现你必须跳过第一个数字,这个系统的调试有点烦人;)does
input()
工作?我不这么认为works@AswinMurugesh它适用于数字,因为Python只能解释它们;但是不应该使用input
。@poke:不,当一系列数字在一行中给出时,使用input()会不会有问题
?@AswinMurugesh是的,在一行上,但是问题描述说每行一个数字。@poke:好的。刚才看到的,仅仅为了使用,而经历imap
的麻烦似乎有点浪费。加入。为什么不循环列表并打印每个元素呢?还有,readlines()
allowed?因为用户必须通过发送EOF来明确结束读取,而不是简单地输入一定数量的输入。@arshajii Yessys.stdin
在codechef上工作得很好。我用for循环尝试了这两种解决方案,但都得到了TLE。这很有趣,我会想到相反的结果。+1无论如何谢谢,很好的解决方案:)
import sys
T = raw_input()
lines = sys.stdin.readlines() #fetch all lines from the STDIN
lines.sort(key=int) #sort the list in-place(faster than sorted)
print "\n".join(lines) #use `str.join` instead of a for-loop
import sys
print '\n'.join(map(str, sorted(map(int, sys.stdin.read().split()[1:]))))