Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested operators

I'm trying to write a tuple list comprehension using operators in python 2.7, tkinter. Alpha is the original data, beta the result.

alpha=[(A,1,1,2),
(B,2,2,2),
(C,3,1,2)]

product

beta=[(alpha[0],"%.2f"% reduce(mul,alpha[1:])) for alpha in alpha]
beta
[(A,2.00),(B,8.00),(C,6.00)]

sum

beta=[(alpha[0],"%.2f"% reduce(add,alpha[1:])) for alpha in alpha]
beta
[(A,4.00),(B,6.00),(C,6.00)]

But when I try to combine these for nested operations, I'm stumped. How do I get the

sum of products?

beta
[(A,16.00),(B,16.00),(C,16.00)]

products / sum of products?

beta
[(A,0.13),(B,0.44),(C,0.38)]

I've tried various iterations of the following with no success

beta=[(alpha[0],"%.2f"% reduce(add, map(mul,alpha[1:])) for alpha in alpha]
like image 339
Jeff Avatar asked Dec 30 '25 01:12

Jeff


1 Answers

Here is one way to do it:

In [46]: alpha=[('A',1,1,2),('B',2,2,2),('C',3,1,2)]

In [49]: total = float(sum(reduce(mul,a[1:]) for a in alpha))

In [50]: total
Out[50]: 16.0

In [51]: [(a[0], "%.2f" % (reduce(mul,a[1:])/total)) for a in alpha]
Out[51]: [('A', '0.12'), ('B', '0.50'), ('C', '0.38')]

I assume the 0.44 is a typo. If it isn't, please clarify how it should be computed.

like image 113
NPE Avatar answered Dec 31 '25 15:12

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!