python - function that checks the length of the cycle -


hey guys have function, gives me error when test it. have idea on how fix exercise. please read through.

write function cyclelength(array), returns number of students form loop, given start talking left-most one. input array list of non-negative integers, such array[m] number of student whom student m redirects. no student redirects himself. left-most student number 0, next number 1, , on. each element in list in range [0, n-1] n length of list. example, suppose list [1, 3, 0, 1]. student 0 redirects student 1, redirects student 3, redirects student 1. there loop of 2 students: 1, 3. answer 2. note though started student 0, not part of loop. here function:

def cyclelength(m):     lst = []     = 0     while not in lst:         lst.append(i)         = int(m[i])      b = len(lst) - lst.index(i)     return b 

you got right.

>>> def cyclelength(students): ...     seen = [] ...     current = 0 ...     # run till have seen students ...     while len(seen) != len(students): ...         # if current index has been seen ...         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]) none) 

this take care of case there no loop well.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -