加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 通过滚动6面骰子从起点到达N个空间有多少种可能性?

发布时间:2020-12-20 12:34:31 所属栏目:Python 来源:网络整理
导读:我刚刚开始像一周前的 python,现在我被困在关于掷骰子的问题上.这是我朋友昨天寄给我的一个问题,我不知道如何自己解决. Imagine you are playing a board game. You roll a 6-faced dice and move forward the same number of spaces that you rolled. If th
我刚刚开始像一周前的 python,现在我被困在关于掷骰子的问题上.这是我朋友昨天寄给我的一个问题,我不知道如何自己解决.

Imagine you are playing a board game. You roll a 6-faced dice and move forward the same number of spaces that you rolled. If the finishing point is “n” spaces away from the starting point,please implement a program that calculates how many possible ways there are to arrive exactly at the finishing point.

所以看起来我将使用带有“N”的参数来创建一个函数,当它到达某个点时,让我们说10,所以我们都可以看到有多少可能性从起点开始到达10个空格.

我想这与“组合”有关,但我不确定它应该如何在python中编码.

拜托,Python大师!

解决方法

这是计算精确结果的一种方法,既不使用迭代也不使用递归:

def ways(n):
    A = 3**(n+6)
    M = A**6 - A**5 - A**4 - A**3 - A**2 - A - 1
    return pow(A,n+6,M) % A

for i in xrange(20):
    print i,'->',ways(i)

输出与https://oeis.org/A001592一致

0 -> 1
1 -> 1
2 -> 2
3 -> 4
4 -> 8
5 -> 16
6 -> 32
7 -> 63
8 -> 125
9 -> 248
10 -> 492
11 -> 976
12 -> 1936
13 -> 3840
14 -> 7617
15 -> 15109
16 -> 29970
17 -> 59448
18 -> 117920
19 -> 233904

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读