codewars(Python):Easy Diagonal 组合数的计算

codewars(Python):Easy Diagonal

Instructions

In the drawing below we have a part of the Pascal’s triangle, lines are numbered from zero (top). The left diagonal in pale blue with only numbers equal to 1 is diagonal zero, then in dark green (1, 2, 3, 4, 5, 6, 7) is diagonal 1, then in pale green (1, 3, 6, 10, 15, 21) is diagonal 2 and so on.解释一下原题并没有给出图片,不过上题所指的就是杨辉三角。
杨辉三角
We want to calculate the sum of the binomial coefficients on a given diagonal. The sum on diagonal 0 is 8 (we’ll write it S(7, 0), 7 is the number of the line where we start, 0 is the number of the diagonal). In the same way S(7, 1) is 28, S(7, 2) is 56.Can you write a program which calculate S(n, p) where n is the line where we start and p is the number of the diagonal?The function will take n and p (with: n >= p >= 0) as parameters and will return the sum.

Examples:

diagonal(20, 3) => 5985
diagonal(20, 4) => 20349

Hint:

When following a diagonal from top to bottom have a look at the numbers on the diagonal at its right.

我的代码

这道题目呢难的不是理解题目,是算法,我试了,不是递归深度超了,而且不知道为什么设置了,也没有办法通过测试。难在算组合数。最后直接找了scipy库,对于最后的答案要用到C(n,m)=C(n-1,m-1)+C(n-1,m)这个性质合并一下。
对scipy库介绍一下吧,是一个第三方的科学计算包,要自己安装的。用这个包可以直接算出组合数。

from scipy.misc import comb
def diagonal(n, p):
    return comb(n+1, p+1, exact=True)#comb有个默认为False的 extra参数,会用浮点数去算,要改成true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zhanghp947

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值