from __future__ import division

class Dual(object):
	"""
	Represents a number of the form a + b * e, where e != 0
	but e^2 = 0.
	"""
	def __init__(self, a=0.0, b=0.0):
		self.a = a
		self.b = b

	def __add__(self, other):
		if isinstance(other, Dual):
			return Dual(self.a + other.a, self.b + other.b)
		else:
			return Dual(self.a + other, self.b)

	def __radd__(self, other):
		if isinstance(other, Dual):
			return Dual(self.a + other.a, self.b + other.b)
		else:
			return Dual(self.a + other, self.b)

	def __sub__(self, other):
		if isinstance(other, Dual):
			return Dual(self.a - other.a, self.b - other.b)
		else:
			return Dual(self.a - other, self.b)

	def __rsub__(self, other):
		if isinstance(other, Dual):
			return Dual(other.a - self.a, other.b - self.b)
		else:
			return Dual(other - self.a, self.b)

	def __mul__(self, other):
		if isinstance(other, Dual):
			return Dual(self.a * other.a, self.b * other.a + other.b * self.a)
		else:
			return Dual(self.a * other, self.b * other)

	def __rmul__(self, other):
		if isinstance(other, Dual):
			return Dual(self.a * other.a, self.b * other.a + other.b * self.a)
		else:
			return Dual(self.a * other, self.b * other)

	def __truediv__(self, other):
		if isinstance(other, Dual):
			c2 = other.a * other.a
			a = self.a * other.a / c2
			b = (self.b * other.a - self.a * other.b) / c2
			return Dual(a, b)
		else:
			return Dual(self.a / other, self.b / other)

	def __rtruediv__(self, other):
		return Dual(other / self.a, other / self.b)

	def __str__(self):
		if self.b == 0:
			return str(self.a)
		elif self.b > 0:
			return '{} + {}e'.format(self.a, self.b)
		elif self.b < 0:
			return '{} - {}e'.format(self.a, -self.b)

def derive(f, x):
	"""
	Returns the derivative of `f` at position `x`.
	"""
	return f(Dual(x, 1)).b

if __name__ == '__main__':
	f = lambda x: x * 5 + 2 * (x * x + 3)
	print(derive(f, 3))
@@ -377,98 +377,8 @@
 r):%0A
-%09%09if isinstance(other, Dual):%0A%09%09%09return Dual(self.a + other.a, self.b + other.b)%0A%09%09else:%0A%09
 %09%09re
@@ -403,32 +403,32 @@
  other, self.b)%0A
+
 %0A%09def __sub__(se
@@ -600,98 +600,8 @@
 r):%0A
-%09%09if isinstance(other, Dual):%0A%09%09%09return Dual(other.a - self.a, other.b - self.b)%0A%09%09else:%0A%09
 %09%09re
@@ -626,32 +626,32 @@
 self.a, self.b)%0A
+
 %0A%09def __mul__(se
@@ -850,117 +850,8 @@
 r):%0A
-%09%09if isinstance(other, Dual):%0A%09%09%09return Dual(self.a * other.a, self.b * other.a + other.b * self.a)%0A%09%09else:%0A%09
 %09%09re

Remove unnecessary conditionals