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 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
推荐阅读
- node.js - 有没有办法通过谷歌登录和 cookie 验证快速添加登录/注册页面,以在重新访问 webapp 后保持会话活跃?
- node.js - 如何使用 APIKey 将 Google Cloud Bigquery 与 NodeJS 连接起来
- typescript - 类型“字符串 []”上不存在属性“替换”
- python - 在 Python 中使用 Rainmeter
- javascript - 使用角度双向数据绑定角度7将字符串值绑定到复选框切换
- javascript - 将 id 从 Vue 路由器参数传递到组件的 Vuex 调度
- javascript - 从 rest api (GET REQUEST) 预填充联系表 7 中的数据
- reactjs - AWS Amplify 基于电子邮件的 MFA
- python - 得到一个 keyerror '项目'
- spring - Spring IMAP Poller 在延迟几个小时后读取电子邮件