【问题标题】:Python Recursive operationPython递归操作
【发布时间】:2020-11-15 10:09:46
【问题描述】:
main_program = True


def program():
    print('Hello user, please enter a value to choose an option')
    print('select 1 to find the sum of two number')
    print('select 2 to find the product two number')
    print('select 3 to raise a number to a power')
    print('4 to find the reminder two number')
    print('select q for exit')

    choice = input('human enter a value: ')

    global main_program
    while main_program:
        if(choice == '1'):
            sum_of_numbers()

        elif(choice == '2'):
            product_of_numbers(*get_information())

        elif(choice == '3'):
            esponent_of_numbers(*get_information())

        elif(choice == '4'):
            modulo_of_numbers(*get_information())

        elif(choice == 'q'):
            print('program terminated')
            main_program = False
        else:
            print('wrong value entered')


def get_information():
    while True:
        try:
            x = float(input('human enter a value: '))
            y = float(input('human enter second value: '))
            return x, y
        except ValueError:
            print('my processors cannot understand the inputs')


def sum_of_numbers():
    x, y = get_information()
    sum = x + y
    print(sum)
    program()


def product_of_numbers(x, y):
    if(x < y):
        print(product_of_numbers(y, x))
        program()
    if(x == 0):
        print(0)
        program()
    else:
        print(x + product_of_numbers(x, y-1))
        program()


def esponent_of_numbers(x, y):
    if y == 0:
        print(1)
        program()
    elif y % 2 == 0:
        print(esponent_of_numbers(x, y / 2)**2)
        program()
    else:
        print(x * esponent_of_numbers(x, y-1))
        program()


def modulo_of_numbers(x, y):
    if x < y:
        print(x)
    print(modulo_of_numbers(x - y, y))
    program()


program() 

我需要你的帮助。我花了几个小时试图找出这些函数中的问题。 我的老师希望我使用给定 2 个数字的递归操作。 问题是每次我启动程序并初始化函数时都会出现此错误。 “RecursionError:调用 Python 对象时超出最大递归深度” 我没有使用位数,我正在关注 StackOverflow 中其他答案中关于相同参数的代码。 所以我想我真的没有掌握这个问题的概念:

如果用户在主菜单输入“1”: 应提示用户输入两个数字,然后求和(加法) 这两个数字将被打印到屏幕上。 要计算此值,您应该创建一个具有以下签名的函数 其中 x 和 y 可以是整数或浮点类型,返回答案:sum(x,y)。 如果用户在主菜单输入“2”: 应提示用户输入两个正数 x 和 y,以及产品 两个数字中的一个将打印到屏幕上。两个数的乘积可以是 表示为重复的加法运算。例如,54 = 20;这可以是 以另一种方式计算为 (5+5+5+5) = 20。 要计算此值,您应该创建一个具有以下签名的函数 其中 x 是 int 或 float,y 是 int,返回答案:prod(x,y)。 如果用户在主菜单输入“3”: 应提示用户输入两个正数 x 和 y。这 然后应将值 xyxy 打印到屏幕上。将 x 提高到 y 次方,可以 表示为重复乘法。例如,53=12553=125;这可以是 或者表示为55*5=125。 要计算此值,您应该创建一个具有以下签名的函数 其中 x 是整数,y 是整数,返回答案:exp(x,y)。 如果用户在主菜单输入“4”: 应提示用户输入两个正数 x 和 y。然后该值应打印到屏幕上。 x 和 y 的模得到余数 在⌊xy⌋⌊xy⌋之后,并且可以表示为重复减法。例如,5 模 2 = 1;这也可以表示为 5-2-2=1。 要计算此值,您应该创建一个具有以下签名的函数

【问题讨论】:

  • 您的问题是什么?
  • 第一个函数有效。对于其他三个,当他们从 get_information 返回值“RecursionError:调用 Python 对象时超出最大递归深度”时,我真的不知道为什么会发生这种情况
  • 您的所有函数都重复调用其他函数。看起来在大多数情况下,你的函数永远不会返回,这意味着它们会不断地消耗内存,直到你的程序崩溃。与其再次调用program 来返回它,不如让函数结束。
  • 虽然这不会是直接的问题。 modulo_of_numbers 无限调用自己。
  • 您需要将print 放在递归调用之前,否则将永远无法到达。

标签: python recursion math


【解决方案1】:

以下是我在您的原始代码中发现的一些改进:

  1. (错误的主要原因) 您没有指定循环何时停止。例如,在这两个数字的乘积中,print(x + product_of_numbers(x, y-1)) 实际上会无限循环,因为您没有告诉循环在 y 的某个值处停止。
  2. 您的程序永远不会停止,因为您没有在循环中对 main_program 指定条件。
  3. (个人观点) 每次选择的操作完成后,程序应该允许用户选择他想要做的新操作。

以下是我使用的修改后的代码,效果很好:

# This program works only for positive values
main_program = True
def program():
    print('Hello user, please note that this program works only for positive values.')
    print('select 1 to find the sum of two number')
    print('select 2 to find the product two number')
    print('select 3 to raise a number to a power')
    print('select 4 to find the reminder two number')
    print('select q for exit')

    choice = input('human select operation: ')
    global main_program
    if(choice == '1'):
        print(sum_of_numbers())

    elif(choice == '2'):
        print(product_of_numbers(*get_information())-1)
    
    elif(choice == '3'):
        print(esponent_of_numbers(*get_information()))

    elif(choice == '4'):
        modulo_of_numbers(*get_information())

    elif(choice == 'q'):
        print('program terminated')
        main_program = False
    else:
        print('wrong value entered')


def get_information():
    while True:
        try:
            x = float(input('human enter first value: '))
            y = float(input('human enter second value: '))
            return x, y
        except ValueError:
            print('my processors cannot understand the inputs')


def sum_of_numbers():
    x, y = get_information()
    return x + y

def product_of_numbers(x, y):
    if(x < y):
        return product_of_numbers(y, x)
    if(x == 0):
        print('first value is equal to 0, result:', x*y)
        return 1
    else:
        if y==0:
            print('End of calculation')
            return 1
        else:
            res = x + product_of_numbers(x, y-1)
            return res

def esponent_of_numbers(x, y):
    if y == 0:
        print('End of calculation')
        return 1
    elif y % 2 == 0:
        res = esponent_of_numbers(x, y / 2)**2
        return res
    else:
        res = x * esponent_of_numbers(x, y-1)
        return res

def modulo_of_numbers(x, y):
    if x<y:
        print('End of calculation')
        print('The result is: ', x)
        return 1
    if y < x:
        res = modulo_of_numbers(x - y, y)
        return res

while main_program==True:
    program()

您鼓励处理product_of_numersmodulo_of_numbers 中的负值情况。为这两个或类似的用户条目添加约束。

祝你好运

【讨论】:

    猜你喜欢
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 2016-01-22
    相关资源
    最近更新 更多