简体   繁体   English

python中使用itertools的组合

[英]Combinations in python using itertools

Hello there is there a way to do 5C2 in python?你好,有没有办法在 python 中做 5C2? I am a noob in python and i can't find the answer anywhere.我是 python 的菜鸟,我在任何地方都找不到答案。 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答案必须是 10。我一直在尝试玩,但我只能得到错误,这是我的代码,我需要得到 10

from itertools import *
    print(combinations(5,2))

It gives me:它给了我:

TypeError: 'int' object is not iterable

Any help is appreciated任何帮助表示赞赏

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不要忘记导入数学

Since you are asking explicitely about finding the number of combinations using itertools , the solution would be由于您明确询问使用 itertools查找组合数,因此解决方案是

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.让我解释一下: itertools.combinations(iterator, k)将迭代器(可以是列表)和要从该列表中选择的元素数量作为参数。 Instead of answering the question of how many combinations of k element tuples you can draw from that list, it returns that list directly.它不是回答您可以从该列表中提取多少个k元素元组组合的问题,而是直接返回该列表。 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.因此,给定一个n元素列表,应从中绘制所有k元组并查看该列表的长度,从而为您提供二项式系数。

Of course there are easier ways to calculate the binomial coefficient, using eg scipy.special.binom当然有更简单的方法来计算二项式系数,例如使用scipy.special.binom

import scipy
print scipy.special.binom(5,2) 

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.如果目标是找到组合数(n 选择k)为一个数,在我看来,以下是最简单的方法,如果可以使用Python 3.8。
From Python 3.8 there is the math.comb(n, k) function in math module.从 Python 3.8 开始, math 模块中有math.comb(n, k)函数。

import math

print(math.comb(5,2))

Gives

10

Some references:一些参考:
https://www.w3schools.com/python/ref_math_comb.asp https://www.w3schools.com/python/ref_math_comb.asp
https://www.geeksforgeeks.org/python-math-comb-method/ https://www.geeksforgeeks.org/python-math-comb-method/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM