[Python] Algorithm for detecting full loop when iterating over a list

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    Assignment:


    Write a funcion cycle_sublist(lst, start, step) where:

    • lst is a list
    • start is number that satisfies: 0 <= start < len(lst)
    • step is the amount we increase your index each iteration

    without using: slicing, importing, list comprehension, built-in functions like map and filter.

    The function works in this way: We start to iterate over the list of items when we get back to start or cross it again. So for example:

    cycle_sublist([1], 0, 2) -> [1]
    cycle_sublist([6, 5, 4, 3], 0, 2) -> [6, 4]
    cycle_sublist([7, 6, 5, 4, 3], 3, 1) -> [4, 3, 7, 6, 5]
    cycle_sublist([4, 3, 2, 5, 1, 6, 9], 2, 2) -> [2, 1, 9, 3]
    cycle_sublist([4, 3, 2, 5, 1, 6, 9], 5, 3) -> [6, 3, 1]​

    My problem is detecting when I have completed a cycle. I tried to:

    • Check my previous step and current steps and check it against start. The problem is there are some cases where it fails.
    • Count my steps and checking if I had crossed the start.

    None of those worked.

    Here is my code - with the missing logic for detecting the cycle:

    def cycle_sublist(lst,start,step):
    index = start
    length = len(last)

    cycle_complete = False
    res = []

    while True:
    index = index % length if index >= length else index

    if ...:
    cycle_complete = True

    if cycle_complete and index >= start:
    break

    res.append(lst[index])

    index += step

    return res


    If you can I'd like to ask you to answer with the algorithm to detect the cycle only so I can write the code myself. But if you feel you want to add the code feel free.

    Continue reading...

Compartilhe esta Página