数据结构2.1-一元多项式的乘法与加法运算

问题

数据结构2.1-一元多项式的乘法与加法运算_第1张图片
一元多项式的乘法与加法运算

代码

p = {}

def mysplit(s, split = ' '):
    l = []
    for i in s:
        if i == split:
            num = s[ : s.index(i)]
            if len(num) != 0:
                l.append(num)
            s = s[s.index(i)+1 : ]
            
    l.append(s)         
    return l

# get and pretty the input polynomial 1 and 2
for i in range(2):
    s = input()
    l = mysplit(s)
    n = int(l.pop(0))
    p[i+1] = {}
    for j in range(n):
        p[i+1][int(l[j*2+1])] =int(l[j*2])

# do the polynomial multiplication
p['*'] = {}
for i in p[1]:
    for j in p[2]:
        if p['*'].get(i+j):
            p['*'][i+j] += p[1][i] * p[2][j]
        else:
            p['*'][i+j] = p[1][i] * p[2][j]

# do the polynomial addition
p['+'] ={}
p['+'] = p[1]
for j in p[2]:
    if p['+'].get(j):
        p['+'][j] += p[2][j]
    else:
        p['+'][j] = p[2][j]

# deal the case if a polynomial is empty
def zero(p):
    for i in p:
        if p[i] != 0:
            return
    p.clear()
    p[0] = 0

zero(p['*'])
zero(p['+'])

# print the polynomial
def pprint(p):
    for i in sorted(p, reverse = True):
        e = ' '
        if(i  == sorted(p, reverse = True)[-1]):
            e = ''

        print(p[i], i, end = e)

pprint(p['*'])
print('')
pprint(p['+'])

有任何问题请回复提出。然后欢迎关注微信公众号格物致愚

格物致愚

你可能感兴趣的:(数据结构2.1-一元多项式的乘法与加法运算)