Reputation: 183
Im trying to write a function which counts the number of digits in a number - with no string
operation. here is my code:
def count_digits(n):
count_list=[]
while (n>0):
n=n%10
i=n
count_list.append(i)
n=n/10
return len(count_list)
n=12345
print count_digits(n)
By using %
i get the last digits - in order to add it to a list. By using /
i throw the digit from the number.
The script does not work. For each n
i put, the script just prints 1
.
Thanks!
Upvotes: 0
Views: 663
Reputation: 26688
count_list
stores the digits.
def count_digits(n):
count_list=[]
while (n>0):
count_list.append(n%10)
n-=n%10
n = n/10
return count_list
n=12345
print len(count_digits(n))
Without using a list
def count_digits(n):
count_list=0
while (n>0):
count_list+=1
n-=n%10
n = n/10
return count_list
n=12345
print count_digits(n)
Upvotes: 1
Reputation: 901
Perhaps you can try this, a much simpler approach. No lists involved :)
def dcount(num):
count = 0
if num == 0:
return 1
while (num != 0):
num /= 10
count += 1
return count
Upvotes: 2
Reputation: 1128
There are several problems to your code:
return
statement should be outside of the loop.n = n % 10
statement modifies n
, making it impossible to get the other digits.//
. In Python 3, n / 10
would give a floating point number.0
as having 0
digits. You need to check whether n
is 0
.Here is a corrected version of your code:
def count_digits(n):
if n == 0:
return 1
count_list = []
while n > 0:
count_list.append(n % 10)
n = n // 10
return len(count_list)
Also, as it was said in the comments, since your goal is just to count the digits, you don't need to maintain a list:
def count_digits(n):
if n == 0:
return 1
count = 0
while n > 0:
n = n // 10
count += 1
return count
Upvotes: 3