Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain if else elegantly

Tags:

python

I have an odd piece of code. It's smelly but I can't think of way to make if more clear.

What I'm trying to do is remove the largest item from either the tail of the left list or the head of right list. I ended up with this code.

if not left:
  right.pop(0)
elif not right:
  left.pop(-1):
elif len(left[-1]) < len(right[0]):
  right.pop(0)
else:
  left.pop(-1)

The bodies of the conditions are exact duplicates of each other, yuck.

Is there an elegant way to restructure this code to minimize duplication?

like image 491
deft_code Avatar asked Dec 17 '22 03:12

deft_code


2 Answers

Chain your conditions instead, and eliminate redundant terms.

if (not left) or (right and (len(left[-1]) < len(right[0]))):
  right.pop(0)
else:
  left.pop(-1)
like image 123
Ignacio Vazquez-Abrams Avatar answered Dec 27 '22 10:12

Ignacio Vazquez-Abrams


Would this work?

>>> left_len = len(left[-1]) if left else -1
>>> right_len = len(right[0]) if right else -1
>>> right.pop(0) if right_len > left_len else left.pop(-1)
9

The behavior is a little different, in that if not left and not right, left.pop(-1) instead of right.pop(0). But then, it's an error either way...

like image 26
senderle Avatar answered Dec 27 '22 10:12

senderle