我有一个小问题要做,因为我真的找不到出路。是一个比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