0

I made the mistake of using permutations instead of combinations, i am supposed to print the names the user enters in this programs in pairs of two, not all the permutations of the names together, here is a snippet of my code, the full code can be found HERE So the general question is instead of printing out every name combination possible, how can i print non repeated pairs of 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()
2
  • 2
    Use itertools.combinations() and set(). Commented Dec 14, 2016 at 14:54
  • @leaf how exactly would i go about with this? delete everything between "for i" up to the "for" statement and replace it? sorry im really noobie Commented Dec 14, 2016 at 14:58

1 Answer 1

1

You can use itertools.combinations() to create all possible combinations, and then use set() to filter out all unique combinations:

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

However, in your code it seems you only care about the number of possible combinations. You can use the builtin function len() to find this:

number_of_combinations = len(combinations)

Wherever you used count replace it with number_of_combinations.

Sign up to request clarification or add additional context in comments.

1 Comment

My pleasure, @ethanjjjjjj.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.