[newbie] Recursive algorithm - review

Chris Angelico rosuav at gmail.com
Sat Jan 4 06:18:09 EST 2014


On Sat, Jan 4, 2014 at 10:09 PM, Wiktor <look at signature.invalid> wrote:
> On Sat, 4 Jan 2014 13:02:37 +1100, Chris Angelico wrote:
>> And in fact, you might want to turn this whole branch into something
>> that harks to a more functional programming style:
>>
>> return all((check(towers, i) for i in range(len(towers)))
>
>   Great. I didn't know all() before. :-)
>   Now check() function looks very neat.

Sometimes they aren't any help at all (puns intended), but sometimes
any() and all() are exactly what you want.

>   Although 'if' statement must now looks like: 'if x is not None:'. Earlier x
> never was going to be 0. Now it can be.

Nicely spotted, I hadn't thought of that implication.

>>>         random.shuffle(row)                    # at every recursion
>>
>> Again, I wouldn't wrap comments onto unrelated lines. You see how
>> confusing this looks, now that I take this line out of context? Same
>> will happen if it throws an exception.
>
>   Yeap. Now I see it. Never gonna do that again. :-)

Please note that I didn't intend this as criticism, or a "this is the
rule so follow it" directive, just as advice :) I'm not bearing down
on you with a sergeant-major's string of orders, just offering some
tips that you're free to ignore if you like. And in fact, you probably
WILL ignore some of them, at some points, even if you believe them to
be good advice now - every stylistic rule must be secondary to the
overriding rule "Make it work and be readable", and should be broken
if it violates the prime directive.

>> This is the same as you have at the top of 'if not towers'. Can you be
>> confident that row is None any time towers is None? If so, just move
>> this up above the other check and save the duplication.
>
>   row is None at start, but later it is list - sometimes an empty list. For
> that cases this if statement was written. If row == [] -> generate new random
> row that I can pop out from.

Yes, but will you ever pass a non-None row and a None towers? If not,
you can deduplicate that bit of code by simply checking one before the
other.

>   Thank you for all Your comments.

My pleasure! Always happy to help out.

ChrisA



More information about the Python-list mailing list