Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Udemy Course. Foundations of Computer Science: Theory and Practice
- # Section 3.5 Cycles.
- def cycles(indices):
- # Initialise an empty list, which will become a list of cycles (each cycle being a sub-list)
- all_cycles = []
- for x in indices: # Work through the given indices list one position at a time
- # Initialise a list for one cycle, containing the index of the start point within indices
- one_cycle = [x]
- while True: # Keep looping until we break out
- x = indices[x] # Pick up the index stored at the current position within indices
- if x == one_cycle[0]: # Have we returned to the start point in the current cycle?
- one_cycle.sort() # Yes - Sort this one cycle, so that we don't create duplicates
- if one_cycle not in all_cycles: # Is this a newly discovered cycle?
- all_cycles.append(one_cycle) # Yes - append it to our results list
- break # And break out to the outer loop to search again
- # We have not hit a cycle point, so append this index to the current cycle
- one_cycle.append(x)
- return all_cycles # Return our result list of all cycles found
- tests = [[2, 0, 1, 4, 3, 5], [0, 1, 2, 3], [3, 2, 0, 1]]
- for test in tests:
- print(cycles(test))
- # Results:
- # [[0, 1, 2], [3, 4], [5]]
- # [[0], [1], [2], [3]]
- # [[0, 1, 2, 3]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement