Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #57657
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: Check if this basic Python script is coded right |
| Date | 2013-10-26 16:16 -0400 |
| References | <9716695c-31e3-40a0-b2a4-73b967494107@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1605.1382818600.18130.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Check if this basic Python script is coded right HC <hikmat@jafarli.net> - 2013-10-26 10:36 -0700
Re: Check if this basic Python script is coded right Joel Goldstick <joel.goldstick@gmail.com> - 2013-10-26 13:53 -0400
Re: Check if this basic Python script is coded right Mark Lawrence <breamoreboy@yahoo.co.uk> - 2013-10-26 18:55 +0100
Re: Check if this basic Python script is coded right John Ladasky <john_ladasky@sbcglobal.net> - 2013-10-26 10:58 -0700
Re: Check if this basic Python script is coded right MRAB <python@mrabarnett.plus.com> - 2013-10-26 19:20 +0100
Re: Check if this basic Python script is coded right rusi <rustompmody@gmail.com> - 2013-10-27 05:20 -0700
Re: Check if this basic Python script is coded right Tim Delaney <timothy.c.delaney@gmail.com> - 2013-10-28 08:30 +1100
Re: Check if this basic Python script is coded right Terry Reedy <tjreedy@udel.edu> - 2013-10-26 15:46 -0400
Re: Check if this basic Python script is coded right Terry Reedy <tjreedy@udel.edu> - 2013-10-26 16:16 -0400
csiph-web