Skip to content

Instantly share code, notes, and snippets.

@too
Last active September 4, 2015 09:30
Show Gist options
  • Save too/631e7e34defecb02c890 to your computer and use it in GitHub Desktop.
Save too/631e7e34defecb02c890 to your computer and use it in GitHub Desktop.
一个看似简单但是还挺麻烦的问题

有 1到14 这14个数字,要求排列组合成 一个列表S, 列表S中 包含14个 元素A, 每个元素 都是一个 包含 7 个数字对的 列表, 就像这样

S = [A1, A2, A3 ... A14] A1 = [(1,2), (3,4) ... (13, 14)]

要求是 在每个元素A中, 这14个数字 各出现一次, 并且只出现一次 在整个 S中, 没有 重复的 数字对。 比如 (4, 8) 出现了 两个以上的元素中, 这是不允许的。

请生成这样的列表S

#!/usr/bin/env python
# -*- coding: utf-8 -*- #
import unittest
class TestIt(unittest.TestCase):
nums = range(1, 15)
count = len(nums)
def test_get_result(self):
res = get_result()
all_pairs = []
self.assertTrue(len(res) > 0)
for a in res:
print a
m, n = zip(*a)
tl = list(m + n)
tl.sort()
self.assertEqual(len(tl), self.count)
self.assertEqual(set(tl), set(self.nums))
all_pairs.extend(a)
print
self.assertEqual(len(all_pairs), len(set(all_pairs)))
print 'Total:', len(res)
def get_result():
a = [(l, k) for k in range(1,15) for l in range(1,15) if k!=l]
result = []
for l in range(40):
tmpset = set()
tmplist = []
for col in range(7):
for thedate in a:
if len(tmpset & set(thedate)) == 0:
tmplist.append(thedate)
tmpset = tmpset|set(thedate)
a.remove(thedate)
if len(tmplist) == 7:
tmplist.sort()
result.append(tmplist)
else:
a.extend(tmplist)
if len(result) == 14:
break
return result
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment