1

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)) 
2
  • sum() is probably what you're looking for Commented Sep 2, 2015 at 15:49
  • sum([1,2,3]) gives you 6. Check out official doc Commented Sep 2, 2015 at 15:50

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks you. I wasn't sure if I could do all of it in one line, since I had the wrong method.
2

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 

2 Comments

right I guess I forgot to mention I don not need the nth term
Nice one. This should be accepted as the best answer this it does not use loops and is surely way faster. Also for a short explanation 1^3 + 2^3 +...+ n^3 = (1+2+...+n)^2 = (n*(n+1)/2)^2
1

change

return cubes.count() 

to

return sum(cubes) 

Check out official doc

Comments

1

You're looking for sum()

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

enjoy

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.