1

While solving the PS problem, there was a problem with memory excess. I looked it up and found one thing

The size of variable 'a' outside the function and the size of variable 'b' within the function were different.

Here is my test code :

from itertools import permutations
import tracemalloc

def test():
    b = list(permutations(range(10)))
    
tracemalloc.start()
test()
a = list(permutations(range(10)))
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')

for stat in top_stats[:10]:
    print(stat)

and the result is :

/Users/codren/Desktop/Coding_Test/test.py:5: size=234 KiB, count=2000, average=120 B
/Users/codren/Desktop/Coding_Test/test.py:9: size=445 MiB, count=3628805, average=129 B

a size is 445 MB,

b size is 234 KB

I think a is more intuitive because the number of permutations is 3628800.

What made the difference? I'd like you to let me know if you know. Thanks :)

3
  • when scoped variables are no longer needed they get eventually destroyed. b is a scoped variable inside a function. who tells you it hasn't been destroyed already? whatever you test here with tracemalloc is not what you think it is. Commented Aug 15, 2021 at 8:52
  • b is local to the function, so it shouldn't even exist outside of it - i suppose it's just there waiting for the GC to do its work Commented Aug 15, 2021 at 8:52
  • 1
    short-description-of-the-scoping-rules Commented Aug 15, 2021 at 9:05

1 Answer 1

1

b is thrown away because it is not returned by test().

It does not exist after the test() call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.