简体   繁体   English

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

[英]Removing and replacing coefficients of polynomials in Python

I´m having some trouble using python´s list function for polynomials. 我在使用python的list函数进行多项式时遇到了一些麻烦。

For example, if I write the poynomial p1 = [0, 0, 0, 1, 1] , I get the output 1*x^4 + 1*x^3 + 0*x^2 + 0*x + 0 例如,如果我写了多项式p1 = [0, 0, 0, 1, 1] 0,0,0,1,1 p1 = [0, 0, 0, 1, 1] ,我得到输出1*x^4 + 1*x^3 + 0*x^2 + 0*x + 0

I want to adjust this so that: 我想调整这个,以便:

  • Terms with coefficient 1 are written without the coefficients, eg "1x^3" should be written as "x^3" . 系数1的术语在没有系数的情况下写入,例如"1x^3"应写为"x^3"

  • Terms with coefficient 0 should not be written at all, eg "x^4 + x^3 + 0*x^2 + 0*x + 0" should be simplified as "x^4 + x^3" . 系数为0的术语根本不应写入,例如"x^4 + x^3 + 0*x^2 + 0*x + 0"应简化为"x^4 + x^3"

Is there a command for this in python? 在python中有这个命令吗?

Thanks in advance. 提前致谢。

/Alex /亚历克斯

//the code //编码

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

Here's an alternative way that also deals with the sign: 这是另一种处理标志的方式:

>>> 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

Here is a one liner to convert a list to a polynomial with the correct conditions for coefficients 这是一个将列表转换为具有正确系数条件的多项式的单线程

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'

To print in opposite order (high powers first): 要以相反的顺序打印(首先是高功率):

    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)

You can do this way as well, 你也可以这样做,

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'

I used enumerate to do the degree trick and avoided stuff you don't need with simple flow instructions. 我使用enumerate来做degree技巧,并通过简单的流程指令避免了你不需要的东西。 Hope it is not that cryptic as other solutions ;-) 希望它不像其他解决方案那样神秘;-)

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])

Minimal changes to your code that works as desired , though I suggest you to understand the first answer by Gerges Dib. 尽管我建议您理解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

This might help(not exactly a one-liner): 这可能有所帮助(不完全是单行):

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:]

More re-presentable form of the function above: 以上功能的更多可重现形式:

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]))

And the output: 并输出:

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM