Heim >Backend-Entwicklung >Python-Tutorial >python实现计算倒数的方法

python实现计算倒数的方法

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-10 15:09:314478Durchsuche

本文实例讲述了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程序设计有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn