Easy function, please help.

Ethan Furman ethan at stoneleaf.us
Wed Feb 9 20:16:06 EST 2011


Jason Swails wrote:
> However, as surprising as this may be I'm actually with RR on this one 
> (for a little) -- for code readability's sake, you should make your 
> conditional more readable (i.e. don't depend on the fact that the 
> iterations will take your test value down to 0 which conveniently in 
> this case evaluates to False).

while n:  is plenty readable.  n is either something or nothing, and 
something evaluates to True, nothing to False.

> This could encourage you in later cases 
> to think that if this result eventually converged to a different number, 
> say the multiplicative identity instead, that the same approach will 
> work [...]

See above comment -- something or nothing, not mathematical identities.

> def num_digits(n):
>    return len(str(n).replace('-','').replace('.',''))
> 
> Or typecast to an int if you want to neglect decimals before converting 
> to a string, etc.
> 
> Or use recursion!
> 
>  >>> def num_digits(n):
> ...    if n == 0:
> ...       return 0
> ...    else:
> ...       return num_digits(n//10) + 1
> ...
>  >>> num_digits(1)
> 1
>  >>> num_digits(0)
> 0

0 is still one digit.  ;)

~Ethan~



More information about the Python-list mailing list