Answer to Question #245999 in Python for mani

Question #245999
the out put should be 12x^4 + 9x^3 - 5x^2 - x - 1 but our code does not give this out put




1
Expert's answer
2021-10-03T06:35:43-0400
def tostring_polynom(p):
  res = ''
  first = True
  for Pi in sorted(p, reverse=True):
    Ci = p[Pi]
    if first:
      if Ci == 0 and Pi == 0:
        return '0'
       
      if Ci == 1 and Pi != 0:
        pass
      elif Ci == -1 and Pi != 0:
        res = '-'
      else:      
        res = f'{Ci}'
      first = False
       
    else:     
      if Ci > 0:
        res += ' + '
      elif Ci < 0:
        res += ' - '
      else:
        continue
      res += f'{abs(Ci)}'
     
    if Pi == 0:
      continue
    if Pi == 1:
      res += 'x'
    else:
      res += f'x^{Pi}'
  return res
def read_polynom():
  n = int(input())
  p = {}
  for i in range(n):
    L = input().split()
    Pi = int(L[0])
    Ci = int(L[1])
    p[Pi] = Ci
  return p
     

def main():
  p = read_polynom()
  res = tostring_polynom(p)
  final_res = ""
  count = 0
  vals = res.split("+")
  for val in vals:
    if "x" in val:
      test_val = int(val.split("x")[0])
      if test_val==1:
        if count ==0:
          final_res=final_res+val.replace("1","")
        else:
          final_res=final_res+"+"+val.replace("1","")
      else:
        if count==0:
          final_res = final_res +str(val)
        else:
          final_res =final_res+ "+"+str(val)
      count+=1
    else:
      final_res =final_res+ "+"+str(val)
      count+=1
  print(final_res)
   

if __name__ == '__main__':
  main()

Question is not given. I just created one question where we can input number and print polynomial.

Sample Input Output

4

0 5

1 0

2 10

3 6

6x^3 + 10x^2 + 5


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