in_chainz

Untitled

Nov 10th, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.66 KB | None | 0 0
  1. def get_cycles(a):
  2.     n = len(a)
  3.     used = [0] * n
  4.     cycles = []
  5.     for i in range(n):
  6.         if not used[i]:
  7.             nw = []
  8.             nxt = i
  9.             while not used[nxt]:
  10.                 nw.append(a[nxt])
  11.                 used[nxt] = 1
  12.                 nxt = a[nxt] - 1
  13.             if nw:
  14.                 cycles.append(nw)
  15.     return cycles
  16.  
  17. def rev(a):
  18.     n = len(a)
  19.     nw = [0] * n
  20.     for i in range(n):
  21.         nw[a[i] - 1] = i + 1
  22.     return nw
  23.  
  24. a = [4, 7, 3, 1, 6, 5, 8, 2]
  25. b = [4, 6, 3, 2, 8, 7, 1, 5]
  26. c = [7, 8, 2, 3, 6, 5, 4, 1]
  27. print(get_cycles(a))
  28.  
  29. print(rev(b))
  30. print(get_cycles(rev(b)))
  31.  
  32. print(get_cycles(c))
Advertisement
Add Comment
Please, Sign In to add comment