将排列更改为组合 (PYTHON)

changing a permutation into combinations (PYTHON)

我错误地使用了排列而不是组合,我应该将用户在此程序中输入的名字成对打印出来,而不是所有名字的排列在一起,这是我的代码片段,可以找到完整的代码 HERE 所以一般的问题不是打印出每个可能的名称组合,而是如何打印不重复的 2 对?

names = []

for i in range(n): names.append(raw_input("Enter name " + str(i + 1) + ": "))

count = 0


def perm(a, k=0):
global count
if (k == len(a)):
    print a

    count += 1
 else:
    for i in xrange(k, len(a)):
        a[k], a[i] = a[i], a[k]
        perm(a, k + 1)
        a[k], a[i] = a[i], a[k]


if n % 2 == 0:
print""
perm(names)
print"total combinations available: " + str(count)
else:

perm(names)
print"total combinations available: " + str(count)
print("please enter an even number next time")

sys.exit()

您可以使用itertools.combinations()创建所有可能的组合,然后使用set()过滤掉所有唯一的组合:

import itertools
...
combinations = set(itertools.combinations(names, 2))

但是,在您的代码中,您似乎只关心 number 个可能的组合。您可以使用内置函数 len() 来查找:

number_of_combinations = len(combinations)

无论您在哪里使用 count,都将其替换为 number_of_combinations