On 10/26/2013 1:36 PM, HC wrote:
I'm doing my first year in university and I need help with this basic 
assignment.

Assignment: Write Python script that prints sum of cubes of numbers between 
0-200 that are multiples of 3. 3^3+6^3+9^3+12^3....+198^3=?

My script:
count = 0
answer = 0

while count<200:
     if count%3==0:
         answer = answer + count**3
     count = count + 1

print ("Result is: " +str(answer))

Is it all okay?

Generalize the problem, put the code in a reusable testable function, and start with test cases.
--
def sum33(n):
  "Return sum of cubes of multiples of 3 <= n."

for n, sm in ( (0,0), (2,0), (3,27), (4,27), (6,243), ):
  assert sum33(n) == sm

print(sum33(200))
--
This will fail because None != 0. Now add 'return 0' and the first two cases pass and then it fails with None != 27. Now change 'return 0' to

  answer = 0
  for i in range(3, n+1, 3):
    answer += i*i*i
  return answer

and it will print 131990067, which I presume is correct. Putting your code in the body instead, indented, with '200' replaced with 'n+1', and with 'return answer' added, gives the same result after passing the same tests.

--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to