Skip to content

Instantly share code, notes, and snippets.

@ledakis
Created June 9, 2015 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ledakis/3d263ccfa89f9f227d18 to your computer and use it in GitHub Desktop.
Save ledakis/3d263ccfa89f9f227d18 to your computer and use it in GitHub Desktop.
Python digit counter
#This will count the digits of a number.
#I tried to use mathematics instead of string length.
#I belive it *has* to do it faster, because it will
#only run k times instead of n, where k=length.
#Without having checked how str() works I expect
#they use more loops, thus more computational time.
#Disclaimer: it works with integers at the moment.
#Will have to make it better in the future.
def digits(n):
if not n/10:
return 1
return 1 + digits(n/10)
if __name__ == '__main__':
print digits(12344342342) #11 digits
print digits(1234567890) #10 digit_sum
print digits(123)
print digits(1234567) #7
print digits(19.2) #will count the .2 as well
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment