Created
February 1, 2017 03:02
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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