使用递归来阻止二项式 [英] Use recursion to FOIL a binomial

查看:86
本文介绍了使用递归来阻止二项式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Pascal的Triangle挫败二项式.我有代码:

I'm trying to foil a binomial using Pascal's Triangle. I have the code:

def next(row):
  newrow = [ row[k-1]+row[k]
             for k in range(1,len(row)) ]
  return [1] + newrow + [1]
def pascal(rowsleft,oldrow):
  if rowsleft > 0:
    R = next(oldrow)
    pascal(rowsleft-1,R)
list1 = [1]
list121 = [1,2,1]
pascal(3,[1,2,1])
rowsleft = exponent

我想做的全部事情就是以等式(x + 1)^ 3"为例,然后将其挫折为[(1x ^ 3 * 1 ^ 0)+(3x ^ 2 * 1 ^ 1) +(3x ^ 1 * 1 ^ 2)+(3x ^ 0 * 1 ^ 3)],结果合并为:x ^ 3 + 3x ^ 2 + 3x +1

The full thing I want to do is take an equation "(x+1)^3" for example, and foil it to [(1x^3*1^0) + (3x^2*1^1) + (3x^1*1^2) + (3x^0*1^3)] with the result concatenated to: x^3 + 3x^2 + 3x + 1

推荐答案

对于解析输入(如我所见,这实际上是您真正需要的),可以使用以下之一:

For parsing input (as I see, that is what you actually need) you can use one of those: str.partition (also check rpartition) or str.split.

示例(以下断言成立):

Examples (following assertions hold):

assert "a;b;c".parition(";") == ("a", ";", "b;c")
assert "a;b;c".split(";") == ["a", "b", "c"]

我将使用分区,以使括号之间的部分(通过"^"进行分区)和元组的最后一部分(我认为是指数部分)之间.然后,我将检查第一部分是否以("开头并以)结尾".现在,我将删除("和)",并用"+"分割剩下的内容.如果"+"不存在,我将其除以-",并假设总和的第二部分为负数.现在,您将拥有加数和指数,可用于形成输出.

I'd use partitioning, to get part between parenthesis (by partitioning by "^"), last part of tuple I'd assume to be expotent. Then, I'd check whether first part starts with "(" and ends with ")". Now, I'd remove "(" and ")" and split whats left by "+". If "+" isn't there, I'd split by "-" and assume second part of sum as negative. Now you'd have both addends and expotent, which you can use to form output.

这篇关于使用递归来阻止二项式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆