[英]Recursive function to make a^b
My recursive function doesn't seem to be working - it's supposed to take parameters a
and b
and return a^b
. 我的递归函数似乎不起作用-应该采用参数
a
和b
并返回a^b
。
Here it is: 这里是:
def power(a, b):
If b == 0:
return
return a * power(a, b-1)
power(2, 3)
Base case return statement is null. 基本案例的返回语句为null。 You should return 1 (since
a^0 = 1
for a != 0
). 您应该返回1(因为
a^0 = 1
表示a != 0
)。
if b == 0:
return 1
You might want to handle the case for a = 0
separately though, since 0^0
is mathematically undefined: 但是,您可能想单独处理
a = 0
的情况,因为0^0
在数学上是未定义的:
if a == 0:
if b > 0:
return 0
else
# raise an exception here?
def power(a, b):
if b == 0:
return 1;
return a * power(a, b - 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.