开发者

Iteration over n values

I'd like to make an iteration to calculate all the possibilities of a given formula. I need to write down nested iteration but couldn't make it right. I am not good at algorithm :(

For calculating all the possibilities(%0-%100) 3 constant{z1,z2,z3} values, I prepared:

a=frange(0,1.0,0.01)
for z1 in a:
  for z2 in a:
    for z3 in a:
      calculate(z1,z2,z3)

and works properly as I expected.

If z is a list which consists开发者_开发百科 of n values(n can be 2-30 in my case), Which algorithm do you suggest to me to handle this? How can I create nested iteration?


The easiest way is to use itertools.product():

a=frange(0,1.0,0.01)
for z in itertools.product(a, repeat=n):
    calculate(*z)

If n really would be 30, this would iterate over 100**30 = 10**60 values. Be prepared to wait.


itertools.product will do what you want (and more). Unfortunately it wants the lists whose products it computes in separate arguments, like this:

>>> list(itertools.product([1,2,3],[1,2,3]))
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

so on the face of it you need to do something like this:

a=frange(0,1.0,0.01)
for (z1,z2,z3) in itertools.product(a,a,a): calculate(z1,z2,z3)

but if you want to use the exact code for different numbers of products you can say

a=frange(0,1.0,0.01)
for (z1,z2,z3) in itertools.product(*(3*[a])): calculate(z1,z2,z3)

or

a=frange(0,1.0,0.01)
for (z1,z2,z3) in apply(itertools.product, 3*[a]): calculate(z1,z2,z3)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜