简体   繁体   English

在 python 中处理大列表的更有效方法?

[英]More efficient way to handle big lists in python?

I'm writing a python script to solve this exercise:我正在编写一个 python 脚本来解决这个练习:

Given in input a vector V of N integers we want to find, for each size between 1 and N, the maximum of the minimum's of every contiguous subsequence in the vector.在输入中给定一个包含 N 个整数的向量 V,对于 1 到 N 之间的每个大小,我们要找到向量中每个连续子序列的最小值的最大值。

The script I wrote works fine with N<1000 but when I try it with greater values, it just keeps running without ending.我编写的脚本在 N<1000 下运行良好,但是当我尝试使用更大的值时,它只会继续运行而不会结束。 I guessed it's too slow because of the 3 for-loops and the many.append() to big lists, but how can I solve that?我猜它太慢了,因为 3 个 for 循环和 many.append() 到大列表,但我该如何解决呢? Or am I wrong and there is another problem I don't see?还是我错了,还有另一个我看不到的问题?

f_name = input("Inserire nome del file: ")
 
f_in = open("inputs/"+f_name, "r")
f_out = open("outputs/"+f_name, "w")
 
# n = int(input())
n = int(f_in.readline())
 
v_s = f_in.readline().rstrip('\n').split()
v = [int(i) for i in v_s]
 
maxs = []
 
for size in range(1, n+1):
    mins = []
    for i in range(n):
        subseq = []
        if (i+size <= n):
            for j in range(size):
                subseq.append(v[i+j])
        if (len(subseq) > 0):
            mins.append(min(subseq))
    maxs.append(max(mins))
 
for max in maxs:
    f_out.write(str(max) + " ")
 
f_in.close()
f_out.close()

Here are some examples of input and output. 以下是输入和 output 的一些示例。

The appends in python are pretty fast, but your algorithm is too slow -- you have three nested loops which have on the order of N elements each, with total complexity of O(n^3). python 中的追加非常快,但是您的算法太慢了——您有三个嵌套循环,每个循环大约有 N 个元素,总复杂度为 O(n^3)。

This means that with careful optimization, maybe you can handle 2000 values or 3000 values... but your biggest example is 500000 values, so this is not going to help.这意味着通过仔细优化,也许您可以处理 2000 个值或 3000 个值......但您最大的例子是 500000 个值,所以这不会有帮助。

If you want to solve this, you need to rewrite the program so it does not have three nested loops.如果你想解决这个问题,你需要重写程序,使它没有三个嵌套循环。 This problem is well-known, and you can find solutions on the internet with no nested loops, O(n) complexity.这个问题是众所周知的,你可以在互联网上找到没有嵌套循环的解决方案,O(n) 复杂度。

Try this:尝试这个:

from numpy import array_split

f_name = input("Inserire nome del file: ")

with open("{}/{}".format("inputs", f_name), "r") as fp:
    lines = fp.readlines()

n = int(lines[0])
v = [int(s.strip()) for s in lines[-1].split()]

maxs = []
n += 1
for i in range (1 , n):
    my_mins = [min(val) for val in array_split(v, i)] 
    maxs.append(max(my_mins))

output = [str(m) for m in maxs]
output = " ".join(output)

with open("{}/{}".format("outputs", f_name), "w") as fp:
    fp.write(output)

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

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