Skip to content

Instantly share code, notes, and snippets.

@rntz
Last active July 4, 2017 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rntz/ffe18dbe016747cdeeebb85d0aeaa11b to your computer and use it in GitHub Desktop.
Save rntz/ffe18dbe016747cdeeebb85d0aeaa11b to your computer and use it in GitHub Desktop.
# this is python3
import random
# generates a cyclic permutation of length `n`
def cycle_permutation(n):
shuffled = list(range(n))
random.shuffle(shuffled)
graph = {shuffled[i]: shuffled[(i+1)%n] for i in range(n)}
return [graph[i] for i in range(n)]
# returns a set of the cycles of a permutation
def cycles(p):
n = len(p)
todo = set(range(n))
cycles = set()
while todo:
init = todo.pop()
# find the cycle starting at `init`
cycle = [init]
x = init
while True:
x = p[x]
if x == init: break
todo.remove(x)
cycle.append(x)
cycles.add(tuple(cycle))
return cycles
# try running: cycles(cycle_permutation(N))
# for some positive integer N.
# it should always return a singleton set.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment