在 Python 中删除和替换多项式的系数

4
我在使用Python的多项式列表函数时遇到了一些问题。
例如,如果我写多项式p1 = [0, 0, 0, 1, 1],输出结果为1*x^4 + 1*x^3 + 0*x^2 + 0*x + 0
我想进行以下调整:
  • 系数为1的项应该省略系数,例如"1x^3"应该写成"x^3"

  • 系数为0的项不应该被写出来,例如"x^4 + x^3 + 0*x^2 + 0*x + 0"应该简化为"x^4 + x^3"

是否有相应的Python命令呢?
提前感谢。
/Alex
//代码
def polynomial_to_string(p_list):
    terms = []
    degree = 0

    for coeff in p_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

    terms.reverse()
    final_string = ' + '.join(terms)

    return final_string

1
请发布您想要调整的代码。 - Omar Einea
@AlexanderWest 请将那段代码发布在问题中。作为独立评论查看它很困难。 - RoadRunner
感谢您的回复。问题已解决! - Alexander West
1
答案不同的一个原因在于你的问题存在歧义。负系数应该是先加后减,如 x^2 + -3x,还是只需要一个减号,如 x^2 - 3x - Rory Daulton
6个回答

4
这里有一种另外的方法,也处理了符号:
>>> def getsign(n):
...     return '-' if n<0 else '+'
...
>>>
>>> def polynom(l):
...     pl = ['' if j==0 else '{}x^{}'.format(getsign(j),i) if j==1 or j==-1 else '{}{}x^{}'.format(getsign(j),abs(j),i) for i,j in enumerate(l)]
...     return ''.join([str(l[0])]+pl) if l[0]!=0  else ''.join(pl)
...
>>> print polynom([0, 0, 0, -1, -2, 1, 7])
-x^3-2x^4+x^5+7x^6

我认为你想要使用'{}{}x^{}'.format(getsign(j),abs(j),i),而不是'{}{}x^{}'.format(getsign(j),j,i)。否则,对于那些不是“ -1 ”的负系数,你最终会得到两个连续的减号。 - Mark Dickinson
@MarkDickinson 是的,非常感谢您,我错过了那部分内容,并且已经更正了我的回答。 - coder
谢谢!这对我帮助很大! - Alexander West

3
这是一个将列表转换为具有正确系数条件的多项式的单行代码。
p = [0, 0, 0, 1, 1]

s = ' + '.join('%d*x^%d' % (pi, i) if pi != 1 else 'x^%d' % i for i, pi in enumerate(p) if pi != 0)

s

'x^3 + x^4'

要按相反的顺序打印(高位数先):
    s = ' + '.join('%d*x^%d' % (pi, i) if pi != 1 else 'x^%d' % i for i, pi in reversed(list(enumerate(p))) if pi != 0)

加入之前,也许可以反转结果([ ][::-1]),使高幂项排在前面。(+1) - trincot
谢谢!这对我帮助很大! - Alexander West

1
你也可以这样做,
def unity(num):
    if num==1:return('')
    elif num=='':return('.1')
    return num

coeffs = [3,2,0,1,6] #6x^4 + 1x^3 + 0x^2 + 2x + 1
variables = ['x^4','x^3','x^2','x','']

output = ' + '.join([str(unity(i))+unity(j) for i,j in zip(coeffs[::-1],variables) if i])
print(output)
>>>'6x^4 + x^3 + 2x + 3.1'

谢谢!这对我帮助很大! - Alexander West

1
我使用enumerate来执行degree技巧,并通过简单的流程指令避免了不必要的内容。希望它不像其他解决方案一样难以理解。
def polynomial_to_string(p_list):
    terms = []

    for degree, coeff in enumerate(p_list):
        if not coeff:
            continue
        if coeff in [1, '1']:
            coeff = ''
        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)

    terms.reverse()
    final_string = ' + '.join(terms)

    return final_string


print polynomial_to_string([0, 0, 0, 1, 1])

谢谢!这对我帮助很大! - Alexander West

1

尽可能少的更改您的代码,以使其按预期工作,但我建议您先了解Gerges Dib的第一个答案。

def polynomial_to_string(p_list):
    terms = []
    degree = 0

    for coeff in p_list:
        if coeff > 0:
            if coeff == 1:
                coeff = ''
            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

    terms.reverse()
    final_string = ' + '.join(terms)

    return final_string

谢谢!这对我帮助很大! - Alexander West

0
这可能会有所帮助(不完全是一行代码):
def polynonmial_equation(coefficients):
        degree = len(coefficients) - 1

        temp = "".join(map(lambda x: "" if x[1] == 0 else [" - ", " + "][x[1]> 0] + [str(abs(x[1])) + "*", ""][abs(x[1]) == 1] + "x^" + str(degree -x[0]), enumerate(reversed(coefficients)))).strip()

        return temp if temp.startswith('-') else temp[1:]

上述函数的更具表现力的形式:

def polynonmial_equation(coefficients):
    degree = len(coefficients) - 1
    temp = "".join(map(lambda x: "" if x[1] == 0 else
                   [" - ", " + "][x[1] > 0] +
                   [str(abs(x[1])) + "*", ""][abs(x[1]) == 1] +
                   "x^" + str(degree - x[0]),
                   enumerate(reversed(coefficients)))).strip()
    return temp if temp.startswith('-') else temp[1:]


print(polynonmial_equation([0, 0, 0, 1, 1]))
print(polynonmial_equation([0, 0, 0, 1, -1]))
print(polynonmial_equation([0, 0, 0, -1, -1]))
print(polynonmial_equation([0, 0, 0, -1, 1]))
print()
print(polynonmial_equation([0, 0, 0, 1, 3]))
print(polynonmial_equation([0, 0, 0, 1, -3]))
print(polynonmial_equation([0, 0, 0, -1, -3]))
print(polynonmial_equation([0, 0, 0, -1, 3]))
print()
print(polynonmial_equation([1, 2, 3, 4, 5]))
print(polynonmial_equation([-1, 2, -3, 4, -5]))
print(polynonmial_equation([-1, 2, 0, 4, -5]))
print(polynonmial_equation([0, 0, 6, -1, -3]))
print(polynonmial_equation([0, -3, 4, -1, 0]))

输出结果:

 x^4 + x^3
- x^4 + x^3
- x^4 - x^3
 x^4 - x^3

 3*x^4 + x^3
- 3*x^4 + x^3
- 3*x^4 - x^3
 3*x^4 - x^3

 5*x^4 + 4*x^3 + 3*x^2 + 2*x^1 + x^0
- 5*x^4 + 4*x^3 - 3*x^2 + 2*x^1 - x^0
- 5*x^4 + 4*x^3 + 2*x^1 - x^0
- 3*x^4 - x^3 + 6*x^2
- x^3 + 4*x^2 - 3*x^1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接