python实现计算倒数的方法

yipeiwu_com6年前Python基础

本文实例讲述了python实现计算倒数的方法。分享给大家供大家参考。具体如下:

class Expr: 
 def __add__(self, other): 
  return Plus(self, other) 
 def __mul__(self, other): 
  return Times(self, other) 
class Int(Expr): 
 def __init__(self, n): 
  self.n = n 
 def d(self, v): 
  return Int(0) 
 def __str__(self): 
  return `self.n` 
class Var(Expr): 
 def __init__(self, var): 
  self.var = var 
 def d(self, v): 
  return Int(self.var == v and 1 or 0) 
 def __str__(self): 
  return self.var 
class Plus(Expr): 
 def __init__(self, a, b): 
  self.e1 = a 
  self.e2 = b 
 def d(self, v): 
  return Plus(self.e1.d(v), self.e2.d(v)) 
 def __str__(self): 
  return "(%s + %s)" % (self.e1, self.e2) 
class Times(Expr): 
 def __init__(self, a, b): 
  self.e1 = a 
  self.e2 = b 
 def d(self, v): 
  return Plus(Times(self.e1, self.e2.d(v)), Times(self.e1.d(v), self.e2))
 def __str__(self): 
  return "(%s * %s)" % (self.e1, self.e2) 
if __name__ == "__main__": 
 x = Var("x") 
 a = Var("a") 
 b = Var("b") 
 c = Var("c") 
 e = a * x * x + b * x + c 
 print "d(%s, x) = %s" % (e, e.d("x")) 

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python重新引入被覆盖的自带function

幸运的是, 这一问题还是很容易解决的, 我们只需要使用__builtins__: from __builtins__ import int as py_int 这样一来我们又可以...

Python计算程序运行时间的方法

本文实例讲述了Python计算程序运行时间的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下: import time def start_sleep():  ...

高效测试用例组织算法pairwise之Python实现方法

高效测试用例组织算法pairwise之Python实现方法

开篇: 测试过程中,对于多参数参数多值的情况进行测试用例组织,之前一直使用【正交分析法】进行用例组织,说白了就是把每个参数的所有值分别和其他参数的值做一个全量组合,用Python脚本实现...

python向字符串中添加元素的实例方法

python向字符串中添加元素的实例方法

Python中的字符串对象是不能更改的,也即直接修改字符串中的某一位或几位字符是实现不了的,即python中字符串对象不可更改,但字符串对象的引用可更改,可重新指向新的字符串对象。 +...

详解Python if-elif-else知识点

有的时候,一个 if … else … 还不够用。比如,根据年龄的划分: 条件1:18岁或以上:adult 条件2:6岁或以上:teenager 条件3:6岁以下:kid Pytho...