Reputation: 131
Hello there is there a way to do 5C2 in python? I am a noob in python and i can't find the answer anywhere. The answer has to be 10. Ive been trying to play around with but i can only get errors, Here's my code I need to get 10
from itertools import *
print(combinations(5,2))
It gives me:
TypeError: 'int' object is not iterable
Any help is appreciated
Upvotes: 0
Views: 1368
Reputation: 231
If the goal is to find number of combinations (n choose k) as one number, in my opinion, the following is the simplest way, if you can use Python 3.8.
From Python 3.8 there is the math.comb(n, k)
function in math module.
import math
print(math.comb(5,2))
Gives
10
Some references:
https://www.w3schools.com/python/ref_math_comb.asp
https://www.geeksforgeeks.org/python-math-comb-method/
Upvotes: 1
Reputation: 113905
In [35]: def choose(n,k):
....: return math.factorial(n)/(math.factorial(k)*math.factorial(n-k))
....:
In [36]: choose(5,3)
Out[36]: 10.0
Don't forget to import math
Upvotes: 1
Reputation: 339052
Since you are asking explicitely about finding the number of combinations using itertools, the solution would be
import itertools
print len(list(itertools.combinations(range(5),2)))
Let me explain: itertools.combinations(iterator, k)
takes as arguments an iterator (which can be a list) and the number of elements to chose from that list. Instead of answering the question of how many combinations of k
element tuples you can draw from that list, it returns that list directly.
So given an n
element list from which all k
-tuples should be drawn and looking at the length of that list, gives you the binomial coefficient.
Of course there are easier ways to calculate the binomial coefficient, using e.g. scipy.special.binom
import scipy
print scipy.special.binom(5,2)
Upvotes: 0