Get the number of digits in a number

Asked

Viewed 8,551 times

2

I was asked to make an algorithm in Python to know the number of digits in a number, there is a way to do without the manipulation of strings?

def achaTamanho(x):
    a = str(x)
    if len(a) > 1:
        if a[0] == '0':
            return len(a) - 1
        else:
            return len(a)
    return len(a)


num = int(input("Digite um número: "))
print(achaTamanho(num))
  • 6

    Logarithm in the base 10

  • 2

    Details: https://answall.com/a/239881/64969

  • 2

    Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

3 answers

7

It is always better to do it with math (well, it seems that Python is not so much, it is still good, but it is slow almost equally). I made one use mathematical function ready and another without needing any module. It could simplify making the division, but division costs more than multiplication.

import math 

def achaTamanho(numero):
    numero = abs(int(numero))
    if numero < 2:
        return 1
    count = 0
    valor = 1
    while valor <= numero:
        valor *= 10
        count += 1
    return count

def achaTamanho2(numero):
    numero = abs(int(numero))
    return (1 if numero == 0 else math.floor(math.log10(numero)) + 1)
    
print(achaTamanho(0))
print(achaTamanho(1))
print(achaTamanho(2))
print(achaTamanho(123))
print(achaTamanho(1000))
print(achaTamanho(-1))
print(achaTamanho(-23))
print(achaTamanho(45678))
print(achaTamanho(9999))
print ("")
print(achaTamanho2(0))
print(achaTamanho2(1))
print(achaTamanho2(2))
print(achaTamanho2(123))
print(achaTamanho2(1000))
print(achaTamanho2(-1))
print(achaTamanho2(-23))
print(achaTamanho2(45678))
print(achaTamanho2(9999))

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • 5

    For future reader: if you are interested in knowing how many digits are needed in the base XYZ, change valor *= 10 for valor *= XYZ and math.log10(numero) for math.log(numero, XYZ)

  • 1

    I think you normalized twice the number inside the math.log10: a right at the beginning of achaTamanho2 and another in the call from math.log10

  • 1

    @Jeffersonquesado is true ;)

  • 2

    Beware of "division costs more than multiplication", especially in Python -" . It has been decades - literally, that at a low level - in machine language time, division and multiplication are equivalent - and are completed by dedicated circuits in a single clock cycle. On the other hand, languages like Python are so abstracted from this low level - in Python, each new numerical value is an object of type "int" that has to be built, for example, that this hardware time has no meaning even if the split was 10 times more expensive than a multiplication.

  • 1

    @jsbueno not in the last tests I did a few years ago. At least in whole. And without considering optimizations that the compiler can do to eliminate the division. Are you saying that Python is highly inefficient that even if the division costs much more, it matters little at all? This I even believe.

  • 2

    This - it is trivial that for intensive numerical computations, in Python, you should use a qeu library to perform operations in native code, such as numpy. To calculate the number of digits of a single number, it is irrelevant. Unless it was a web-service to respond to 50,000 such requests per second.

  • now, I got curious about this whole - how did you do these tests? do you have them somewhere? Why for integers in C or other native code, the multiplication and division time should be the same (the division should use more hardware resources, but these resources are there ,"soldiers" on the chip)

  • @jsbueno I did a long time ago, but it’s a very trivial test. I didn’t say the difference is 10x, it’s not big, but multiplication is better than division, I just said that.

  • yes - but in "my account", both should cost 1 clock cycle. but it must be something around, whether in the microcode, or in the compiler code, to take exceptions from the division then.

  • I did not take memory and CPU into account, because I thought it would be an exaggeration, but in operations per second (approximate) both methods were similar (although it depends a lot on the machine that is running): https://repl.it/@inphinit/benchmark-size-digits -- On Windows, on a 16GB RAM machine all tests were almost equal, which varied with each test, so in the matter of operations per second none was apparently advantageous. PS: I liked the first one better, which used the "checking" houses:) +1

  • @Guilhermenascimento in repl.it can’t even be trusted, each execution gives a completely different number, but I believe you, I think that’s what I said, Python is so bad of performance that everything gets bad. It’s that story I tell when Clipper ran Codeblock much faster than the macro to get the same result. Then a company made its version of Clipper and eliminated this difference between them,now Codeblock is as slow as macro :D Meanwhile the community made its version of Clipper (Harbour) and created a way for the macro (or something equivalent) to get almost as fast qto the CB

Show 6 more comments

-4

def achaTamanho(x): 
    return (len(str(x)))
num = int(input("Digite um número: "))
print(achaTamanho(num))

-5

Dude, I did it without using "if" or mathematical expression, just treating the numbers as string and using the "Len" parameter".

def contador(n):
    contagem = len(n)
    return contagem
n = str(input('Informe um numero inteiro: '))
print(contador(n))
  • 3

    Which is the same "solution" as the other answers posted months ago. I highlight this detail of the question: I was asked to do an algorithm in Python to know the number of digits in a number, there is a way to do without strings handling?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.