简体   繁体   English

在 Python 中计算多项式?

[英]Calculating polynomials in Python?

I really don't have code to post with this, since I'm pretty stuck on how to write it.我真的没有代码可以发布这个,因为我很困惑如何编写它。 I have to give a list of positive ints and an x value to replicate the following example:我必须给出一个正整数列表和一个 x 值来复制以下示例:

>>> poly([1, 2, 1], 2)
9
>>> poly([1, 0, 1, 0, 1], 2)
21
>>> poly([1, 0, 1, 0, 1], 3)
91

The equation I have is p(x) = a0 + a1x + a2x**2 + a3x**3 + ... + anx**n , so an idea I had was checking the length of the list and making it so that it automatically determined how many calculations it had to do, then just replacing x with whatever value was outside the list.我的等式是p(x) = a0 + a1x + a2x**2 + a3x**3 + ... + anx**n ,所以我的一个想法是检查列表的长度并使其成为它会自动确定它必须进行多少次计算,然后将 x 替换为列表之外的任何值。 Unfortunately I don't know how to write that or where to start really.不幸的是,我不知道该怎么写,也不知道从哪里开始。

Even better if you have numpy:如果你有 numpy,那就更好了:

>>> from numpy import polyval
>>> polyval([1, 2, 1], 2)
9
>>> polyval([1, 0, 1, 0, 1], 2)
21

I think you have to reverse the a_list first though.我认为你必须先反转 a_list 。 (it happens to work since a_list is palindromic ) (它碰巧有效,因为 a_list 是回文)

Here is how you can implement poly :以下是实现poly

def poly(l, x):
    sum = 0
    xp =1 
    for a in l:
        sum += a *xp #add next term
        xp = x* xp #xp is x^p
    return sum

print poly([1,2,1],2)
print poly([1,0,1,0,1],3)
def poly(a_list, x):
    ans = 0
    for n,a in enumerate(a_list):
        ans += a*x**n
    return ans

The enumerate function returns a tuple containing the index and value of each element in the list. enumerate 函数返回一个包含列表中每个元素的索引和值的元组。 So you can iterate easily through a list using "for index,value in enumerate(list)".因此,您可以使用“for index,value in enumerate(list)”轻松遍历列表。

You could use itertools starmap你可以使用itertools 星图

>>> from itertools import starmap
>>> def poly(a_list, x):
...     val = lambda p, a: a*x**p
...     return sum(starmap(val, enumerate(a_list)))
...
>>> poly([1, 2, 1], 2)
9
>>> poly([1, 0, 1, 0, 1], 2)
21

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM