[Tutor] HOW DO I PYTHONIZE A BASICALLY BASIC PROGRAM?

bob gailer bgailer at gmail.com
Tue Jan 13 03:20:10 CET 2009


WM. wrote:
> # The natural numbers(natnum), under 1000, divisible by 3 or by 5 are 
> to be added together.
> natnum = 0
> num3 = 0
> num5 = 0
> cume = 0
> # The 'and' is the 15 filter; the 'or' is the 3 or 5 filter.
> while natnum <= 999:
>     num3 = natnum/3
>     num5 = natnum/5
>     if natnum - (num3 * 3) == 0 and natnum - (num5 * 5) == 0:
>         cume = cume + natnum
>     elif natnum - (num3 * 3) == 0 or natnum - (num5 * 5) == 0:
>         if natnum - (num3 * 3) == 0:
>             cume = cume + natnum
>         elif natnum - (num5 * 5) == 0:
>             cume = cume + natnum
>     natnum = natnum + 1
> print cume
>
My head hurts trying to follow all that logic and expressions. That is a 
sign of too much code. Let's simplify:

1) no need to initialize num3 or num5
2) replace while with for
3a) replace natnum - (num3 * 3) == 0 with natnum == (num3 * 3)
3b) replact that with not (natnum % 3)
4) use += and -=

for natnum in range(1000):
  if not (natnum % 3 or natnum % 5): # adds 1 if divisible by 3 and/or 5
    cume += 1
  if not natnum % 15: # remove one of the ones if divisible by 15
    cume -= 1

Since the result of not is True (1) or False (0) one can also write
  cume += not (natnum % 3 or natnum % 5)
  cume 1= not (natnum % 15)

An alternative:
for natnum in range(1000):
  if  not natnum % 15:
    pass
  elif not (natnum % 3 or natnum % 5): # adds 1 if divisible by 3 or 5
    cume += 1
   

>
> This problem was kicked around last month and I did not understand any 
> of the scripts.  

That's really unfortunate. Would you for your learning take one of them, 
tell us what if any parts of it you understand and let us nudge you 
toward more understanding.


-- 
Bob Gailer
Chapel Hill NC 
919-636-4239



More information about the Tutor mailing list