1

To learn Python, I'm working on a game. I've hit a puzzle that may have multiple solutions (recursion? reduce? comprehension?), so I want to know what is the best way (e.g. most "Pythonic", best-performing, readable, etc.). Can you help a newbie learn cool stuff?

The puzzle is to get a list of cartesian coordinates with which to refer to the spaces in the game board--but I want my solution to work for arbitrary number of dimensions (not just 2D chess, but also 3D chess, etc.)

Here's what I've got, and I'm wondering if there are better ways:

def cartc(dimensions):
    """Returns an object that generates a unique tuple of integers (cartesian coordinates) for each spot 
        in the dimensions. 


    Args:
        dimensions: An arbitrarily long sequence range objects. Each range object represents one
            dimension of the space

    Returns:
        an iterable object that generates tuples of integers: e.g. (1, 1)
        
            cartc( [range(3), range(2)] ) generates (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), and (2, 1)
            
    """
    
    # Generate sets of coordinates by joining lists
    tally = [[]]
    for dim in reversed( dimensions ):
        tally = [ [coord] + partial for coord in dim for partial in tally ]
    
    # Convert to tuples
    for coords in tally:
        yield tuple( coords )

0 Answers0