Issue
In solid mechanics, I often use Python and write code that looks like the following:
for i in range(3):
for j in range(3):
for k in range(3):
for l in range(3):
# do stuff
I do this really often that I start to wonder whether there is a more concise way to do this. The drawback of the current code is: if I comply with PEP8
, then I cannot exceed the 79-character-limit per line, and there is not too much space left, especially if this is again in a function of a class.
Solution
By using nested for-loops you're basically trying to create what's known as the (Cartesian) product of the input iterables, which is what the product
function, from itertools
module, is for.
>>> list(product(range(3),repeat=4))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 0, 2), (0, 0, 1, 0), (0, 0, 1, 1),
(0, 0, 1, 2), (0, 0, 2, 0), (0, 0, 2, 1), (0, 0, 2, 2), (0, 1, 0, 0),
...
And in your code you can do :
for i,j,k,l in product(range(3),repeat=4):
#do stuff
Based on python documentation, "This function is roughly equivalent to the following code, except that the actual implementation does not build up intermediate results in memory:"
def product(*args, repeat=1):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = [tuple(pool) for pool in args] * repeat
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
Answered By - Mazdak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.