首页 > 解决方案 > 如何在 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

标签: python

解决方案


对字符串使用格式化字符串而不是+操作,并像这样比较两个列表:

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

推荐阅读