简体   繁体   中英

Why does the following python code throw a Memory error?

Here is the code:

import itertools

num_cases = int(input())

answer_list = []

while num_cases>0:
    live_ans = []
    question_list = []
    nums = int(input())
    d1 = int(input())
    d2 = int(input())
    sample_space= {d1, d2}
    temp = []

    no_cases = 2**(nums-1)

    combs = itertools.product(sample_space, repeat = nums-1)

    for i in combs:
        temp.append(i)

    for i in temp:
        if sum(i) not in live_ans:
            live_ans.append(sum(i))
        else:
            pass
    live_ans.sort()
    answer_list.append(live_ans)
    num_cases -= 1

for i in answer_list:
    finalans = " ".join(map(str, i))
    print(finalans)

For small inputs like:

1
3
1
2

The program works just fine. Where as for a relatively larger input like:

1
58
69
24

It gives a memory error. I dont cite any reason for this as the code doesn't look memory consuming at all. Isn't it?

Look at your following lines:

no_cases = 2**(nums-1)
combs = itertools.product(sample_space, repeat = nums-1)
for i in combs:
    temp.append(i)

2**58 = 2.8823038e+17
You do the math on why it gets a memory error from here

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