-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.py
More file actions
executable file
·96 lines (82 loc) · 2.79 KB
/
calculator.py
File metadata and controls
executable file
·96 lines (82 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import math
class Calc():
def __init__(self):
'''Same as ac()--see below'''
self.ac()
def __str__(self):
'''The string representation of Calc() is the list of calculations.'''
return self.showcalc()
def __add__(self, other):
'''Calc1 + Calc2 combines the totals and the lists of caclulations.'''
self.calculations.extend(other.calculations)
self.total = other.total
return self
def notecalc(self, op, op1, op2):
'''Add latest calculation to the running list.'''
calc = ''
if op == 'log':
op += op2
else:
calc = str(op2) + " "
calc += str(op) + ' ' + str(op1) + ' = ' + str(self.total)
self.calculations.append(calc)
def add(self, op1, op2 = None):
'''Add two numbers. If only one number supplied, add to running total.'''
if op2 == None:
op2 = self.total
self.total = op1 + op2
self.notecalc('+', op1, op2)
return self.total
def sub(self, op1, op2 = None):
'''Subtract two numbers. If only one number supplied, subtract from
running total.
'''
if op2 == None:
op2 = op1
op1 = self.total
self.total = op1 - op2
self.notecalc('-', op1, op2)
return self.total
def mult(self, op1, op2 = None):
'''Multiply two numbers. If only one number supplied, multiply
running total.
'''
if op2 == None:
op2 = self.total
self.total = op1 * op2
self.notecalc('*', op1, op2)
return self.total
def pow(self, op1, op2 = None):
'''Raise a number to a power. If no number supplied, raise the
running total to the power.
'''
if op2 == None:
op2 = op1
op1 = self.total
self.total = math.pow(op1, op2)
self.notecalc('**', op1, op2)
return self.total
def dolog(self, logtype, op1 = None):
'''Take log/log10 of a number. If no number supplied, take log
of the running total.
'''
if op1 == None:
op1 = self.total
if logtype == 'log':
self.total = math.log(op1)
self.notecalc('log', op1, '')
else:
self.total = math.log10(op1)
self.notecalc('log', op1, '10')
return self.total
def log(self, op1 = None):
return self.dolog('log', op1)
def log10(self, op1 = None):
return self.dolog('log10', op1)
def showcalc(self):
'''Show current list of calculations.'''
return '\n'.join(self.calculations)
def ac(self):
'''All clear--set total to 0 and erase the list of calculations.'''
self.calculations = []
self.total = 0.0