[Tutor] Need help w/ a for loop

W W srilyk at gmail.com
Fri Oct 24 12:51:54 CEST 2008


On Thu, Oct 23, 2008 at 10:29 PM, Monte Milanuk <monte at milanuk.net> wrote:

> Hello again, and thanks to all of you who extended your help!
> <snip>Maybe I'm not clever enough, but I didn't see how either example
> could be used for doing the addition/subtraction determination.  Or rather,
> I found a different way after reading someone else's examples.
>
<snip>
>
#  loop thru n times, summing each pass and switching the sign
>     #  on m each time, and printing x every time through.
>     for i in range(n):
>         x = x + m*(4.0/(i*2+1))
>         m = -m
>

That's probably just as elegant as the way I would have done it; mod
division! :)

 In [50]: for x in range(1, 10):
   ....:     print "%d %% 2 = " % (x, ), x % 2
   ....:
   ....:
1 % 2 =  1
2 % 2 =  0
3 % 2 =  1
4 % 2 =  0
5 % 2 =  1
6 % 2 =  0
7 % 2 =  1
8 % 2 =  0
9 % 2 =  1

Thus, to adapt it to what you had, declare:
m = -1

And the terms of the loop:
for i in range(1, n+1):
    x = x + (m * (i % 2)) * (4.0/(i*2))

At least I'm pretty sure that's syntactically correct. It's 5:47 am and I'm
getting ready for school, so you never know for sure ;)

The great thing about using mod division is that it's /always/ applicable
when you're looking for even/odd status of a number:

In [52]: for x in xrange(-3,3):
   ....:     print "%d %% 2 = " % (x, ), x % 2
   ....:
   ....:
-3 % 2 =  1
-2 % 2 =  0
-1 % 2 =  1
0 % 2 =  0
1 % 2 =  1
2 % 2 =  0

Yay for mod division! :)

Glad my advice helped!
-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20081024/488b9394/attachment.htm>


More information about the Tutor mailing list