a to the power of b without (a**b), Python

时间秒杀一切 提交于 2019-12-02 12:23:42

Naive implementation(not the the best of solutions but i think you should be able to follow this one):

def powerof(base, exp):
    results = 1
    for n in range(exp):
        results *= base
    return results


print(powerof(5,2))

Hope it helps.

Try with recursion:

def powerof(base,exp):
    if exp == 0:
        return 1
    if exp == 1:
        return base
    return base * powerof(base, exp-1)

# I want to print 2**8. Suprisingly getting two (incorrect) values as a result
print(powerof(2,8))

So what it does, it calls itself while decreasing the exponent, thus the call will look like: 2*(2*(2*2))) ... when being executed. You could also do this in a for-loop, but recursion is more compact.

I would certainly recommend recursion too, but obviously that's not an option ;-)

So, let's try to fix your code. Why are you trying to return something in your if statement ?

return result
return counter  # here it says "unreachable code". Can I not return more variables at the same time?

You know that when you return, you exit from your function ? This is not what you meant. What I guess you want is to multiply result as long as you did not do it exp times. In other words, you want to repeat the code inside your if statement until you did it exp times. You have a keyword for that : while. And while certainly includes that condition you tried to provide with your if.

Good luck!

edit: btw I don't understand why you say you are getting two results. This is suspicious, are you sure of that ?

You can solve the task "raise a to the power of b without using a**b" in one of the following ways:

>>> a, b = 2, 8
>>>
>>> pow(a, b)
>>> a.__pow__(b)
>>>
>>> sum(a**i for i in range(b)) + 1  # Okay, technically this uses **.
>>>
>>> import itertools as it
>>> from functools import reduce
>>> import operator as op
>>> reduce(op.mul, it.repeat(a, b))
>>>
>>> eval('*'.join(str(a) * b))  # Don't use that one.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!