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?
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)
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With