问题
Struggling with an exercise that asks me to write a**b without this operator. Tried to write something myself but am not getting correct results. Instead of one value am getting two, both incorrect. Seems like the counter doesnt really increase. May I ask for help? Thanks!
def powerof(base,exp):
result=1
counter=0
# until counter reaches exponent, go on
if counter<=exp:
# result multiplies itself by base, starting at 1
result=result*base
# increase counter
counter=counter+1
return result
return counter # here it says "unreachable code". Can I not return more variables at the same time?
else: # counter already reached exponent, stop
return
# I want to print 2**8. Suprisingly getting two (incorrect) values as a result
print(powerof(2,8))
回答1:
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.
回答2:
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.
回答3:
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 ?
回答4:
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.
来源:https://stackoverflow.com/questions/42299891/a-to-the-power-of-b-without-ab-python