Search code examples
pythonmatrixinfix-notationinfix-operator

python infix operator on a list of objects


I'm using a library for mathematical optimization (PICOS) in a jupyter notebook.

In PICOS, the symbols // and & are infix operators for vertical and horizontal concatenation, to build matrices out of blocks. Note that I cannot use numpy.bmat because the blocks are not numpy objects.

If I have a list of blocks, say [A,B,C], I would form a matrix by concatenating them horizontally with the notation A & B & C, for instance. The problem arises when the list contains hundreds of symbols and I cannot build the matrix by hand. Is there a simple way of interposing an infix between each symbol in a list?


Solution

  • I should have been less hasty. I just did it with a recursive function:

    def concat_horizontal(lst):
    if len(lst) == 2:
        return lst[0] & lst[1]
    else:
        return concat_horizontal([lst[0] & lst[1]] + lst[2:]) 
    

    and an analogous one for the vertical concatenation. Yay, recursion!