Advertisement
agnishom

Polynomial Derivatives

Oct 11th, 2014
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. def polyparse(s,x):
  2.         c = []
  3.         current = ['','0','coefficient']
  4.         for i in s:
  5.             if i in ['0','1','2','3','4','5','6','7','8','9','.']:
  6.                 if current[2] == 'coefficient':
  7.                     current[0] += i
  8.                 elif current[2] == 'exponent':
  9.                     current[1] += i
  10.             elif i == x:
  11.                 if current[0] == '':
  12.                     current[0]=1
  13.                 elif current[0] == '-':
  14.                     current[0] = -1
  15.                 current[2] = 'exponent'
  16.                 current[1] = '1'
  17.             elif i == '^':
  18.                 current[1] = '0'
  19.             elif i == '+':
  20.                 c.append([float(current[0]), int(current[1])])
  21.                 current = ['','0','coefficient']
  22.             elif i == '-':
  23.                 c.append([float(current[0]), int(current[1])])
  24.                 current = ['-','0','coefficient']
  25.         c.append([float(current[0]), int(current[1])])
  26.         return c
  27. def derivative(poly):
  28.     for i in poly:
  29.         i[0] *= i[1]
  30.         i[1] = i[1]-1
  31.     return poly
  32. def polyform(poly,x):
  33.     p = ''
  34.     for i in poly:
  35.     if i[0] == 0:
  36.         continue
  37.         if i[0] >= 0:
  38.                 p += '+'
  39.         if i[0] == int(i[0]):
  40.             i[0] = int(i[0])
  41.     if i[0] == 1:
  42.         i[0] = ''
  43.         if i[1]==1:
  44.             p += str(i[0]) + x
  45.         elif i[1]== 0:
  46.             p += str(i[0])
  47.         else:
  48.             p += str(i[0]) +x +'^' +str(i[1])
  49.     p = p[1:]
  50.     return p
  51.  
  52. while True:
  53.     x = raw_input('Enter your variable: ')[0]
  54.     print 'Derivative: ' + polyform(derivative(polyparse(raw_input('Enter your polynomial: '),x)),x),'\n'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement