list comprehension syntax..?
Duncan Booth
duncan.booth at invalid.invalid
Tue Aug 1 13:35:58 EDT 2006
Gregory Guthrie wrote:
> Sorry for a simple question- but I don't understand how to parse this
> use of a list comprehension.
>
> The "or" clauses are odd to me.
>
> It also seems like it is being overly clever (?) in using a lc
> expression as a for loop to drive the recursion.
You are spot on there. It is a list comprehension, but the resulting list
is just thrown away, so using a list comprehension is a complete waste of
time serving only to confuse the issue. Presumably it saved the author a
character or two.
[ exp for var in seq ]
when the result isn't used can be rewritten as:
for var in seq:
exp
and:
exp1 or exp2
when the result is thrown away is just:
if not exp1:
exp2
So:
[ m in [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)
or board[j] for j in range(81) ]
or solve(board[:i]+m+board[i+1:]) for m in'%d'%5**18 ]
is equivalent to:
inner = [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or board[j] for j in
range(81) ]
for m in '3814697265625':
if m not in inner:
solve(board[:i]+m+board[i+1:])
(That inner list comprehension doesn't depend on m, so it doesn't need to
be reevaluated each time round the loop except, again, to save a few
characters.)
The '%d'%5**18 looks to be a silly way to iterate through all possible
digits for m even though it does some of them twice while saving one
character over writing range(1,10).
The strange expression I called 'inner' is a list containing the string
value board[j] if j is in the same row, column or block as i, or an integer
for any other cells. So 'm not in inner' is true only if the value for m is
not already used in that row column or block and is therefore a possible
candidate for that location in the board.
More information about the Python-list
mailing list