Python 编写一个函数,该函数接受表示多项式的列表
不管我试了多少次,我都无法通过所有的博士考试 我真的不知道你在问什么,但我还是要试着回答 您希望在python中有一个函数(应将其添加到标记中),该函数的定义使print_poly([coef0,coef1,…,coefn])产生多项式: coef0*x^(n)+coef1*x^(n-1)+…+coefn 试试这个:Python 编写一个函数,该函数接受表示多项式的列表,python,polynomials,Python,Polynomials,不管我试了多少次,我都无法通过所有的博士考试 我真的不知道你在问什么,但我还是要试着回答 您希望在python中有一个函数(应将其添加到标记中),该函数的定义使print_poly([coef0,coef1,…,coefn])产生多项式: coef0*x^(n)+coef1*x^(n-1)+…+coefn 试试这个: def print_poly(p): """ >>> print_poly([4, 3, 2]) 4x^2 + 3x + 2
def print_poly(p):
"""
>>> print_poly([4, 3, 2])
4x^2 + 3x + 2
>>> print_poly([6, 0, 5])
6x^2 + 5
>>> print_poly([7, 0, -3, 5])
7x^3 - 3x + 5
>>> print_poly([1, -1, 0, 0, -3, 2])
x^5 - x^4 - 3x + 2
"""
printable = ''
for i in range(len(p) -1, -1, -1):
poly += ('p[i]' + 'x^' + str(i))
for item in printable:
if 0 in item:
item *= 0
printable += poly[0]
for item in poly[1:]:
printable += item
print(printable)
这是您的答案,但老实说,您应该尝试自己检查python函数定义、布尔运算符和数学运算符,因为看起来您对它们没有很好的掌握
布尔运算符-
算术-
函数-《Python教程》\u 3/定义函数》
如果你有承诺:
艰苦地学习Python()作为第一步,您能让它为指定大小的输入工作吗?例如,假设
p
是一个由3个系数组成的列表,然后尝试从中进行概括。这将有助于确定您的问题是迭代任意大小的列表,还是构造正确的字符串有问题。另外,您的函数是否产生任何输出,或者只是产生与预期输出不一致的输出?poly未初始化,您尝试在其上使用运算符+=。。当你修复它时,会有不正确的输出,但至少会有输出。看起来它是一次性写的。什么是多边形<代码>'p[i]'不会做你认为它会做的事情。沿途打印所有内容
def print_poly(list):
polynomial = ''
order = len(list)-1
for coef in list:
if coef is not 0 and order is 1:
term = str(coef) + 'x'
polynomial += term
elif coef is not 0 and order is 0:
term = str(coef)
polynomial += term
elif coef is not 0 and order is not 0 and order is not 1:
term = str(coef) + 'x^' + str(order)
polynomial += term
elif coef is 0:
pass
if order is not 0 and coef is not 0:
polynomial += ' + '
order += -1
print(polynomial)