Advertisement
albertoanggi

Polynomial Multiply

Sep 26th, 2018
453
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # Created by Enji
  3.  
  4. def polymul(coefficientsF, coefficientsG):
  5.     m = len(coefficientsF)
  6.     n = len(coefficientsG)
  7.  
  8.     prod = []
  9.  
  10.     for i in range(m+n-1):
  11.         prod.append(0)
  12.  
  13.     for i in range(m):
  14.         for j in range(n):
  15.             prod[i+j] += coefficientsF[i] * coefficientsG[j]
  16.  
  17.     return prod
  18.  
  19. def convert2String(prod):
  20.     p = len(prod)
  21.  
  22.     for i in range(p-1, -1, -1):
  23.         print(prod[-i+(p-1)], end="")
  24.         if(i != -1):
  25.             print("x^%d "%(i), end="")
  26.             if(prod[-i+(p-1)] > 0 or prod[-i+(p-1)] < 0):
  27.                 if(prod[-i+(p)] > 0):
  28.                     print("+ ", end="")
  29.  
  30. def main():
  31.     degreeF = int(input("Masukkan derajat f: "))
  32.     coefficientsF = []
  33.  
  34.     for i in range(degreeF, -1, -1):
  35.         coefficientF = int(input("Masukkan koefesien x^%d: "%(i)))
  36.         coefficientsF.append(coefficientF)
  37.  
  38.     degreeG = int(input("Masukkan derajat g: "))
  39.     coefficientsG = []
  40.  
  41.     for i in range(degreeG, -1, -1):
  42.         coefficientG = int(input("Masukkan koefesien x^%d: "%(i)))
  43.         coefficientsG.append(coefficientG)
  44.  
  45.     print("Hasil perkalian polinom:")
  46.     result = polymul(coefficientsF, coefficientsG)
  47.     convert2String(result)
  48.  
  49. if __name__ == '__main__':
  50.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement