Skip to content

Instantly share code, notes, and snippets.

@shamikalashawn
Created February 1, 2017 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamikalashawn/24ad0a7d21994deb5508653b2ecc27de to your computer and use it in GitHub Desktop.
Save shamikalashawn/24ad0a7d21994deb5508653b2ecc27de to your computer and use it in GitHub Desktop.
Using OOP, a simple calculator is created which keeps track of previous operations.
class Calculator(object):
def __init__(self):
self.cache = {}
def add(self, x, y):
if not self.cache.has_key('add'):
self.cache.setdefault('add', [])
for previous_x, previous_y, res in self.cache['add']:
if previous_x == x and previous_y == y:
return res
else:
self.cache['add'].append((x, y, x+y))
return x+y
def subtract(self, x, y):
if not self.cache.has_key('subtract'):
self.cache.setdefault('subtract', [])
for previous_x, previous_y, res in self.cache['subtract']:
if previous_x == x and previous_y == y:
return res
else:
self.cache['subtract'].append((x, y, x-y))
return x-y
def multiply (self, x, y):
if not self.cache.has_key('multiply'):
self.cache.setdefault('multiply', [])
for previous_x, previous_y, res in self.cache['multiply']:
if previous_x == x and previous_y == y:
return res
else:
self.cache['multiply'].append((x, y, x*y))
return x*y
def divide (self, x, y):
if not self.cache.has_key('divide'):
self.cache.setdefault('divide', [])
for previous_x, previous_y, res in self.cache['divide']:
if previous_x == x and previous_y == y:
return res
else:
self.cache['divide'].append((x, y, x/y))
return x/y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment