Reputation: 660
I want to use boolean algebra instead of several conditionals, for example
def boo(x,y):
if x==3 and y==1: return 4
if x==3 and y==4: return 1
if x==4 and y==1: return 2
if x==4 and y==2: return 1
if x==5 and y==1: return 3
what I want to do is
def simple(x,y):
return x#y
and there are total 12 equations, I just want to directly return (x#y) where # is a boolean operator. I did this to a smaller problem where I luckily found out a relation. I want to do the same in this case also, how do I proceed with it?
Does this have any performance gains, because its not going through several if conditionals? Is this normal practice?
sample:
x y output
1 2 3
1 3 2
1 4 5
1 5 4
here a simple bitwise xor gate will do
def(x,y): return x^y
Upvotes: 0
Views: 574
Reputation: 5515
You could consider using dictionaries. You could perhaps make a dictionary of dictionaries, and have your function retrieve values through the dictionary.
def boo(x,y):
if x==3 and y==1: return 4
if x==3 and y==4: return 1
if x==4 and y==1: return 2
if x==4 and y==2: return 1
if x==5 and y==1: return 3
def boodict(x,y):
d1 = {3: {1:4, 4:1} ,4: {1:2, 2:1},5: {1:3}}
try:
value = d1[x][y]
except KeyError:
value = None
return value
Upvotes: 0
Reputation: 185852
I don't know whether trying to find a terser expression of the above logic would lead to more readable code; probably not. But you can rework the logic as-is to a more mathematical formulation:
def boo(x, y):
p = (x, y)
return (1 if p in ((3, 4), (4, 2)) else
2 if p == (4, 1) else
3 if p == (5, 1) else
4 if p == (3, 1) else
None)
Another option is to use a dictionary:
def boo(x, y):
return {(3,4):1, (4,2):1, (4,1):2, (5,1):3, (3,1):4}.get((x, y), None)
If you know that all values will match the specified cases, you can write [(x, y)]
instead of .get((x, y), None)
.
Upvotes: 1
Reputation: 27233
You can find the right expression that yields the same values as your conditionals, but such code becomes harder to read and maintain.
A better solution is to use a nested list or dictionary which you can index with input values. This way you turn code into data which is a clear and fast representation of your mapping and which can be readily understood and easily modified in the future.
Upvotes: 2