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 :)

martineau
  • 119,623
  • 25
  • 170
  • 301
codren
  • 11
  • 2
  • 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. – Patrick Artner Aug 15 '21 at 08: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 – gimix Aug 15 '21 at 08:52
  • 1
    [short-description-of-the-scoping-rules](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – Patrick Artner Aug 15 '21 at 09:05

1 Answers1

1

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

It does not exist after the test() call.

log0
  • 10,489
  • 4
  • 28
  • 62