'How to make alternating 'for' loop?
How do i make alternating step for a 'for' loop? i.e number sequence (-1,2,-3,4,-5)
I know how to make all negative which is
n=int(input())
for i in range (1,n+1):
i=i*(-1)
print(i)
im sure there's a better way to do it, but how do i make a 2nd step on for the n=2,4,6... ? putting another i=i*(-1) makes it all+ again
Solution 1:[1]
You could introduce a parity check, i.e. check whether the value of i of the current interation is even or odd. This can be achieved using the modulo operator %.
n = int(input())
for i in range(1, n+1):
if i % 2 == 0:
print(i)
else:
print(-i)
Solution 2:[2]
Use math odd numbers are negative, -1 to power of a odd number is -1 so we multiply odd numbers by (-1)^i same way for even numbers because -1 to power of even is +1 so generally in our case each number from <1, 2, 3, 4, ...> maps to <-1, 2, -3, 4, ...>
>>> for i in range(1, n + 1):
... j = i * (-1)**i
... print(j)
...
-1
2
-3
4
-5
Solution 3:[3]
Raising -1 to odd powers for -1 and even powers for +1 is how I'd do it. Depends on if you want "odd numbers negative" or "first third fifth numbers" negative.
You could also just maintain a "flip":
flip = -1 # first number will be negative; make it 1 for first number postive
for i in range(1, n+1):
print(i * flip)
flip *= -1
# output:
-1
2
-3
4
-5
You can use itertools.cycle() with list of [-1, 1] and zip it with your range.
Solution 4:[4]
Another way to think about this problem is that you have two sequences, one of positive values, one of negative ones and you alternate between them for producing the result. That is, you interleave values from those sequences. The third-party Toolz library has lots of useful functions, like interleave:
from toolz.itertoolz import interleave
n = 5
positives = range(2, n + 1, 2)
negatives = range(-1, -(n + 1), -2)
combined = interleave([negatives, positives])
for i in combined:
print(i)
Solution 5:[5]
I added if part that checks the number not even. It provides odd numbers to multiply with -1.
n=int(input())
for i in range (1,n+1):
if i%2!=0:
i=i*(-1)
print(i)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | aneroid |
| Solution 4 | |
| Solution 5 |
