Answer to Question #242870 in Python for bannu

Question #242870

for this inputs

5

0 -2

3 6

4 7

1 -3

2 -1

5

0 1

1 2

2 -4

3 3

4 5

expected output is

12x^4 + 9x^3 - 5x^2 - x - 1

but output is

12x^4 + 9x^3 - 5x^2 - 1x - 1

for question #206080



1
Expert's answer
2021-09-28T00:50:03-0400
def enter_polinom():


  while True:
    try:
      N = int(input(''))
    except:
      print('enter positive integer')
      continue
    if N < 0:
      print('enter positive integer')
      continue
    break
  P = []
  k = 0
  while k < N:
    try:
      t = list(map(int, input('').split()))
      if len(t) != 2:
        print('enter two integers')
        continue
      k += 1
    except:
      print('enter two integers')
      continue
    add = True
    for i in range(len(P)):
      if P[i][0] == t[0]:
        P[i][1] += t[1]
        add = False
    if add:
      P.append(t) 
  return P


def add_polinoms(pol_1, pol_2):
    added = []
    while pol_1 or pol_2:
        if pol_1:
            tmp = pol_1.pop(0)
            for i in range(len(pol_2)):
                if pol_2[i][0] == tmp[0]:
                    tmp[1] += pol_2[i][1]
                    pol_2.pop(i)
                    break
        else:
            tmp = pol_2.pop(0)


        added.append(tmp)
    added.sort(reverse=True)
    return(added)


def polinom_to_str(p, c, first=True):
  s = ''
  if c == 0:
    return s
  if first:
    if c < 0:
      s += '-'
      c *= -1
  else:
    if c < 0:
      s += ' - '
      c *= -1
    elif c > 0:
      s += ' + '
  if c != 1:
    s += '{}'.format(c)
  if p > 1:
    s += 'x^{}'.format(p)
  elif p == 1:
    s += 'x'
  elif p < 0:
    s += 'x^({})'.format(p)
  elif p == 0 and c == 1:
    s += '{}'.format(c)
  return s


def print_polinom(p):
  s = ''
  for el in p:
    s += polinom_to_str(el[0], el[1], len(s)==0)
  if len(s) == 0:
    print('0')
  else:
    print(s)


for i in range(1):
  A = enter_polinom()
  B = enter_polinom()
  print_polinom(add_polinoms(A, B))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS