How do I solve a potentiation problem in an alternative way?

Asked

Viewed 7,020 times

1

I need help regarding the resolution of a potentiation problem in an alternative way.

The goal is to show the result of the potentiation and the number of characters (or numbers) that appear in the result. The code I will put next I managed to put to work through some character conversions to integer and vice versa.

base = input('Base: ')
expoente = input('Expoente: ')
potencia = int(base) ** int(expoente)
print('Potência: %d' %potencia)
digito = len(str(potencia))
print('Digitos: %d' %digito)

However, when I made a call not specifically to the mathematical library, I ended up having no success in solving the problem. The result of the variable potencia is correct, but the result of the variable digito appears erroneously.

The code that did not work is similar to the previous one, it has only the changes below compared to the above.

# potencia = int(base) ** int(expoente) (Colocado como comentário para visualização)
import math
potencia = math.pow(int(base),int(expoente))

I do not know if the result of the variable potência is an integer after the call of the mathematical library, or a character type variable, including so I am trying to convert the supposed integer to character by using the function len().

How could you solve the problem according to the second code?

  • The return of math.pow is float. I can’t understand what the problem is. I’ve read your question 5 times. Please try to be more succinct and specific. Try to answer the following: 1. What are you trying to do? 2. What is the expected result? 3. What is the current result (problematic)?

  • Okay. I’m trying to get the correct number of the variable digit through the second way of doing the code. That is, through the use of the mathematical library. The number of the variable digit appears the number of characters of the word power, ie, appears with the result 8.

1 answer

2

The exit is completely correct.

Take the example

import math
res = math.pow(2, 8) # Saída: 256.0
len(str(res)) # Saída: 5

This is because when converting the variable res (who’s kind float) for string floating point and decimal place shall also be taken into account.

If you want to ignore the decimals if the number is integer you can do the check using the function is_integer().

Example:

import math

def teste(base, exp):
    res = math.pow(base, exp)
    digitos = 0    

    if(res.is_integer()):
        digitos = len(str(int(res)))
    else:
        digitos = len(str(res))

    print('resultado: %s \t digitos: %s' % (res, digitos))

teste(2, 8)      #resultado: 256.0         digitos: 3
teste(1.5, 8)    #resultado: 25.62890625   digitos: 11
teste(3.0, 8)    #resultado: 6561.0        digitos: 4

Browser other questions tagged

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