简体   繁体   English

为什么代码1比代码2快?

[英]Why is Code 1 faster than Code 2?

Code 1: 代码1:

n = int(input())
ls = []
for x in range(n):
    ls += [(input())]
ls.sort(key = int)
for x in ls:
    print (x)

Code 2: 代码2:

n = int(input())
ls = []
for x in range(n):
    ls += [int(input())]
ls.sort()
for x in ls:
    print (x)

These were my solutions to the HackerRank's "Big Sorting" problem: https://www.hackerrank.com/challenges/big-sorting 这些是我对HackerRank的“大分类”问题的解决方案: https ://www.hackerrank.com/challenges/big-sorting

Code 1 does not give time limit exceeded error while Code 2 does. 代码1没有给出超过时间限制的错误,而代码2却给出了错误。

Why is Code 1 faster and than Code 2? 为什么代码1比代码2更快?

The code is slower because you now need to convert the list of integers back to strings, while version 2 keeps the string versions, only converting to integers to sort. 代码比较慢,因为您现在需要将整数列表转换回字符串,而版本2保留字符串版本,仅转换为整数以进行排序。

Converting integers back to strings takes time too: 将整数转换回字符串也需要时间:

>>> import timeit
>>> timeit.timeit("str(235739630407432043190819704398)", number=10**7)
2.4063552810002875

I strongly suspect that the values to sort included in some of the tests are both numerous and very, very large. 我强烈怀疑某些测试中包含的要排序的值既众多又非常大。

I'd not use in-place extending either. 我也不会使用就地扩展 Use a list comprehension instead: 改用列表理解:

ls = [input() for x in range(n)]

Personally, I'd use iteration over sys.stdin to read faster than input() calls can; 就个人而言,我将使用sys.stdin上的迭代来读取速度比input()调用要快; here all loops are delegated to optimised C code: 在这里, 所有循环都委托给优化的C代码:

import sys
from itertools import islice

n = int(next(sys.stdin))
nums = sorted(map(str.strip, islice(sys.stdin, n)), key=int)
print(*nums, sep='\n')

(because the last line read from stdin has no newline you can't count on the newline being present on all lines, and then it's just easier and faster to strip). (因为从stdin读取的最后一行没有换行符,所以您不能指望所有行上都存在换行符,这样剥离起来会更容易,更快捷)。

Replacing str.strip with int will once more cause time-outs. str.strip替换为int会再次导致超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM