My backwards logic

Chris Angelico rosuav at gmail.com
Sat Sep 6 01:44:48 CEST 2014


On Sat, Sep 6, 2014 at 3:44 AM, Seymore4Head
<Seymore4Head at hotmail.invalid> wrote:
> BTW since I am getting no grade, I much prefer the answer than a hint.
> The best hint IMO is to tell me how you would do it.

But for your own learning, it's still better for you to do things
yourself. Giving you the answer doesn't teach you nearly as
effectively as giving you a hint and having you work out the answer
yourself.

But telling you how we'd do it can be useful too, especially when we
get down to the detaily bits where there are lots of ways to do
things. For instance, there's been a suggestion made a few times to
break the primality test out into a function... but compare these two:

def isprime(n):
   """Return True iff n is prime"""

def find_factor(n):
    """Return a factor of n, or None if n is prime"""

Aside from inverting the truth value, these are both tests of
primality - you can write "if isprime(n):" or "if find_factor(n):" and
they'll both work. (The latter is actually "iscomposite".) But the
second function is giving you a bit more information - it tells you
what factor it found.

As a general rule, try to avoid throwing information away. To prove
that n is composite, your function found a factor. Returning that,
rather than a boolean value, might make your function more useful; and
it's zero cost, because you know that factors of a number will never
be zero.

ChrisA



More information about the Python-list mailing list