编写一个接受表示多项式的列表的函数
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)
无论我尝试多少次,我就是无法让所有的测试通过。
1 个回答
0
我不太明白你在问什么,但我还是试着回答一下。
你想在Python中定义一个函数(你应该把这个加到你的标签里),这个函数叫做print_poly([coef0, coef1, ..., coefn]),它的输出应该是一个多项式:
coef0*x^(n) + coef1*x^(n-1) + ... + coefn
你可以试试这个:
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)
这就是你的答案,但老实说,你应该自己去了解一下Python的函数定义、布尔运算符和数学运算符,因为看起来你对这些还不太熟悉。
布尔运算符 - https://docs.python.org/3.1/library/stdtypes.html
算术运算 - http://en.wikibooks.org/wiki/Python_Programming/Operators
函数 - http://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_3/Defining_Functions
如果你有决心的话,可以看看这个:
《艰难的Python学习之路》(http://learnpythonthehardway.org/)