递归的替代方法 - Python

时间:2017-02-15 09:19:23

标签: python recursion logic

我有一个小问题要做,因为我真的找不到出路。是一个逻辑问题而不是Python问题。我正在做的是当结果不准确或错误时再次调用方法。我使用递归来执行此操作,但显然,它返回的值与调用的递归方法一样多。

我正在做的是使用该方法通过超声波传感器找到机器人手臂的“z”,当传感器的结果不准确时,我希望再次调用该方法再次重新启动该过程。

def get_z_from_ultrasonic_sensor(self, uarm, x, y):

    # clear all IO data
    self.serial_port.reset_input_buffer()
    self.serial_port.reset_output_buffer()

    count = 0
    z = 110
    uarm.set_position(x, y, z, 1)
    time.sleep(2)
    global input
    # if self.count is 1:
    #     while True:
    #         print(self.serial_port.readline())
    while True:
        # if z is to small, means that has not been detected well, recursive call
        if z < 70:
            self.get_z_from_ultrasonic_sensor(uarm, x, y)

        # check if input is an integer else, recursive call
        try:
            input = int(self.serial_port.readline())

            if input > 160:
                break
        except:
            break

        if input <= 116:
            # print("Distance:", int(input))
            break
        else:
            count = count + 1
            # print("Distance:", int(input))
            # print("Z", z)
            if count is 5:
                z = z - 1
                count = 0
                print("US Distance:", int(input))
                print("Z Robot", z)
        uarm.set_position(x, y, z, 1)

    if z is 110:
        pass
    print("Z to Write:", z)
    # self.count += 1
    return z-6

我想要的只是返回一个值,而不是递归调用的值(现在返回第一个值为'z',然后返回多个z = 110 - 请参阅局部变量的声明 - as递归调用)。我无法真正找到解决方案,我不能使用Iteration,因为它基于相同的原理。

有什么建议吗?提前致谢

2 个答案:

答案 0 :(得分:1)

我会刺伤。也许这就是你要找的东西。

def function(x, y):

    count = 0
    z = 110
    global input

    try:
        input = int(serial_port.readline())
    except:
        return function(x,y)


    if z < 70 or input <= 116:
        return function(x, y)

    else:
        count = count + 1
        if count == 5:
            z = z - 1
            count = 0
            # do something

    return z

答案 1 :(得分:1)

我不确定你的代码究竟是你要做什么的。但是避免递归的大纲代码可能如下所示:

while True:
    try:
        value = get_input()
    except ValueError:
        # print an error message about value, if not already done
        continue # have another go at getting valid input
    except EOFError:
        break # get out of the infinite loop

    # do something with value

当提供错误输入时,get_input将raise ValueError;当检测到数据结束或“退出”或其他任何内容时,raise EOFError(如果需要)。

关键点:使用异常在最方便的地方处理异常情况(此处,“检测并提高条件的代码”上方)。