﻿ python – 生成所有唯一的对排列 - 代码日志

#### python – 生成所有唯一的对排列

``````import itertools

for perm in itertools.permutations(range(9)):
print zip(perm[::2], perm[1::2])
``````

``````...
[(8, 4), (7, 6), (5, 3), (0, 2)]
[(8, 4), (7, 6), (5, 3), (1, 0)]
[(8, 4), (7, 6), (5, 3), (1, 2)]
[(8, 4), (7, 6), (5, 3), (2, 0)]
[(8, 4), (7, 6), (5, 3), (2, 1)]
[(8, 5), (0, 1), (2, 3), (4, 6)]
[(8, 5), (0, 1), (2, 3), (4, 7)]
[(8, 5), (0, 1), (2, 3), (6, 4)]
[(8, 5), (0, 1), (2, 3), (6, 7)]
[(8, 5), (0, 1), (2, 3), (7, 4)]
[(8, 5), (0, 1), (2, 3), (7, 6)]
[(8, 5), (0, 1), (2, 4), (3, 6)]
[(8, 5), (0, 1), (2, 4), (3, 7)]
[(8, 5), (0, 1), (2, 4), (6, 3)]
...
``````

``````from collections import deque

def round_robin_even(d, n):
for i in range(n - 1):
yield [[d[j], d[-j-1]] for j in range(n/2)]
d[0], d[-1] = d[-1], d[0]
d.rotate()

def round_robin_odd(d, n):
for i in range(n):
yield [[d[j], d[-j-1]] for j in range(n/2)]
d.rotate()

def round_robin(n):
d = deque(range(n))
if n % 2 == 0:
return list(round_robin_even(d, n))
else:
return list(round_robin_odd(d, n))

print round_robin(5)
[[[0, 4], [1, 3]],
[[4, 3], [0, 2]],
[[3, 2], [4, 1]],
[[2, 1], [3, 0]],
[[1, 0], [2, 4]]]

print round_robin(2)
[[[0, 1]]]
``````

`````` round 1     round 2       # pairs are those numbers that sit
----------  ---------      # on top of each other
0 1 2 3 4   8 0 1 2 3
8 7 6 5     7 6 5 4
``````

(我错过了第一次因为我只检查了不均匀的情况.这产生了一个非常错误的算法……这表明在实现算法时检查边缘情况是多么重要……)

`````` round 1     round 2       # pairs are those numbers that sit
----------  ---------      # on top of each other
0 1 2 3     0 7 1 2
7 6 5 4     6 5 4 3
``````

``````def round_robin(n):
is_even = (n % 2 == 0)
schedule = []
d = deque(range(n))
for i in range(2 * ((n - 1) / 2) + 1):
schedule.append(
[[d[j], d[-j-1]] for j in range(n/2)])
if is_even:
d[0], d[-1] = d[-1], d[0]
d.rotate()
return schedule
``````

``````def round_robin_odd(d, n):
for i in range(n):
h = [[d[j], d[-j-1]] for j in range(n/2)]
h[-1].append(d[n/2])
yield h
d.rotate()
``````

``````print round_robin(5)
[[[0, 4], [1, 3, 2]],
[[4, 3], [0, 2, 1]],
[[3, 2], [4, 1, 0]],
[[2, 1], [3, 0, 4]],
[[1, 0], [2, 4, 3]]]
``````