Itβs actually quite simple to calculate the indices for the diagonals for the case repeat=2 :
def diagonal_product(inp): inp = tuple(inp) n = len(inp)
Just to show the results:
>>> list(diagonal_product(range(4))) [(0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 2), (3, 0), (2, 1), (1, 2), (0, 3), (3, 1), (2, 2), (1, 3), (3, 2), (2, 3), (3, 3)] >>> list(diagonal_product(range(3))) [(0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 2), (2, 1), (1, 2), (2, 2)]
The function itself may be a little more complicated (or slower) than it should be, but so far I have not been able to find any reference implementation for this case.
If you enter range you can also avoid all indexing and just return the indexes:
def diagonal_product(n): # upper left triangle for i in range(n): for j in range(i+1): yield ij, j # lower right triangle for i in range(1, n): for j in range(ni): yield nj-1, i+j list(diagonal_product(3)) # [(0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 2), (2, 1), (1, 2), (2, 2)]