Skip to content

Instantly share code, notes, and snippets.

@phil8192
Created September 14, 2018 17:12
Show Gist options
  • Save phil8192/4865308649b6c34941986125d8fbb540 to your computer and use it in GitHub Desktop.
Save phil8192/4865308649b6c34941986125d8fbb540 to your computer and use it in GitHub Desktop.
def sample(x):
"""
1
2 3
4 5 6 7
=
4 2 6 1 3 5 7
>>> list(sample(['a', 'b', 'c', 'd', 'e', 'f', 'g']))
[('d', 1), ('b', 2), ('f', 2), ('a', 3), ('c', 3), ('e', 3), ('g', 3)]
"""
def pivot(x):
p = len(x) // 2
l = x[:p]
r = x[p+1:]
return x[p], l, r
q = deque([(x, 0)])
while q:
x = q.popleft()
p, l, r = pivot(x[0])
depth = x[1] + 1
if l: q.append((l, depth))
if r: q.append((r, depth))
yield p, depth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment