Skip to content

Add step argument to circular shifts. Simplify the implementation #869

@rhettinger

Description

@rhettinger
def circular_shifts(iterable, steps=1):
    """Return a list of circular rotations of *iterable*.

    >>> circular_shifts(range(4))
    [(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)]

    Set *steps* to the number of places to rotate to the left
    (or to the right if negative).  Defaults to 1.

    """
    buffer = deque(iterable)
    if steps == 0:
        raise ValueError('Steps should be a non-zero integer')

    buffer.rotate(steps)
    steps = -steps
    n = len(buffer)
    n //= math.gcd(n, steps)

    return [buffer.rotate(steps) or tuple(buffer) for _ in repeat(None, n)]

Side question: Why does this function return a list instead of an iterator?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions