Python: simple way to increment by alternating values?
Asked Answered
K

5

5

I am building a list of integers that should increment by 2 alternating values.

For example, starting at 0 and alternating between 4 and 2 up to 20 would make:

[0,4,6,10,12,16,18]

range and xrange only accept a single integer for the increment value. What's the simplest way to do this?

Kirkcudbright answered 31/8, 2016 at 5:36 Comment(0)
C
14

I might use a simple itertools.cycle to cycle through the steps:

from itertools import cycle
def fancy_range(start, stop, steps=(1,)):
    steps = cycle(steps)
    val = start
    while val < stop:
        yield val
        val += next(steps)

You'd call it like so:

>>> list(fancy_range(0, 20, (4, 2)))
[0, 4, 6, 10, 12, 16, 18]

The advantage here is that is scales to an arbitrary number of steps quite nicely (though I can't really think of a good use for that at the moment -- But perhaps you can).

Chrotoem answered 31/8, 2016 at 5:44 Comment(2)
Thanks, this is exactly what I was looking for. The scaling of steps is actually perfect for my needs.Kirkcudbright
Nice solution indeed.Ardrey
O
5

You can use a list comprehension and the modulus operator to do clever things like that. For example:

>>> [3*i + i%2 for i in range(10)]
[0, 4, 6, 10, 12, 16, 18, 22, 24, 28]
Outlive answered 31/8, 2016 at 5:42 Comment(0)
S
1
l = []
a = 0
for i in xrnage (N) :
    a += 2
    if i&1 == 0 :
        a+=2
    l.append (a)

Looks simple enough to me.

Sherylsheryle answered 31/8, 2016 at 5:42 Comment(0)
B
0

This could be solution that is flexible and work for any range.

def custom_range(first, second, range_limit):
    start , end = range_limit
    step = first + second
    a = range(start, end, step)
    b = range(first, end, step)
    from itertools import izip_longest
    print [j for i in izip_longest(a,b) for j in i if j!=None]

custom_range(4,2,(0,19))
custom_range(6,5,(0,34))

Output:

[0, 4, 6, 10, 12, 16, 18]
[0, 6, 11, 17, 22, 28, 33]
Baloney answered 31/8, 2016 at 5:58 Comment(0)
T
0

1 Generate a range of numbers from 0 to n with step size 4 2 generate another range of numbers from 0 to n with step size 6 3 Combine both the list and sorted. Remove duplicates

>>> a = range(0,20,4)
>>> a
[0, 4, 8, 12, 16]
>>> b = range(0,20,6)
>>> c = sorted(a + b)
>>> b
[0, 6, 12, 18]
>>> c
[0, 0, 4, 6, 8, 12, 12, 16, 18]
>>> c = list(set(c))
>>> c
[0, 4, 6, 8, 12, 16, 18]
Tesch answered 31/8, 2016 at 6:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.