[Tutor] Optimize the code - removing the multiple IF conditions

Peter Otten __peter__ at web.de
Mon Dec 21 07:46:27 EST 2015


Sunil Tech wrote:

> Hi,
> 
> I Have a code..
> 
> 
> class OptIf(object):
>     """docstring for OptIf"""
> 
>     def opt_me(self, ext):
>         if ext == 'CM':
>             rec = self.call_cm(cm, ad)
>         if ext == 'MM':
>             rec = self.call_mm(mm, ax)
>         if ext == 'DM':
>             rec = self.call_dm(dm, md)
>         return rec
> 
>     def call_cm(cm, ad):
>         pass
> 
>     def call_mm(mm, ax):
>         pass
> 
>     def call_dm(dm, md):
>         pass
> 
> 
> I want to optimize the code by removing the if conditions in the opt_me
> method,

No offence, but you have been around for some time now, long enough to learn 
how to properly present a problem.

The above code is broken, and until you have a working base that uses if 
statements it does not make much sense to "optimize" it. 

> I tried with few things making a dictionary of key as the ext and the
> value as the method that to be called.
> 
> med_map = {'CM': call_cm, 'MM': call_mm, 'DM': call_dm}
> but I am not able to pass the arguments.
> 
> can you please help or suggest the other way?

Go back to the drawing board and once you can present correct code that uses 
if statements it will be our pleasure to show you how to convert it to dict 
lookup.




More information about the Tutor mailing list