import timeit
setup = """
class X:
def __init__(self):
self.n = 2
def f0(self):
return 0
def f1(self):
return 1
def f2(self):
return 2
def f3(self):
return 3
x = X()
d = {0: x.f0, 1: x.f1, 2: x.f2, 3: x.f3}
"""
# If-statement 1
code1 = """
if x.n == 0:
x.n = x.f0()
elif x.n == 1:
x.n = x.f1()
elif x.n == 2:
x.n = x.f2()
elif x.n == 3:
x.n = x.f3()
"""
# If-statement 2
code2 = """
n = x.n
if n == 0:
x.n = x.f0()
elif n == 1:
x.n = x.f1()
elif n == 2:
x.n = x.f2()
elif n == 3:
x.n = x.f3()
"""
# Dictionary 1
code3 = """
try:
x.n = d[x.n]()
except KeyError:
pass
"""
# Dictionary 2
code4 = """
x.n = d.get(x.n, lambda: x.n)()
"""
print timeit.Timer(code1, setup).timeit(), "If-statement 1"
print timeit.Timer(code2, setup).timeit(), "If-statement 2"
print timeit.Timer(code3, setup).timeit(), "Dictionary 1"
print timeit.Timer(code4, setup).timeit(), "Dictionary 2"
aW1wb3J0IHRpbWVpdAoKc2V0dXAgPSAiIiIKY2xhc3MgWDoKICBkZWYgX19pbml0X18oc2VsZik6CiAgICBzZWxmLm4gPSAyCiAgZGVmIGYwKHNlbGYpOgogICAgcmV0dXJuIDAKICBkZWYgZjEoc2VsZik6CiAgICByZXR1cm4gMQogIGRlZiBmMihzZWxmKToKICAgIHJldHVybiAyCiAgZGVmIGYzKHNlbGYpOgogICAgcmV0dXJuIDMKeCA9IFgoKQpkID0gezA6IHguZjAsIDE6IHguZjEsIDI6IHguZjIsIDM6IHguZjN9CiIiIgojIElmLXN0YXRlbWVudCAxCmNvZGUxID0gIiIiCmlmIHgubiA9PSAwOgogIHgubiA9IHguZjAoKQplbGlmIHgubiA9PSAxOgogIHgubiA9IHguZjEoKQplbGlmIHgubiA9PSAyOgogIHgubiA9IHguZjIoKQplbGlmIHgubiA9PSAzOgogIHgubiA9IHguZjMoKQoiIiIKIyBJZi1zdGF0ZW1lbnQgMgpjb2RlMiA9ICIiIgpuID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