0

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) 
1
  • Yes, there is. Commented Mar 20, 2022 at 17:31

2 Answers 2

2

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) 
Sign up to request clarification or add additional context in comments.

3 Comments

If you are using a recent enough python version, you can also use the "new" cool syntax := to make it even shorter and more readable.
@BlackBeans, this answer is pretty explicit which is good for beginners. It's arguable that assignment expression somehow increases readability,
@BlackBeans It's a feature you can only use if you're using Python3.8 or newer and since it wasn't specified which python version is used I tried to keep it as universal as possible.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.