'Is there a way to simplify this if else block?
So I have this really long if else block and I was wondering if there is a way to simplify it?
def position(self, k):
if self.b == None:
self.b = k
if (self.b).location_of(k) == 0:
if self.aquire(0) == None:
self.put(0, ABK(k))
else:
self.aquire(0).insert(k)
elif (self.b).location_of(k) == 1:
if self.aquire(1) == None:
self.put(1, ABK(k))
else:
self.aquire(1).insert(k)
elif (self.b).location_of(k) == 2:
if self.aquire(2) == None:
self.put(2, ABK(k))
else:
self.aquire(2).insert(k)
Solution 1:[1]
You could store the value of self.b.location_of(k) on a variable and use it later to call your functions.
def position(self, k):
if self.b is None:
self.b = k
loc = self.b.location_of(k)
if loc < 0 or loc > 2:
return # Return in case the value is out of scope
if self.aquire(loc) is None:
self.put(loc, ABK(k))
else:
self.aquire(loc).insert(k)
Edit:
Olvin Roght pointed out that you can also save the result of the self.aquire(loc) call:
def position(self, k):
if self.b is None:
self.b = k
loc = self.b.location_of(k)
if loc < 0 or loc > 2:
return
aqu = self.aquire(loc)
if aqu is None:
self.put(loc, ABK(k))
else:
aqu.insert(k)
Solution 2:[2]
As of python 3.8, you can achieve a result similar to the other answers in a shorter manner using the walrus operator (:=), more formally known as the assignment expression operator. This sort of inline assignment is similar to the way assignment can sometimes be done in nested ifs in C:
def position(self, k):
if self.b is None:
self.b = k
if 0 <= (loc := self.b.location_of(k)) <= 2:
if (val := self.aquire(loc)) is None:
self.put(loc, ABK(k))
else:
val.insert(k)
In addition to the more obvious changes, I recommend using x is None rather than x == None, as it is the more idiomatic comparison.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Olvin Roght |
| Solution 2 | Chris |
