On 08/10/2016 11:54, Chris Angelico wrote:
On Sat, Oct 8, 2016 at 9:12 PM, BartC <b...@freeuk.com> wrote:
On 08/10/2016 11:03, Chris Angelico wrote:

On Sat, Oct 8, 2016 at 8:58 PM, meInvent bbird <jobmatt...@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.

Well, there'll be three lots. But it's true there won't be 8 billion elements which is what I immediately thought when the OP said they'd run out of memory. So perhaps something is going on inside run() to account for it.

--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to