How can I generate the sequence of numbers "1,2,5,6,9,10......" and so until 100 in Python? I even need the comma (',') included, but this is not the main problem.

The sequence: every number from 1..100, divisible by 4 with remainder 1 or 2.

Every number from 1,2,5,6,9,10... is divisible by 4 with remainder 1 or 2.

```
>>> ','.join(str(i) for i in xrange(100) if i % 4 in (1,2))
'1,2,5,6,9,10,13,14,...'
```

```
>>> ','.join('{},{}'.format(i, i + 1) for i in range(1, 100, 4))
'1,2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65,66,69,70,73,74,77,78,81,82,85,86,89,90,93,94,97,98'
```

That was a quick and quite dirty solution.

Now, for a solution that is suitable for different kinds of progression problems:

```
def deltas():
while True:
yield 1
yield 3
def numbers(start, deltas, max):
i = start
while i <= max:
yield i
i += next(deltas)
print(','.join(str(i) for i in numbers(1, deltas(), 100)))
```

And here are similar ideas implemented using itertools:

```
from itertools import cycle, takewhile, accumulate, chain
def numbers(start, deltas, max):
deltas = cycle(deltas)
numbers = accumulate(chain([start], deltas))
return takewhile(lambda x: x <= max, numbers)
print(','.join(str(x) for x in numbers(1, [1, 3], 100)))
```

Licensed under: CC-BY-SA with attribution

Not affiliated with: Stack Overflow