[Python Edinburgh] How to do dynamic nesting of loops

James Doig jamesdoig at gmail.com
Tue Nov 18 16:17:49 CET 2014


Hi Doug,
Lists nested like this ( e.g: [1, [2, 3, [4 ,5 ,6 ,7]]] ) can be thought of
as "tree" data structures.... Just incase you wanted to categorise the
problem to aid future googling :)

Cheers,

James

On 18 November 2014 12:56, Magnus Hagdorn <magnus.hagdorn at marsupium.org>
wrote:

> Hi Doug,
> I think you will need to write an iterator which will return a tuple of
> indicies.
>
> How do you decide on the number of nested loops?
>
> Your program might looks something like
>
> def myIterator(some,args):
>   white some condition:
>       do some stuff to figure out what to do
>       yield (i,j,k,...)
>
> for indicies in myIterator(...):
>     do something with the tuple of indicies
>
> Hope this gives you a starting point
>
> Cheers
> magi
>
>
>
> On 18/11/14 12:08, Douglas Houston wrote:
>
>> Hi all,
>>
>> I'm a bit stuck with this so maybe someone can help me.
>>
>> I'm writing a little program that needs to iterate through several
>> nested 'for' loops. However, the number of loops (and therefore the
>> depth of the nesting) cannot be predetermined.
>>
>> I've read that lots of nested loops are bad form anyway, and that "you
>> should do it with functions instead".
>>
>> However I still can't work out how to set the number dynamically.
>>
>>
>> for ((l=0; l<10; l++)); do
>> ​ ​
>>   for ((m=0; m<10; m++))
>> ​;​
>> do
>> ​ ​
>> for (n=0; n<10; n++)); do
>> ​ ​
>> something
>> ​ that uses l, m and n​
>>
>>      done
>>    done
>> done
>>
>> So this is what it needs to look like if nest_depth=3
>>
>> But how do I write a program that iterates something
>> ​ for nest_depth=4 (which in this case would use l, m, n and o)​, or any
>> other number (which can't be predicted)?
>>
>> cheers,
>> Doug
>>
>> PS I didn't write this in Python just for speed, but feel free to reply
>> in Python if you want - the practice would be good for me.
>>
>>
>> _______________________________________________
>> Edinburgh mailing list
>> Edinburgh at python.org
>> https://mail.python.org/mailman/listinfo/edinburgh
>>
>>
> _______________________________________________
> Edinburgh mailing list
> Edinburgh at python.org
> https://mail.python.org/mailman/listinfo/edinburgh
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edinburgh/attachments/20141118/6868e409/attachment.html>


More information about the Edinburgh mailing list