Answer the question
In order to leave comments, you need to log in
Can associative arrays be used as an alternative to branch operators?
So hello.
Actually, having stumbled upon a small piece of code that contained a rather voluminous branching operator, I thought - but is it possible to somehow simplify this fragment and increase its readability?
I think it's easier to explain in a primer.
Let's say we have the following code:
def convertSecondsTo(seconds, type):
if type == "seconds":
return seconds
elif type == "minutes":
return seconds / 60
elif type == "hours":
return seconds / 3600
elif type == "days":
return seconds / 86400
elif type == "months":
return seconds / 2592000
elif type == "years":
return seconds / 31536000
assert False
def convertSecondsTo(seconds, type, types):
#types -- наш словать со значениями.
return seconds / types[type]
Answer the question
In order to leave comments, you need to log in
Yes, this is quite an acceptable option, and much better than the original one. In this case, there is probably no need to pass types, it is better to just store them somewhere.
By the way, Lutz in "Learning Python" just wrote that dictionaries should be used as branching operators.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question