2

I'd like to start by saying that I'm fairly new to Python and am very interested in coding in general. I have some familiarity with basic concepts, but the functions used specifically in Python are largely unknown to me. Fwiw I'm a visual/experiential learner.

I'd also like to state right off the bat that I apologize if this question has been asked and already answered. I found alot of "similar" questions, but none that really helped me find a solution.

Problem

As stated in my topic title I'm interested in creating an "output" (correct terminology?) of an nCr into a list or whatever is the best method to view it.

It would be a 10 choose 5. The ten variables could be numbers, letters, names, words, etc. There are no repeats and no order to the combinations.

Research

I would like to say that I'd looked at similar topics like this question/answer and found the concepts helpful, but have discovered that in the example code:

    from itertools import izip

    reduce(lambda x, y: x * y[0] / y[1], izip(xrange(n - r + 1, n+1), xrange(1, r+1)), 1)

The reduce tool/function isn't used that way anymore. I think I read that it changed to functools as of Python 3.

Question

How would the above code (examples are helpful) or any other be updated/changed to accommodate for reduce? Are there any other ways to output the combination results?

***Edit*** I think I didn't clearly connect the content of the Problem and Question headings. Basically my main question is under the Problem heading. While it is helpful to see how a person can use the itertools to make combinations from a list, I don't have any idea how to output the 10 choose 5. :\

Community
  • 1
  • 1
CusterDawg
  • 21
  • 4
  • 1
    `reduce` used to be a built-in function. It's now a function inside the `functools` package. Nothing else should have changed. The equivalent line in Python3 is `reduce(lambda x, y: x * y[0] / y[1], zip(range(n - r + 1, n+1), range(1, r+1)), 1)` after the import `from functools import reduce`. Note the changes `izip -> zip` and `xrange -> range` – Adam Smith Nov 02 '15 at 18:25
  • Could you give an example of what you would like the output to look like? – glibdud Nov 02 '15 at 20:27
  • I'm looking for something like: `Variables are 1/a/2/b/3/c/4/d/5/e output is 1a2b3, 1a2bc, 1a2b4...` and so on. – CusterDawg Nov 04 '15 at 01:08

1 Answers1

0

Are you trying to do:

>>> import itertools
>>> for combination in itertools.combinations('ABCDEFGHIJ', 5):
>>>    print(''.join(combination))
ABCDE
ABCDF
ABCDG
ABCDH
ABCDI
ABCDJ
ABCEF
ABCEG
ABCEH
ABCEI

If so, it's done. If you want to learn how to implement the combinations function yourself, you're lucky because the itertools.combinations documentation gives an implementation.

Julien Palard
  • 8,736
  • 2
  • 37
  • 44