我有一個小問題要做,因爲我真的找不到出路。是一個比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我想,因爲它是基於相同的原則。
有什麼建議嗎?在此先感謝
你的功能應該做什麼? – khelwood
也許我只是錯過了一些東西(我今天剛剛獲得第一杯咖啡) - 代碼中的'x'和'y'在哪裏?你用它來調用你的函數,但是我沒有看到你在函數中如何改變它。它是全球性的嗎? –
@barakmanos有一部分代碼被省略,因爲它是基於一個機器人手臂和超聲波傳感器。爲了簡單起見,我沒有包含它。如果z小到小於70,則再次調用函數,因爲它有問題。 – LDG