if - else

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Nov 27 04:27:26 EST 2003


Jeff Wagner <JWagner at hotmail.com> wrote in
news:oanasvs703tipmup24qgc5toggte8uh67n at 4ax.com: 

> This is what I am trying to accomplish:
> 
> def MasterNumberRoutine(SumOfNumbers):
> 
>         #This routine determines if the input is a master number and,
>         if not, #adds the resultant
>         if SumOfNumbers == 11 or  22 or  33:

Strangely, none of the replies I have seen mentioned the obvious problem, 
which is that the line above tests the three conditions "SumOfNumbers==11", 
"22", and "33". If any of these three is true the whole expression is true, 
and both 22 and 33 are values which are always true.

You want to write something like:

    if SumOfNumbers == 11 or SumOfNumbers==22 or SumOfNumbers==33:
        return SumOfNumbers

Or, you might be happier with the snappier:

    if SumOfNumbers in (11,22,33):
        return SumOfNumbers
>             #go back to where you came from, don't continue ...
> 
>         I2 = int(SumOfNumbers / 10)
>         F2 = SumOfNumbers - (I2 * 10)
>         SumOfNumbers = I2 + F2
These lines are trying to do integer division by 10 and then extract the 
remainder. You could use something like:

       I2, F2 = SumOfNumbers//10, SumOfNumbers%10

or, you could do both operations at the same time:

       I2, F2 = divmod(SumOfNumbers, 10)

Those variable names I2 and F2 are exactly meaningful or descriptive 
either.

> 
>         if SumOfNumbers = 10:
>             #If SumOfNumbers = 10, then set it's value to 1
>             SumOfNumbers = 1

It seems to me that this test is completely superfluous. If you removed it, 
and the result was 10, then the recursive call would convert it to 1 
anyway.

>         elif SumOfNumbers > 9:
>             MasterNumberRoutine()
>         else:
>             return SumOfNumbers 
> 
Recursion may look cool, but for many situations, it can be clearer to 
rewrite the whole think as an iterative solution:

def MasterNumberSolution(valueToSum):
    while valueToSum > 9:
        if valueToSum in (11,22,33):
            return valueToSum
        quotient, remainder = divmod(valueToSum, 10)
        valueToSum = quotient + remainder
    return valueToSum


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list