Posted by: Kiddo February 6, 2013
how to?
Login in to Rate this Post:     0       ?        

You have a flaw in your logic

I am not familiar with Python programming and am no longer a programmer, but it seems fairly straight forward so I tested your logic and you are getting what you are programming.

Flaw

  • First of all, how can you print two variables at a time (i and x with print function) when you might have to print odd number of variables (say N=5)? WIth you program you can only do 1-2+3-4+5-6 and so on, not 1-2+3 OR 1-2+3-4+5.
  • Second, for N=5, your program will NOT run beyond those 4 since X becomes 6 which stops the program from going more than 2 iterations, hence 4 values.

         Let's check it out (for N=5)

               First iteration: x (initial value) = 2, x (final value)=4 //Since x=x+2

               Second iteration: x (initial value) = 4, x (final value)=6

               Third iteration fails as x>N

Solution

First of all, you can't print two variables at once since you can have odd number of digits (like N=5).

But, if you print one at a time, you have to alternate between + and -.
You can do this in a number of ways, let's keep it simple and use i as our counter. So if i is odd (i/2 not=1) then you will print "-" and add to the sum while if it is even you will do opposite:

N = int(input("N: "))
i=1
Sum=0

while i <= N:
    
    if i/2=1:                                              //If i is even
           print(i, "+", end=' ')
           Sum=Sum-i
    else:                                                  //if i is odd
           print(i, "-", end=' ')
           Sum=Sum+i

     i=i+1

print("=", Sum)

Like I said, I am not familiar with Python and might have my syntax wrong, but the logic should work.

Read Full Discussion Thread for this article