|
def dice_count(a, b, x):
total = 0
count = 0
for pv in xrange(a, a*b+1):
result = get_stitutions(a, b, pv)
print 'a:', a, 'b:', b, 'count:', pv, 'result:', result
total += len(result)
if pv == x:
count = len(result)
print 'total:', total
print 'count:', count
print 'probability:', count*1.0/total
def get_stitutions(a, b, count):
if count == a:
return [[1] * a]
lst = get_stitutions(a, b, count-1)
result = []
for stitution in lst:
for i in xrange(len(stitution)):
newstitu = copy.deepcopy(stitution)
newstitu[i] += 1
if newstitu[i] > b:
continue
if not containResult(result, newstitu):
result.append(newstitu)
return result
def containResult(result, stitution):
for i in result:
if not [s for s in stitution if s not in i]:
return True
return False
代码说明:
函数get_stitutions是为了获取a个b面骰子情况下 随机抛出count点数所有的情况
假如a=2, b=6, count=3 函数返回的结果为:[[2, 1]]
假如a=2, b=6, count=4 函数返回的结果为:[[3, 1], [2, 2]] 依次类推
函数containResult是为了防止结果中有重复的现象
例如:[[2, 1]] 和 [[1, 2]]是同一种结果 出现这种情况最主要原因是我采用递归来求取点数的情况的
也就是函数get_stitutions的功能
函数的核心是假如我想求取抛出点数为10的所有情况 那么我会将所有抛出点为9的情况遍历
将每种情况下的骰子点数+1 然后在筛选出符合情况的(骰子点数>b 包含相同数据的都不符合情况)
|
|