我用 Python 编写了一个函数,它接受列表多项式并忽略末尾的所有零多项式。
我现在的任务是定义一个函数eq_poly(p,q)
,它接受列表中的两个多项式,如果它们相等则输出True
,如果它们相等则输出False
如果它们不相等。
请注意,应保留末尾属性处的零。所以
p = [1,2,3,0]
q = [1,2,3]
仍应输出True
。
谁能告诉我该怎么做?代码写在下面。
def drop_zeroes(list):
while list and list[-1] == 0: #drops zeroes at the end, all else equal
list.pop()
terms = []
degree = 0
# Collect a list of terms
for coeff in list:
if degree == 0:
terms.append(str(coeff))
elif degree == 1:
terms.append(str(coeff) + 'x')
else:
term = str(coeff) + 'x^' + str(degree)
terms.append(term)
degree += 1
final_string = ' + '.join(terms) # The string ' + ' is used as "glue" between the elements in the string
return final_string
b = [1,2,0,3,2,0,0] #example of list with zeroes at the end
drop_zeroes(b)
预期输出:
1 + 2x + 0x^2 + 3x^3 + 2x^4
最佳答案
使用格式化字符串而不是字符串的 +
操作,并像这样比较两个列表:
def drop_0s_and_compare(p, q):
results = []
for lst in [p, q]:
while lst[-1] == 0:
lst.pop()
final_string = ''
for i, coeff in enumerate(lst):
if not i:
final_string += f'{coeff}'
elif i == 1:
final_string += f' + {coeff}x'
else:
final_string += f' + {coeff}x^{i}'
results.append(final_string)
return results[0] == results[1]
p = [1,2,3,0]
q = [1,2,3]
print(drop_0s_and_compare(p, q))
输出:
True
这是一个更短的方法:
def drop_0s_and_compare(p, q):
results = []
for lst in [p, q]:
while lst[-1] == 0:
lst.pop()
final_string = ''.join([f' + {coeff}x^{i}' if i else str(coeff) for i, coeff in enumerate(lst)]).replace('^1', '')
results.append(final_string)
return results[0] == results[1]
p = [1, 2, 3]
q = [1, 2, 3, 0]
print(drop_0s_and_compare(p, q))
输出:
True
关于python - 如何在Python中定义一个使多项式相等的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64848180/