-1

This code is ugly and not Pythonic. I am new to python not new to programming. Instead of guessing on one of many possible refactorings, could you tell me the pythonic way to do this?

As you can see a bunch of variables (forward, left, right, etc) are set up with a floating point number. I want to store in a variable "closest_dir" a string name for the variable which contained the smallest value.

forward = calc_range(msg.ranges, 359, 0, 15)
right = calc_range(msg.ranges, 270, 271, 15)
left = calc_range(msg.ranges, 90, 91, 15)
back = calc_range(msg.ranges, 180, 181, 15)
narrow_l1 = sum(msg.ranges[83:87])/5
narrow_l2 = sum(msg.ranges[88:92])/5
narrow_l3 = sum(msg.ranges[93:97])/5
narrow_r1 = sum(msg.ranges[273:277])/5
narrow_r2 = sum(msg.ranges[268:272])/5
narrow_r3 = sum(msg.ranges[263:267])/5
closest_dist = min(narrow_l1, narrow_l2, narrow_l3, narrow_r1, narrow_r2, narrow_r3,
                   forward, left, right, back)
if (closest_dist == forward):
    closest_dir = "forward"
elif (closest_dist == left):
    closest_dir = "left"
elif (closest_dist == right):
    closest_dir = "right"
elif (closest_dist == back):
    closest_dir = "back"
elif (closest_dist == narrow_l1):
    closest_dir = "narrow_l1"
elif (closest_dist == narrow_l2):
    closest_dir = "narrow_l2"
elif (closest_dist == narrow_l3):
    closest_dir = "narrow_l3"
elif (closest_dist == narrow_r1):
    closest_dir = "narrow_r1"
elif (closest_dist == narrow_r2):
    closest_dir = "narrow_r2"
elif (closest_dist == narrow_r3):
    closest_dir = "narrow_r3"
else:
    closest_dir = "bug"
halfer
  • 19,824
  • 17
  • 99
  • 186
pitosalas
  • 10,286
  • 12
  • 72
  • 120
  • @johnrsharpe you were a little quick on the draw. This question is actually totally different. It is not about creating a number of variables at all! – pitosalas Jul 28 '19 at 17:16
  • it is though ... `d = {'narrow_l1':value,'narrow_l2':value...}; for key,val in d.items(): if val == whatever: print key` – Joran Beasley Jul 28 '19 at 19:44

1 Answers1

6

Use a dictionary.

foos = {
    'forward': calc_range(msg.ranges, 359, 0, 15),
    'right': calc_range(msg.ranges, 270, 271, 15),
    'left': calc_range(msg.ranges, 90, 91, 15),
    'back': calc_range(msg.ranges, 180, 181, 15),
    'narrow_l1': sum(msg.ranges[83:87]/5),
    'narrow_l2': sum(msg.ranges[88:92])/5,
    'narrow_l3': sum(msg.ranges[93:97])/5,
    'narrow_r1': sum(msg.ranges[273:277])/5,
    'narrow_r2': sum(msg.ranges[268:272])/5,
    'narrow_r3': sum(msg.ranges[263:267])/5,
}

closest_dir = min(foos, key=foos.get)

min uses the dict iterator, which returns the keys, and the key argument says that foo.get(x) will determine the "size" of each key x for comparison purposes.

chepner
  • 497,756
  • 71
  • 530
  • 681