Reputation: 2429
sample = [['AAAA','BBBB','CCCC'],['BBBBB','FFFFF','GGGGG'],['AA','MM']]
I need to calculate 'a' such that a = summation 1/i; where i ranges from 1 to n-1. In the process, I need to divide an integer (MyInt) by a list.
i2 =[]
afinal =[]
for sub_list in sample:
i1 = range(len(sample[0]))
i1.pop(0)
myInt = [1 for x in i1]
newList = [float(int1)/float(x) for int1,x in zip(myInt,i1)]
a = [sum(i) for i in zip(newList)]
afinal.append(a)
print afinal
However, I get the output as [[1.0]], whereas I should be getting an output with as [1.83333333333, 2.08333333333,1] numbers within a list.
Any idea where I may be going wrong?
Upvotes: 0
Views: 5507
Reputation: 16700
If I understand well, you want to divide a
by every element of your list.
What you need is reduce
:
l = [1, 2, 3, 4]
reduce((lambda x, y : x/y), l)
Will return the first element of l
, which is 1
, divided by all the other elements of l
.
Explanation
reduce
applies the first parameter to the first two elements of the second parameter, and repeats it with a new list whose first element is the result of the call, and the other elements are the elements of the passed list, started from the 3rd, until the second parameter has only one element.
Example call to clarify:
>>>reduce((lambda x, y : x+y), [1, 2, 3])
step 1: 1+2=3, so the new call is reduce((lambda x, y : x+y), [3, 3])
step 2: 3+3=6, so the new call is reduce((lambda x, y : x+y), [6])
step 3: [6] has only one element, so returns 6.
lambda x, y : x/y
means "you know, that function that takes two arguments and that returns their quotient". This is an anonymous function.
Upvotes: 1
Reputation: 177481
I need to calculate 'a' such that a = summation 1/i; where i ranges from 1 to n-1
>>> n = 5
>>> a = sum(1.0 / i for i in range(1,n))
>>> a
2.083333333333333
>>> 1./1 + 1./2 + 1./3 + 1./4
2.083333333333333
Is that what you are trying to do?
Upvotes: 3
Reputation: 472
Assuming you are talking about (Integer division). I would prefer using Numpy. Following might be what you are looking for:
import numpy as np
a = np.array([1,2,3,4,5]) # a List
b = 3 # INT Value
print b/a
Upvotes: 0