[Tutor] Summing arrays
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Mar 16 05:12:30 EDT 2017
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
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list