Easy function, please help.
Rikishi42
skunkworks at rikishi42.net
Wed Feb 9 17:54:13 EST 2011
On 2011-02-09, Michael Hrivnak <mhrivnak at hrivnak.org> wrote:
> Your function only works if n is an integer. Example:
>
>>>> num_digits(234)
> 3
>>>> num_digits(23.4)
> 325
>
> When doing integer division, python will throw away the remainder and
> return an int. Using your example of n==44, 44/10 == 4 and 4/10 == 0
>
> Before each iteration of the while loop, the given expression (in this
> case just n) is evaluated as a boolean. Your function would act the
> same if it looked like this:
>
> def num_digits(n):
> count = 0
> while bool(n):
> count = count + 1
> n = n / 10
> return count
>
> 0 of course evaluates to False as a boolean, which is why the while loop stops.
>
> Just for kicks, this function would work about as well:
>
> def num_digits(n):
> return len(str(n))
What about this one:
import math
def num_digits(n):
return int(math.ceil(math.log(n,10)))
--
When in doubt, use brute force.
-- Ken Thompson
More information about the Python-list
mailing list