Help on return type(?)

Rustom Mody rustompmody at gmail.com
Sat Jan 9 22:17:52 EST 2016


On Sunday, January 10, 2016 at 7:16:23 AM UTC+5:30, Robert wrote:
> Hi,
> 
> I see below code snippet. The return line is not as the usual type.
> 
> 
> 
> def make_cov(cov_type, n_comp, n_fea):
>     mincv = 0.1
>     rand = np.random.random
>     return {
>         'spherical': (mincv + mincv * np.dot(rand((n_components, 1)),
>                                              np.ones((1, n_features)))) ** 2,
>         'tied': (make_spd_matrix(n_features)
>                  + mincv * np.eye(n_features)),
>         'diag': (mincv + mincv * rand((n_components, n_features))) ** 2,
>         'full': np.array([(make_spd_matrix(n_features)
>                            + mincv * np.eye(n_features))
>                           for x in range(n_components)])
>     }[cov_type]
> 
> Specifically, could you explain the meaning of 
> 
> {
> ...    }[cov_type]
> 
> to me?
> 
> 
> Thanks,

May help if you see it in pseudo-C like this

 switch (cov_type)

       case 'spherical': return (mincv + mincv * np.dot(rand((n_components, 1)),
                                              np.ones((1, n_features)))) ** 2,
       case 'tied': return (make_spd_matrix(n_features)
                  + mincv * np.eye(n_features)),
       case 'diag': return (mincv + mincv * rand((n_components, n_features))) ** 2,
       case  'full': return np.array([(make_spd_matrix(n_features)
                            + mincv * np.eye(n_features))
                           for x in range(n_components)])
     

Yeah looks backward in python compared to the C-ish
The python is more powerful however because its *data-driven* 
ie what is code in C is data in python.

BTW this is one of the motley components collected together under the somewhat
inept moniker of 'functional programming':
http://blog.languager.org/2012/10/functional-programming-lost-booty.html

Also you can make the python look less backward by naming the dictionary,
separate from the lookup:

d = {'spherical' : ..., 'tied' :..., 'diag' : ...}
return d[cov_type]



More information about the Python-list mailing list