Search code examples
pythonpython-3.xloopsiteratordry

Combining Four Different Ranges Effectively


Context

Say I have 4 ranges with four different numbers, A1, A2, B1, B2. I want to perform several operations on the same object, using combinations of those 4 ranges

obj = SomeClass() # SomeClass has a method some_func which manipulates an instance

Simply, I would use 4 for-loops

for a, b in zip(range(A1), range(B1)):
    obj.some_func(a, b)

for a, b in zip(range(A2, -1, -1), range(B1)):
    obj.some_func(a, b)

for a, b in zip(range(A1), range(B2, -1, -1)):
    obj.some_func(a, b)

for a, b in zip(range(A2, -1, -1), range(B2, -1, -1)):
    obj.some_func(a, b)

Question

Is there a way to do this with only 1 for-loop? since using 4 for-loops seems redundant since I'm basically doing the same thing.


Solution

  • If you really wanted only one for loop, you could combine the zips:

    def all_pairs(A1, A2, B1, B2):
        yield from zip(range(A1), range(B1))
        yield from zip(range(A2, -1, -1), range(B1))
        yield from zip(range(A1), range(B2, -1, -1))
        yield from zip(range(A2, -1, -1), range(B2, -1, -1))
    
    for a,b in all_pairs(A1, A2, B1, B2):
        print(a, b)