简体   繁体   中英

Python Traceback Memory Error

I'm writing in python and this is what I whant to do: The first line of the input contains the number of plates n (1≤n≤1000). Each of the following n lines contains one positive integer less than or equal to 1000, denoting the weight of each plate. Output one integer, the combined weight closest to 1000. In case there exist two such numbers which are equally close to 1000 (eg 998 and 1002), pick the greater one (in this case 1002).

My code looks like this righet now:

from itertools import permutations, chain
N=int(input())
s=0
vikter=[]
while (N>s):
    vikt=int(input())
    vikter.append(vikt)
    s=s+1
c = chain(*(list(permutations(vikter, i)) for i in range(1, len(vikter) + 1)))
result = min(c, key = lambda x: (abs(sum(x) - 1000), -sum(x))) 
print(result)

But this code is giving me this memory error:

Traceback (most recent call last):
File "C:\Users\Hanna\Documents\walrusweights.py", line 9, in <module>
c = chain(*(list(permutations(vikter, i)) for i in range(1, len(vikter) + 1)));
File "C:\Users\Hanna\Documents\walrusweights.py", line 9, in <genexpr>
c = chain(*(list(permutations(vikter, i)) for i in range(1, len(vikter) + 1)));
MemoryError

what can I do to avoid this error?

Your problem is that you are using brute force where it is not applicable. You are trying to generate all possible permutations of a list that has (in the worst case) a 1000 elements. The number of permutations of such as list is 1000!, which is too large to be processed in the lifetime of this universe. Instead, you may look at Dynamic Programming or a Branch and Bound algorithm to implement this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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