Created
June 9, 2015 09:58
-
-
Save ledakis/3d263ccfa89f9f227d18 to your computer and use it in GitHub Desktop.
Python digit counter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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