Search code examples
pythonlistfunctionpython-2.7cycle

function that checks the length of the cycle


Hey guys i have the function, but it gives me error when I test it. Does anyone have any Idea on how to fix it This is my exercise. Please read through.

Write a function cycleLength(array), which returns the number of students that form a loop, given that you start by talking to the left-most one. The input array is a list of non-negative integers, such that array[m] is the number of the student to whom student m redirects. No student redirects to himself. The left-most student is number 0, the next is number 1, and so on. Each element in the list will be in the range [0, n-1] where n is the length of the list. For example, suppose the list was [1, 3, 0, 1]. Then student 0 redirects to student 1, who redirects to student 3, who redirects back to student 1. There is a loop of two students: 1, 3. Thus the answer would be 2. Note that even though you started with student 0, he is not part of the loop. Here is my function:

def cycleLength(m):
    lst = []
    i = 0
    while i not in lst:
        lst.append(i)
        i = int(m[i])

    b = len(lst) - lst.index(i)
    return b

Solution

  • You almost got it right.

    >>> def cycleLength(students):
    ...     seen = []
    ...     current = 0
    ...     # Run till we have seen all the students
    ...     while len(seen) != len(students):
    ...         # If the current index has been seen already
    ...         if current in seen:
    ...             return len(seen) - seen.index(current)
    ...         seen.append(current)
    ...         current = students[current]
    ... 
    >>> assert(cycleLength([1, 3, 0, 1]) == 2)
    >>> assert(cycleLength([1, 3, 0, 2]) is None)
    

    This will take care of the case where there is no loop as well.