MathNYYB
MathNYYB

Reputation: 13

Finding the number of digits in a number restricted number of tools since I am a Python beginner

def digits(n):
  total=0
  for i in range(0,n):
    if n/(10**(i))<1 and n/(10**(i-1))=>1:
      total+=i
    else:
      total+=0
  return total

I want to find the number of digits in 13 so I do the below

print digits(13)

it gives me $\0$ for every number I input into the function. there's nothing wrong with what I've written as far as I can see:

if a number has say 4 digits say 1234 then dividing by 10^4 will make it less than 1: 0.1234 and dividing by 10^3 will make it 1.234 and by 10^3 will make it 1.234>1. when i satisfies BOTH conditions you know you have the correct number of digits. what's failing here? Please can you advise me on the specific method I've tried and not a different one? Remember for every n there can only be one i which satisfies that condition. so when you add i to the total there will only be i added so total returning total will give you i

Upvotes: 0

Views: 41

Answers (2)

Krzysztof Skowronek
Krzysztof Skowronek

Reputation: 2936

your loop makes no sense at all. It goes from 0 to exact number - not what you want.

It looks like python, so grab a solution that uses string:

def digits(n):
  return len(str(int(n))) # make sure that it's integer, than conver to string and return number of characters == number of digits

EDIT: If you REALLY want to use a loop to count number of digits, you can do this this way:

def digits(n):
i = 0
while (n > 1):
    n = n / 10
    ++i

return i

EDIT2:

since you really want to make your solution work, here is your problem. Provided, that you call your function like digits(5), 5 is of type integer, so your division is integer-based. That means, that 6/100 = 0, not 0.06.

def digits(n):
  for i in range(0,n):
    if n/float(10**(i))<1 and n/float(10**(i-1))=>1:
      return i # we don't need to check anything else, this is the solution

    return null # we don't the answer. This should not happen, but still, nice to put it here. Throwing an exception would be even better

Upvotes: 1

MathNYYB
MathNYYB

Reputation: 13

I fixed it. Thanks for your input though :)

def digits(n): for i in range(0,n): if n/(10**(i))<1 and n/(10**(i-1))>=1: return i

Upvotes: 0

Related Questions