组合选择

2024-04-26 04:52:22 发布

您现在位置:Python中文网/ 问答频道 /正文

总共有N盒不同的球。有P个盒子,每个盒子包含若干个球,其余的Q个盒子每个盒子包含B个球。你知道吗

给定一个数字X,你可以从盒子里至少挑选X个球的方法总数是多少。你知道吗

p=Q+N

例如:Number of P boxes=2每个包含2个球,Number of Q boxes=1每个包含2个球。X=3(Given)其中x=minimum number of balls to be picked 所以,P+Q=3(总箱数) 选择至少x个球(即3个球)的方法的数量组合为:

combinations of 3:(111),(210),(120),(021),(012),(201),(102)
combinations of 4:(220)(202)(022)(211)(121)(112)
combinations of 5:(212)(122)(221)
combinations of 6: (222)
total Combinations: 17

我的方法:
我曾用过“星条旗法”:

^{2}$
1+3+6+10=20
but the answer should be 1+3+6+7=17

在计算3的组合时出现了边缘情况。我该如何解决这个问题?你知道吗

global total_combinations
total_combinations=0

from math import factorial

def combinations(a):
    global total_combinations
    bars=numberofAs+numberofBs-1
    stars=a
    total_combinations+=factorial(stars+bars)/(factorial(bars)*factorial(stars))


numberofAs,numberofBs,numberofballsinA,numberofballsinB=map(int,raw_input().split())

x=int(raw_input())

operational_array=[]

for i in range(numberofAs):
    operational_array.append(numberofballsinA)

for i in range(numberofBs):
    operational_array.append(numberofballsinB)

max_x=sum(operational_array) #calculate combinations from x to max_x
k=max_x

for i in range(max_x,x-1,-1):
    k=max_x-i
    combinations(k)

print total_combinations

PS:我在网上找到这个问题,但我觉得很有趣。你知道吗


Tags: of方法forarraymax盒子totalstars