2017-02-15 117 views
0

我有一个小问题要做,因为我真的找不到出路。是一个比Python更逻辑的问题。当我的结果不准确或错误时,我正在做的是再次调用该方法。我正在使用递归来做到这一点,但很显然,它会返回与递归方法相同的值。递归替代 - 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 - 见的声明局部变量 - 作为递归调用)。我无法真正找到解决方案,我不能使用Iteration我想,因为它是基于相同的原则。

有什么建议吗?在此先感谢

+0

你的功能应该做什么? – khelwood

+0

也许我只是错过了一些东西(我今天刚刚获得第一杯咖啡) - 代码中的'x'和'y'在哪里?你用它来调用你的函数,但是我没有看到你在函数中如何改变它。它是全球性的吗? –

+0

@barakmanos有一部分代码被省略,因为它是基于一个机器人手臂和超声波传感器。为了简单起见,我没有包含它。如果z小到小于70,则再次调用函数,因为它有问题。 – LDG

回答

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 
+0

谢谢我真的很愚蠢,并没有返回到函数的调用。 – LDG

+0

发生的人,乐于帮助! ;-) –

0

我不确定你的代码到底是你想做什么。但是,这避免了递归的大纲代码可能是这样的:

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(如有必要),当它检测到数据的结束或“跳槽”或什么的。关键点:在最方便的地方(这里,“检测和提升条件的代码的上面”)使用异常来处理异常情况。