Luis
Luis

Reputation: 21

Adding what's inside a list

I am trying to make a function that will make a list of all the cubes less than n. Then all those numbers together and print that out however the .count() doesn't work as I was hoping. Is there a way to count up every number of the list or do I have to go through the list one by one to add them up?

def sum_cubes_less(n):
    '''Return the sum of the cubes of the positive integers less than n.'''
    x = 1
    cubes = [x**3 for x in range(1,n)]
    return cubes.count()

 print(sum_cubes_less(2**8))

Upvotes: 1

Views: 73

Answers (5)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You don't need to sum all the cubes, the sum of the first n cubes can be calculated with ((n( n + 1) / 2)^2):

In [6]: n = 25

In [7]: sum(x ** 3 for x in range(1, n+1))
Out[7]: 105625

In [8]: (n * ( n + 1) / 2) ** 2
Out[8]: 105625

If you are using range you need to use n+1 to include n in the result.

To not include n just subtract 1 from n:

In [16]: n = 25

In [17]: sum(x ** 3 for x in range(1, n))
Out[17]: 90000

In [18]: n -= 1

In [19]: (n * ( n + 1) // 2) ** 2
Out[19]: 90000

Upvotes: 2

Cyrbil
Cyrbil

Reputation: 6478

count is for counting the number of occurrences that appears in the list.

You want to use sum for suming all your cubes. Also you can avoid saving all your cubes in a list in memory (since you only want the total sum) by computing the cube then adding to the sum.

def sum_cubes_less(n):
   '''Return the sum of the cubes of the positive integers less than n.'''
    return sum(x**3 for x in range(1, n))

Edit: using the generator form is simplier, less heavy and faster.

Upvotes: 2

Alea Kootz
Alea Kootz

Reputation: 919

You're looking for sum()

replace return cubes.count() with return sum(cubes)

enjoy

Upvotes: 1

Andy
Andy

Reputation: 50540

You want to use sum for this task.

return sum(cubes)

This will return 1065369600 for your input value of 2**8.


.count() returns the number of times a specific item is in a list. You have to pass it a value to check:

return cubes.count(27)

This returns 1 because 3*3*3 is 27 and that value appears 1 time.

Upvotes: 0

taesu
taesu

Reputation: 4570

change

return cubes.count()

to

return sum(cubes)

Check out official doc

Upvotes: 1

Related Questions