[Tutor] Summing arrays
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Thu Mar 16 05:38:42 EDT 2017
On 03/16/2017 10:12 AM, Alan Gauld via Tutor wrote:
> On 16/03/17 05:11, Aaliyah Ebrahim wrote:
>
>> def sum2(N):
>>
>> b = np.arange(1,N+1,1)
>> mylist = [ ]
>> for i in b:
>> terms = 2*(1+3**(i-1))
>> a = mylist.append[terms]
>> return np.sum(mylist)
>
>> terms = 2*(1+3**(i-1))----> 9 mylist.append[terms] 10
>> return np.sum(mylist) 11
>> TypeError: 'builtin_function_or_method' object is not subscriptable
>
> You are using [] to call append instead of ().
> It should be
> a = mylist.append(terms)
>
> However, most of your function could be replaced by
> a list comprehension:
>
> def sum2(N):
> mylist = [2*(1+3**(i-1)) for i in np.arange(1,N+1,1) ]
> return np.sum(mylist)
>
> And I'm not sure the np versions of the functions will
> give much advantage over the standard range() and sum()
>
> Any time you see a structure like
>
> aList = []
> for <some iteration>
> aList.append(<some expression>)
>
> You should consider whether a comprehension would
> be more suitable
>
Alternatively, you could even use a generator expression (essentially,
just omitting the brackets from Alan's suggestion) and avoid keeping
mylist in memory like this:
def sum2(N):
return np.sum(2*(1+3**(i-1)) for i in np.arange(1,N+1,1))
In addition, I'd agree with Alan that the advantage of using numpy
functionality in this function seems quite questionable. You'd probably
get pretty much the same performance with just:
def sum2(N):
return sum(2*(1+3**(i-1)) for i in range(1,N+1,1))
Best,
Wolfgang
More information about the Tutor
mailing list