Reputation: 201
I have this function that defines and returns variables a
and b
depending on the value of the parameter orientation
.
def myfunc(orientation, l, w):
if orientation == 1:
a = -w
b = l
elif orientation == 2:
a = -l
b = w
elif orientation == 3:
a = -w
b = -l
elif orientation == 4:
a = -l
b = -w
elif orientation == 5:
a = w
b = l
elif orientation == 6:
a = l
b = w
elif orientation == 7:
a = w
b = -l
elif orientation == 8:
a = l
b = -w
return a, b
My question is: is there a more compact and/or more efficient way to do the same thing? and if there is a better way, which is it?
Upvotes: 2
Views: 28
Reputation: 532093
First, the loops are unnecessary; only the values assigned in the very last iteration will be returned. Once you get rid of those, it's fairly easy to see the pattern:
def myfunc(orientation, l, w):
a, b = (w, l) if orientation % 2 else (l, w)
if orientation <= 4:
a = -a
if orientation in (3, 4, 7, 8):
b = -b
return a, b
Upvotes: 3
Reputation: 90989
A way would be to use a dictionary . Example -
def myfunc(orientation, l, w):
return { 1: (-w, l), 2: (-l, w), 3: (-w, -l),
4: (-l, -w), 5: (w, l), 6: (l, w),
7: (w, -l), 8: (l, -w) }[orientation]
Please note this evaluates all possible values in the dictionary and then selects the appropriate value to return based on the orientation
as the key. You should not use this method if want the values to be evaluated only when needed.
Demo -
>>> def myfunc(orientation, l, w):
... return {1: (-w, l), 2: (-l, w), 3: (-w, -l),
... 4: (-l, -w), 5: (w, l), 6: (l, w),
... 7: (w, -l), 8: (l, -w)}[orientation]
...
>>> myfunc(3,3,4)
(-4, -3)
The above would end up in a KeyError
, if the key is not found. If its possible that you call this function with an orientation not found in the dictionary, you can use .get(key, default)
, to make it return some default other default value. Example -
def myfunc(orientation, l, w):
return { 1: (-w, l), 2: (-l, w), 3: (-w, -l),
4: (-l, -w), 5: (w, l), 6: (l, w),
7: (w, -l), 8: (l, -w) }.get(orientation) #This returns `None` if orientation is not found in the dictionary. Use `.get(orientation, defaultval)` for some other default value.
Upvotes: 1
Reputation: 155566
Not likely to be faster, but more succinct (and raises the same exceptions when orientation
is "invalid"):
def myfunc(orientation, l, w):
if 1 <= orientation <= 8:
a = (-w, -l, -w, -l, w, l, w, l)[orientation - 1]
b = (l, w, -l, -w)[(orientation - 1) % 4]
return a, b
Upvotes: 1