Paths in python
<p>Consider a rectangular grid.</p>

<p>I want a short and elegant way of generating a straight path from <code>[x0,y0]</code> to <code>[x1,y1]</code>, where either <code>x0=x1</code> or <code>y0 = y1</code>.</p>

<p>For example, on input <code>[1,3], [3,3]</code> the output <code>[[1,3],[2,3],[3,3]</code> should be generated. Likewise if the input is <code>[3,3], [1,3]</code>.</p>

<p>I have tried <code>[[i,j] for i in range(self.origin[0],self.end[0]+1) for j in range(self.origin[1], self.end[1]+1)]</code>, but it only works for the case where the input is ordered.</p>

<p>Your question states that the solution from <code>x -&gt; y</code> should be the same as the solution <code>y -&gt; x</code>, i.e. we're only interested in defining the points on the path, not in any ordering of those points. If that's true, then simply find out which path has the smaller <code>x</code> (or <code>y</code>) and designate that as the origin.</p>

<pre><code>origin = (3,3)
dest = (1,3)

origin, dest = sorted([origin, dest])

path = {(i,j) for i in range(origin[0], dest[0]+1) for j in range(origin[1], dest[1]+1)}
# note that this is now a set comprehension, since it doesn't make any sense
# to use a list of unique hashable items whose order is irrelevant
</code></pre>

<p>of course, this solves any obstructionless 2-D pathfinding. If you know that only one direction is changing, then only look in that direction.</p>

<pre><code>origin, dest = sorted((origin, dest))
if origin[0] == dest[0]:  # y is changing
    path = {(origin[0], j) for j in range(origin[1], dest[1]+1)}
else:  # x is changing
    path = {(i, origin[1]) for i in range(origin[0], dest[0]+1)}
</code></pre>

python python-3.x