如何在Python中定义等同于多项式的函数
我用Python编写了一个函数,它接受列表多项式并忽略末尾的所有零多项式 我现在的任务是定义一个函数如何在Python中定义等同于多项式的函数,python,Python,我用Python编写了一个函数,它接受列表多项式并忽略末尾的所有零多项式 我现在的任务是定义一个函数eq_poly(p,q),它在列表中取两个多项式,如果它们相等,则输出True,如果它们不相等,则输出False 请注意,应该保留end属性处的零。所以 p = [1,2,3,0] q = [1,2,3] 仍应输出True 谁能告诉我怎么做?代码写在下面 def drop_zeroes(list): while list and list[-1] == 0: #drops zeroes
eq_poly(p,q)
,它在列表中取两个多项式,如果它们相等,则输出True
,如果它们不相等,则输出False
请注意,应该保留end属性处的零。所以
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
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
True
有很多方法可以做到这一点。这里有一个:
def remove_zeros(p):
# this just creates a copy of p so we don't mutate it:
p = [j for j in p]
while True:
if p[-1] == 0:
p.pop()
else:
break
return p
def eq_poly(p, q):
q = remove_zeros(q)
p = remove_zeros(p)
if len(p) != len(q):
return False
for j, k in zip(p,q):
if j != k:
return False
return True
# examples:
p = [1,2,3,0]
q = [1,2,3]
eq_poly(p,q) # True
eq_poly([2,1,2], [2,1,2]) # True
eq_poly([2,1,0], [2,1]) # True
eq_poly([2,1,0,1], [2,1]) # False
只需使用现有函数删除两个列表中的所有最后零,然后测试剩余的是否相等。