查找是否存在递归指数



我需要编写一个函数,它包含两个参数base和number。如果有一个指数给出数字base ** exp == number,则函数返回True,否则返回False

示例:

check_is_power(2, 16) -> True  # because you have a valid exp here (4)
check_is_power(3, 17) -> False # because there is not a whole positive number as an exp

重要:我只能使用这些函数来解决这个问题:

def add(x: float, y: float) -> float:
return x + y

def subtract_1(x: int) -> int:
return x - 1

def is_odd(n: int) -> bool:
return n % 2 == 1

def divide_by_2(n: int) -> int:
return n // 2

这就是我尝试的:

def check_is_power(base: int, number: int) -> bool:
if number == base:
return True

return check_is_power(base, divide_by_2(number))

现在,我知道我对这个代码有问题,但这是我的开始位置,我想帮助完成这个。谢谢

类似的东西?仅适用于整数和正数

def add(a, b) :
return a + b
def subtract_1(x):
return x - 1
def mul(a, b) :
if b == 1:
return a
if(b == 0):
return 0
return add(mul(a, subtract_1(b)), a)
def exp(a, b) :
if a == 0 and b == 0:
return -1 #should be NaN
if b == 1:
return a
if(b == 0):
return 1
return mul(exp(a, subtract_1(b)), a)

def check_is_power(base, number):
e = 0
if base == 0 and number == 0:
return True
if base <= 0 or number <= 0:
return False
while True:
r = exp(base, e)
if r == number:
return True
if r > number:
break
e = add(e, 1)
return False

print(check_is_power(15, 170859375))

由于我没有看到允许将值的符号从正更改为负的限制,下面是一个非常简单的代码块,似乎可以提供必要的结果。

def add(x: float, y: float) -> float:
return x + y
def is_exponent(x,y):
a = 0
b = y
c = -x          # No mention of not allowing changing the sign of the base to effectively allow subtraction
while b > 0:
b = add(b,c)
a = a + 1

if b < 0:
return False

elif b == 0 and a == x:
return True

elif b == 0 and a < x:
return False

else:
return is_exponent(x,a)

while True:
base = int(input("Enter base "))
value = int(input("Enter value to check "))

if (is_exponent(base, value)):
print(value, "is an exponent of", base)
else:
print(value, "is not an exponent of", base)

choice = input("Do you want to check another pair (y/n)? ")
if choice != 'y':
break

所需要的只是加法函数以及递归地调用";is_exponent"作用

用几个不同的基数来测试这一点似乎是一致的。

@Una:~/Python_Programs/Exponent$ python3 Exponent.py 
Enter base 6
Enter value to check 36
36 is an exponent of 6
Do you want to check another pair (y/n)? y
Enter base 25
Enter value to check 625
625 is an exponent of 25
Do you want to check another pair (y/n)? y
Enter base 25
Enter value to check 125
125 is not an exponent of 25
Do you want to check another pair (y/n)? y
Enter base 17
Enter value to check 4913
4913 is an exponent of 17
Do you want to check another pair (y/n)? 

尝试一下,看看它是否符合练习的精神。

最新更新