Henri
Henri

Reputation: 1235

Increase a value every second iteration

I want to increase a value every second iteration by a fixed value. The above code solves this, but I wonder if there's a better solution to this problem? In my real world problem the dataset is bigger and writing an if-statement is perhaps not an efficient solution. Can I use count in a better way?

iter= range(6)

start = 0.25
increase = 0.01

for count, i in enumerate(iter):
    print(count)
    if count in [1,3,5]:
        start = start + increase
        print(start)

Upvotes: 1

Views: 1733

Answers (3)

Alain T.
Alain T.

Reputation: 42143

You can use zip to skip iterations:

iter6 = iter(range(6))

start = 0.25
increase = 0.01

for _,i in zip(iter6,iter6): 
    start += increase       # i is only every second value

there is also islice() in itertools:

for i in islice(iter6,1,None,2): 
    start += increase       # i is only every second value

Or sum with either of those:

start += sum(increase for _ in zip(iter6,iter6))

Upvotes: 1

Carlos Adir
Carlos Adir

Reputation: 472

You can use the operator % who tells you if it's even or odd:

print(1%2)  # 1
print(2%2)  # 0
print(3%2)  # 1
print(4%2)  # 0
print(5%2)  # 1

In the case, you use counter:

for count, i in enumerate(iter):
    print(count)
    if count % 2:  # It gives only 1 or 0
        start += increase
        print(start)

Upvotes: 6

Kelly Bundy
Kelly Bundy

Reputation: 27588

You could cycle between adding zero and your increment, and accumulate:

from itertools import cycle, accumulate, islice

length = 6
start = 0.25
increase = 0.01

xs = accumulate(cycle([0, increase]), initial=start)
for x in islice(xs, length):
    print(x)

Output:

0.25
0.25
0.26
0.26
0.27
0.27

Upvotes: 2

Related Questions