使用递归查找两个数字乘积的 Python 程序
当需要使用递归技术查找两个数字的乘积时,使用一个简单的 if 条件和递归。
递归计算较大问题的小部分输出,并将这些部分组合起来以给出较大问题的解决方案。
示例
以下是相同内容的演示 -
def compute_product(val_1,val_2): if(val_1<val_2): return compute_product(val_2,val_1) elif(val_2!=0): return(val_1+compute_product(val_1,val_2-1)) else: return 0 val_1 = int(input("Enter the first number... ")) val_2 = int(input("Enter the second number... ")) print("The computed product is: ") print(compute_product(val_1,val_2))
输出
Enter the first number... 112 Enter the second number... 3 The computed product is: 336
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
解释
- 定义了一个名为“compute_product”的方法,它将两个数值作为参数。
- 如果第一个值小于第二个值,则通过交换这些参数再次调用该函数。
- 如果第二个值为 0,则通过传递第一个值并从第二个值中减去“1”并将其添加到函数的结果中来调用该函数。
- 否则,该函数返回 0。
- 在函数外部,用户输入两个数字值。
- 通过传递这两个值来调用该方法。
- 输出显示在控制台上。
广告