def geo():
start = int(input()) # starting number
multiplier = int(input()) # the multiplier
length = int(input()) # how long the list should be
for i in range(length):
x = start * multiplier ** i
print(x, "", end = "")
print()
我需要根据用户输入创建递归几何函数。我知道如何非递归地处理它,但我如何递归地处理它?提前致谢。
即:如果用户输入
start = 1
multiplier = 2
length = 5
Output: 1, 2, 4, 8, 16
编辑:感谢所有的例子,我现在理解递归的方式好多了。
答案 0 :(得分:0)
删除for循环。 而不是通过参数中的递减递归地调用函数。 创建一个以整数作为参数的函数,并每次调用它直到满足条件。
def geo(start, multiplier, length, i=0):
if length <= 0:
exit() #or use a return statement
x = start * multiplier ** i
print(x, "", end = "")
print()
geo(start, multiplier, length-1, i+1)
start = int(input())
multiplier = int(input())
length = int(input())
i=0
geo(start, multiplier, length, i)
答案 1 :(得分:0)
假设您有一个循环要转换为递归函数:
for i in range(length):
x = start * multiplier ** i
您需要做的是:
i < length
)在此功能之前执行此操作,因为您需要此值
length = int(input()) # how long the list should be
start = int(input()) # starting number
multiplier = int(input()) # the multiplier
def recursive_geo(i):
# stop condition
if i == length:
return 1 # since the value will be multiplied by the previous values, you don't want to use 0 or any other value
else:
print(x, "", end = "")
print()
return start * multiplier ** i * recursive_geo(i+1)
答案 2 :(得分:0)
使用任何递归函数,您需要一个基本案例和一般(递归)案例。
让我们从您当前的代码开始获取输入,但不是立即计算值,而是调用递归函数。
def geo():
start = int(input()) # starting number
multiplier = int(input()) # the multiplier
length = int(input()) # how long the list should be
result = geo_rec(start, multiplier, length)
print(result)
def geo_rec(start, multiplier, length):
print(start) # As per your current program
# Base case check
if length = 0:
return start
# Recursive case
else:
start = start * multiplier
length = length - 1
geo_rec(start, multiplier, length)
现在考虑一下,如果长度为0,我们会得到什么?我们将开始 - 这很好。如果length = 1,我们将递归一个级别,然后返回start(此时将是我们的原始start *乘数) - 也很好。
请注意,每次运行递归情况时,我们都会逐步处理基本情况?