2017-02-15 113 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(如有必要),當它檢測到數據的結束或「跳槽」或什麼的。關鍵點:在最方便的地方(這裏,「檢測和提升條件的代碼的上面」)使用異常來處理異常情況。