3

How can I simplify this complex logical condition?

For a much shorter and more readable code

if i < 13:
 linux0[j] = query_res
elif 13 <= i < 27:
 linux1[j] = query_res
elif 27 <= i < 28:
 linux2[j] = query_res
elif 28 <= i < 33:
 linuxDnsServer1[j] = query_res
elif 33 <= i < 41:
 linuxRadius[j] = query_res
elif 41 <= i < 46:
 gen[j] = query_res
elif 46 <= i < 49:
 cdu[j] = query_res
elif 49 <= i < 55:
 avalanche[j] = query_res
elif 55 <= i < 69:
 defensePro_devices[j] = query_res
Kyle Parsons
1,5559 silver badges14 bronze badges
asked Aug 4, 2021 at 19:41

1 Answer 1

4

It's not clear that it's more understandable, but you can put the limits and lists in another list, and iterate over it;

targets = [(12, linux0), (26, linux1), (27, linux2), (32, linuxDnsServer1),
 (40, linuxRadius), (45, gen), (48, cdu), (54, avalanche), (68, defensePro_devices)]
for limit, target in targets:
 if i <= limit:
 target[j] = query_res
 break
answered Aug 4, 2021 at 19:50
Sign up to request clarification or add additional context in comments.

3 Comments

To add: 1) If you need non-consecutive intervals, you can swap the limits with explicit range objects and then use if i in interval in place of if i <= limit. 2) You can also add an else branch at the end of the for to handle the case where no match is found (i.e. when the break statement is never reached)
I was going to put #2 in, but since the original code doesn't print an error, I left it out.
Another way to handle non-consecutive intervals is to use an extra list for the gaps.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.