python - 如何在Python中定义一个使多项式相等的函数

标签 python

我用 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/

相关文章:

python - 支持前端CSS和HTML的Python GUI?

python - 在 python 中实现高效的固定大小 FIFO

python - 从图中删除节点

python - 我是否能够将变量分离到另一个类中但保持用法相同?

python - 将用户定义的数组设置为 Pyevolve 中的初始个体

python - Pony ORM实体单向映射报错

python - psycopg2 copy_from 在 celery 任务中使用同步连接引发异步 ProgrammingError

python - 列表与特定总和的组合

Python-将根目录名称与所有子文件夹名称连接起来

python - 在 pyparsing 期间更改字符串