Home > Back-end >  Reduce if loops to a single line
Reduce if loops to a single line

Time:12-22

I want to reduce the below if loops in Python. Is there any efficient way?

if a and b:
  print("case1")
elif not a and b:
  print("case2")
elif not a:
  print("case3")

CodePudding user response:

While I would recommend against this type of code, if this was some sort of requirement, you could technically do:

a = True
b = False

{(True, True): lambda: print("case 1"), (False, True): lambda: print("case 2"), (True, False): lambda: print("case 3")}.get((a, b), lambda: None)()

If I had a little wiggle room to improve this slightly I might do:

a = True
b = False
lookup = {
    (True, True): lambda: print("case 1"),
    (False, True): lambda: print("case 2"),
    (True, False): lambda: print("case 3")
}
lookup.get((a, b), lambda: None)()

However, I would personally almost certainly use something close to your original answer:

a = True
b = False

if a:
    if b:
        print("case1")
else:
    if b:
        print("case2")
    else:
        print("case3")

This version more explicitly shows the case that does not print() and might highlight a potential bug.

CodePudding user response:

print("case1" if a and b else "case2" if not a and b else "case3")

CodePudding user response:

That is not loops. That is just if statements. Having it on one line just make it hard to read. These kind of problems must be broken down to write better code.

if a and b:
  print("case1")
elif not a and b:
  print("case2")
elif not a:
  print("case3")

First you have, if both, then you have if not a and b (a is false b is true), lastly only if not a. This code is readable and therefore good. I would not change it.

  • Related