|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码:- class Monomial:
- def __init__(self, term=1, times=1, have_space = True):
- self.term = term
- self.times = times
- self.have_space = have_space
- def derivate(self):
- return Monomial(self.term*self.times, self.times-1)
- def __repr__(self):
- if self.times == 0:
- return str(self.term)
- else:
- return str(self.term) + \
- (' ' if self.have_space else '') + \
- '*' + \
- (' ' if self.have_space else '') + \
- 'x' + \
- (' ' if self.have_space else '') + \
- '^' + \
- (' ' if self.have_space else '') + \
- str(self.times)
- def __str__(self):
- if self.times == 0:
- return str(self.term)
- else:
- return str(self.term) + \
- (' ' if self.have_space else '') + \
- '*' + \
- (' ' if self.have_space else '') + \
- 'x' + \
- (' ' if self.have_space else '') + \
- '^' + \
- (' ' if self.have_space else '') + \
- str(self.times)
- class Polynomial:
- def __init__(self, formula, have_space = True):
- self.have_space = have_space
- self.formula = formula.split('+')
- self.formula = [i.replace(' ', '') for i in self.formula]
- for i in range(len(self.formula)):
- temp = self.formula[i]
- if not(len(temp) == 5 and temp[2] == 'x' and temp[3] == '^' and temp[1] == '*'):
- raise TypeError
- self.formula[i] = Monomial(int(temp[0]), int(temp[4]), self.have_space)
- def derivate(self):
- import copy
- temp = copy.copy(self)
- #print(temp)
- del copy
- for i in range(len(temp.formula)):
- #print(temp.formula[i], type(temp.formula[i]))
- temp.formula[i] = temp.formula[i].derivate()
- return temp
- def __str__(self):
- temp = ''
- for i in range(len(self.formula)):
- temp += str(self.formula[i])
- return temp
- def __repr__(self):
- temp = ''
- for i in range(len(self.formula)):
- temp += repr(self.formula[i])
- return temp
复制代码
演示:- >>> x = Polynomial('1*x^5+1*x^4')
- >>> x
- 1 * x ^ 5 + 1 * x ^ 4
- >>> x.derivate()
- 5 * x ^ 4 + 4 * x ^ 3
- >>> y = Polynomial('3*x^5', False)
- >>> y
- 3*x^5
- >>> y.derivate()
- 15 * x ^ 4
- >>>
复制代码
缺点:
1. 输入的多项式只能是包含x的式子,并且必须是1 * x ^ 5这种形式(不能写成x^5)
2. 不能输入ln sin cos tan 等函数
3. 不能输入 (x+1)^2 这种式子
总的来说,就是特别简单,限制很多 |
|