Reputation: 95
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?
Upvotes: 5
Views: 1719
Reputation: 1034
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]
Upvotes: 0
Reputation: 11134
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]
Upvotes: 0
Reputation: 309959
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).
Upvotes: 14
Reputation: 3938
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]
Upvotes: 5
Reputation: 1329
l = []
a = 0
for i in xrnage (N) :
a += 2
if i&1 == 0 :
a+=2
l.append (a)
Looks simple enough to me.
Upvotes: 1