list comprehension return a list and sum over in loop

Peter Otten __peter__ at web.de
Fri Dec 12 07:32:16 EST 2014


Jussi Piitulainen wrote:

> KK Sasa writes:
> 
>> def p(x,t,point,z,obs):
>>     d = x[0]
>>     tau = [0]+[x[1:point]]
>>     a = x[point:len(x)]
>>     at = sum(i*j for i, j in zip(a, t))
>>     nu = [exp(z[k]*(at-d)-sum(tau[k])) for k in xrange(point)]
>>     de = sum(nu, axis=0)
>>     probability = [nu[k]/de for k in xrange(point)]
>>     return probability[obs]
> 
> I must be blind, but this looks like computing a whole probability
> distribution and then throwing almost all of it away.
> 
> Can't this just return nu[obs]/de?
> 
> The expression for tau also seems weird to me. Isn't it equivalent to
> [0, x[1:point]], a two-element list with the second element a list?
> How can sum(tau[k]) work at all then, for any k > 1?

Also, after adding 

from numpy.random import seed

to the code I run into the next problem:

Traceback (most recent call last):
  File "hessian.py", line 34, in <module>
    re = [d2(x,t[k],2,z,1) for k in range_people]
  File "/home/petto/.local/lib/python2.7/site-packages/ad/__init__.py", line 
1114, in hess
    return func(xa, *args).hessian([xa])
  File "hessian.py", line 26, in p
    nu = [exp(z[k]*(at-d)-sum(tau[k])) for k in xrange(point)]
TypeError: 'int' object is not iterable

OP: Optimizations only make sense when you can start from a known-good base. 
You should sort out the logic of your problem (we probably can't help you 
with that), then fix the bugs in your code and only then revisit the "speed 
issue". 




More information about the Python-list mailing list