Advertisement
acclivity

pyUdemyCourse-CyclesTask

Apr 11th, 2021
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. # Udemy Course. Foundations of Computer Science: Theory and Practice
  2. # Section 3.5 Cycles.
  3.  
  4. def cycles(indices):
  5.     # Initialise an empty list, which will become a list of cycles (each cycle being a sub-list)
  6.     all_cycles = []
  7.  
  8.     for x in indices:       # Work through the given indices list one position at a time
  9.         # Initialise a list for one cycle, containing the index of the start point within indices
  10.         one_cycle = [x]
  11.         while True:         # Keep looping until we break out
  12.             x = indices[x]              # Pick up the index stored at the current position within indices
  13.             if x == one_cycle[0]:       # Have we returned to the start point in the current cycle?
  14.                 one_cycle.sort()        # Yes - Sort this one cycle, so that we don't create duplicates
  15.                 if one_cycle not in all_cycles:     # Is this a newly discovered cycle?
  16.                     all_cycles.append(one_cycle)    # Yes - append it to our results list
  17.                 break                               # And break out to the outer loop to search again
  18.  
  19.             # We have not hit a cycle point, so append this index to the current cycle
  20.             one_cycle.append(x)
  21.  
  22.     return all_cycles           # Return our result list of all cycles found
  23.  
  24.  
  25. tests = [[2, 0, 1, 4, 3, 5], [0, 1, 2, 3], [3, 2, 0, 1]]
  26. for test in tests:
  27.     print(cycles(test))
  28.  
  29. # Results:
  30. # [[0, 1, 2], [3, 4], [5]]
  31. # [[0], [1], [2], [3]]
  32. # [[0, 1, 2, 3]]
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement