Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/214.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何优化代码,使其也能运行在较大的值上_Python - Fatal编程技术网

Python 如何优化代码,使其也能运行在较大的值上

Python 如何优化代码,使其也能运行在较大的值上,python,Python,下面是我的代码。对于较小的值,它返回我正确的答案。我在这里做的是找到任意两个数字之间的最小差值,这样它就不会形成负值。 实际上,输入线是每年的成本,我需要找到最小损失(是的,它必须是一个损失)。 当输入很大时,比如说20000个数字,我会得到一个超时错误。 以下是指向测试用例的链接: 第一行包含值的数量,后续行包含值 #!/bin/python import sys number = long(raw_input().strip()) cost=map(long,raw_input().st

下面是我的代码。对于较小的值,它返回我正确的答案。我在这里做的是找到任意两个数字之间的最小差值,这样它就不会形成负值。 实际上,输入线是每年的成本,我需要找到最小损失(是的,它必须是一个损失)。 当输入很大时,比如说20000个数字,我会得到一个超时错误。 以下是指向测试用例的链接:

第一行包含值的数量,后续行包含值

#!/bin/python

import sys

number = long(raw_input().strip())
cost=map(long,raw_input().strip().split())
flag=1
j=0
mincost=max(cost)

print (mincost)

while j < number:
  k=j+1
  while k<number:
    if mincost>abs(cost[j] - cost[k]) and cost[j]> cost[k]:
      mincost=abs(cost[j] - cost[k])
    k+=1
  j+=1

print mincost
#/bin/python
导入系统
数字=长(原始输入().strip())
成本=映射(长,原始输入().strip().split())
标志=1
j=0
最小成本=最大(成本)
打印(最小成本)
而j成本[k]:
最小成本=绝对成本(成本[j]-成本[k])
k+=1
j+=1
印刷成本

对于20000个数字,您有(20000 x 19999)/2=199990000个成对比较。这是O(n^2)复杂性。但是,如果对值进行排序,两个相邻数字之间的差值将最小。由于排序是O(n logn),您可以通过(a)对值进行排序,然后(b)找到连续对之间的最小差异来改进算法

costs = [5, 4, 1, 8, 12]

sorted_costs = sorted(costs)
pairs = zip(sorted_costs[:-1], sorted_costs[1:])
differences = map(lambda (a, b): b - a, pairs)

print(min(differences)) # 1
剩下的唯一问题是你是否能在O(n)时间内达到同样的结果。如果您的值是整数,则可以将排序减少到O(n)(具有潜在的巨大空间复杂性):

costs = [5, 4, 1, 8, 12]

min_cost = min(costs)
max_cost = max(costs)

flag_list = [False] * (max_cost - min_cost + 1)
for cost in costs:
    flag_list[cost - min_cost] = True

sorted_costs = [i + min_cost for i, b in enumerate(flag_list) if b]

为什么要导入sys?“flag”有什么用? 如果你有足够的内存,我会这样做:

import numpy as np
number = 20000
cost = np.random.rand(number) * 1e6 # just for the example
current_min = 1e10 # just for the example
for i,j in enumerate(cost):
    diff = j-cost[i+1:]
    pos = diff > 0
    if pos.any():
        temp = np.min(diff[pos])
        if temp<current_min:
            current_min = temp
print(final estimation: ',current_min)
将numpy导入为np
数量=20000
成本=np.random.rand(数字)*1e6#仅作为示例
当前_min=1e10#仅作为示例
对于枚举中的i,j(成本):
差异=j-成本[i+1:]
pos=diff>0
如果位置为any():
温度=np.最小值(不同位置)

如果“不形成负数”的确切含义是什么?这意味着差值不应小于0。真正的问题陈述涉及以下每一个值作为房屋多年的成本。问题涉及最低成本,因此我以最低的损失出售它。(应该是损失)。例:测试用例:3 5 10 3这里房子可以以5-3=2 PS的价格出售:前3个是成功获得它的数值。