how to refactor nested for loop into smaller for loop assume each of them independent?
Chris Angelico
rosuav at gmail.com
Sat Oct 8 06:54:01 EDT 2016
On Sat, Oct 8, 2016 at 9:12 PM, BartC <bc at freeuk.com> wrote:
> On 08/10/2016 11:03, Chris Angelico wrote:
>>
>> On Sat, Oct 8, 2016 at 8:58 PM, meInvent bbird <jobmattcon at gmail.com>
>> wrote:
>>>
>>> how to refactor nested for loop into smaller for loop assume each of them
>>> independent?
>>>
>>> because memory is not enough
>>>
>>> for ii in range(1,2000):
>>> for jj in range(1,2000):
>>> for kk in range(1,2000):
>>> print run(ii,jj,kk)
>>
>>
>> Since you're using Python 2, you could try xrange instead of range.
>> But it won't make a lot of difference. You're trying to call your run
>> function 8,000,000,000 times... that is a *lot* of function calls.
>> Consider a faster algorithm instead!
>
>
> Printing even one character 8 billion times is likely to take quite a few
> hours too.
>
> The OP's code however is a good demonstration of how crazy Python's original
> for-range loop was: you need to construct a list of N elements just to be
> able to count to N. How many years was it until xrange was introduced?
Hardly matters in this case. The memory usage of a list of 2000 ints is:
>>> sys.getsizeof(range(2000))
16072
>>> 2000 * sys.getsizeof(1999)
48000
About 64KB. Not overly significant. (A bit less than the naive figure
of 64,072 bytes, because the low integers are cached.) Even if run()
is defined as merely returning an empty string, it's going to take a
long time to print eight billion newlines...
ChrisA
More information about the Python-list
mailing list