HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Lazily combine ranges dependent on modulo with one loop

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
combinewithloopdependentrangeslazilyonemodulo

Problem

I have a positive integer n. I want to lazily loop over a range of integers less than n consisting of a) integers divisible by 3 (excluding zero) in reversed sorted order and b) zero and integers not divisible by 3 in any order. Is this a very stupid solution? I couldn't think of another way of doing it without having to make use two loops.

d = divisor = 3
list(itertools.chain(
    itertools.chain(*zip(*(((i),(i-1),(i-2)) for i in range(d*((n-1)//d),0,-d)))),
    (0,),range(n-1,d*((n-1)//d),-1)))

>>> n = 18
[15, 12, 9, 6, 3, 14, 11, 8, 5, 2, 13, 10, 7, 4, 1, 0, 17, 16]

>>> n = 17
[15, 12, 9, 6, 3, 14, 11, 8, 5, 2, 13, 10, 7, 4, 1, 0, 16]

>>> n = 16
[15, 12, 9, 6, 3, 14, 11, 8, 5, 2, 13, 10, 7, 4, 1, 0]

>>> n = 4
[3, 2, 1, 0]

>>> n = 3
[0, 2, 1]

>>> n = 2
[0, 1]

>>> n = 1
[0]

Solution

Code is read far more often than written.
So I prefer to make code as readable as possible.
Clever code is very often not good code.

I find the posted code very hard to read,
and I don't see why it has to be that way.

I believe this simple, straightforward implementation meets your posted requirements and very easy to read.

def gen(n):
    for x in range(n - 1, divisor - 1, -1):
        if x % divisor == 0:
            yield x
    yield 0
    for x in range(n):
        if x % divisor:
            yield x

Code Snippets

def gen(n):
    for x in range(n - 1, divisor - 1, -1):
        if x % divisor == 0:
            yield x
    yield 0
    for x in range(n):
        if x % divisor:
            yield x

Context

StackExchange Code Review Q#91564, answer score: 2

Revisions (0)

No revisions yet.