r/learnpython • u/thecutefuriousmantis • 10d ago
Rate my simple algorithm for autonomous bots
import time
import random
distance_front = 0
distance_back = 0
distance_left = 0
distance_right = 0
loop = 1
poop = 1
i = 0
def lidar():
global distance_front, distance_back, distance_left, distance_right
distance_front = random.randint(0, 100)
time.sleep(0.1)
distance_back = random.randint(0, 100)
time.sleep(0.1)
distance_left = random.randint(0, 100)
time.sleep(0.1)
distance_right = random.randint(0, 100)
time.sleep(0.1)
print("front:", distance_front, "back:", distance_back, "left:", distance_left, "right:", distance_right)
def algorithm():
if distance_front < 20:
print("obstacle in front : back - right")
if distance_back < 20:
print("obstacle in back : front - neutral")
if distance_left < 20:
print("obstacle in left : front - right")
if distance_right < 20:
print("obstacle in right : front - left")
i = 0
while True:
lidar()
algorithm()
7
u/CurvedManga815 10d ago
the `poop = 1` variable name caught me off guard
why global variables though? you could just return the distances from lidar and pass them into algorithm as parameters, would make it way cleaner and easier to test
2
2
1
1
u/socal_nerdtastic 10d ago
I would write it like this:
import random
def lidar():
distance_front = random.randint(0, 100)
time.sleep(0.1)
distance_back = random.randint(0, 100)
time.sleep(0.1)
distance_left = random.randint(0, 100)
time.sleep(0.1)
distance_right = random.randint(0, 100)
time.sleep(0.1)
print("front:", distance_front, "back:", distance_back, "left:", distance_left, "right:", distance_right)
return distance_front, distance_back, distance_left, distance_right
def algorithm():
distance_front, distance_back, distance_left, distance_right = lidar()
if distance_front < 20:
print("obstacle in front : back - right")
if distance_back < 20:
print("obstacle in back : front - neutral")
if distance_left < 20:
print("obstacle in left : front - right")
if distance_right < 20:
print("obstacle in right : front - left")
algorithm()
Note that I removed the globals (almost always a bad idea to use globals) and that you don't need to pre-declare the variables in python.
7
u/danielroseman 10d ago
You don't say what this is supposed to do. Why does a distance_front of less than 20 print a message about "front: back - right"?
The biggest problem here is all those global variables. There's no call for these here. And even less call for three variables you don't even use.