V
V
VyusFire2015-01-20 13:22:35
Python
VyusFire, 2015-01-20 13:22:35

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

Actually, the branching here is quite large, I thought that if we take a dictionary
like { 'seconds': 1, 'minutes': 60, ... }, then this expression can be expressed as:
def convertSecondsTo(seconds, type, types):
  #types -- наш словать со значениями.
  return seconds / types[type]

Actually the question is whether such a method is justified and whether it has a right to life at all?
PS It's just that somewhere I heard that if there are large branch operators in the code, then such sections of the code need to be reworked.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladlen Grachev, 2015-01-20
@VyusFire

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.

L
lPolar, 2015-01-20
@lPolar

By the way, Lutz in "Learning Python" just wrote that dictionaries should be used as branching operators.

F
Flammar, 2015-01-21
@Flammar

Not only possible, but also recommended, and not only in Python, but even in Java (and, therefore, in Python even more so), however, due to the specifics of the language, enumerated types are not used there, but associative arrays ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question