Actually yes. First off, Python doesn't have the iconic switch
statement, which provides a binary search when the statement becomes long enough, which is much faster than a linear search.
In Python, you can use a dictionary, either with exact values, or custom functions:
def other_case(x):
'''We can store non-lambdas too'''
return 8
functions = {
'd': lambda x: 4*x,
'!': lambda x: 5,
'k': lambda x: (1-2*x+x**2),
'Z': lambda x: (1/x),
'*': other_case,
}
To call this, just right a short wrapper:
def call(a, x):
return functions[a](x)
This has O(1) time, or constant complexity, so in addition to being a lot more readable, it will be a lot faster too.
Edit
If you have numbers of a specific range, that can be all over that entire range, you can also use a list and a transformation. Say I want to process something from a mass of 2000 Da to 5000 Da (I'm a biologist), at intervals of 100 Da. It makes no sense to encode a list of 500 items, but I could use a 30-item list to consider the entire range.
from __future__ import division # for //, floor division
def mass2000(x):
'''Do something for mass of 2000'''
return 1/x
def mass2100(x):
'''Do something for mass of 2100'''
return x
def mass2200(x):
'''Do something for mass of 2200'''
return x**2
lookup = [
mass2000,
mass2100,
mass2200,
# ....
]
def call(mass, x):
if (mass < 2000 or mass > 5000):
raise ValueError("Mass out of range")
return lookup[(mass - 2000) // 100](x)
def all_funcs(operation, operand)
is not pythonic