I made another version of this calculator on a different forum, but now that I've learned about lexing and parsing, I've decided to add some more elements to it that make it a bit more efficient.
Todo:
push from definitions to module
Features:
- CLI (duh)
- In-program help function
- Exception catching
- Fibonacci reference
- Formatted times tables
- Input history (unintentional but cool nonetheless)
- Exit function
Available operations:
+ addition
- subtraction
/ division
* multiplication
** exponents
./ floor division w/ remainder
Source:
from sys import exit as e
import operator as op
def rem(a,b):
return "v: %s\n r: %s" % (a // b,a % b)
ops={'+': op.add,'-': op.sub,'*': op.mul,'/': op.div,'**': op.pow,'%': op.mod,'./': rem}
def fib_to(n):
fibs = [1, 1]
for i in range(2, int(n)+1):
fibs.append(fibs[-1] + fibs[-2])
print", ".join(map(str, fibs))
def tables():
for row in range(1,13):
s = ''
for col in range(1,13):
s += '{:3} '.format(row * col)
print(s)
def interface():
m = raw_input("} ").split()
try:
if m == ["/?"]: print "/? Help\n/e Exit\n/f <n> Fibonacci series to <n>\n/x Multiplication tables"
elif m == ["/e"]: e()
elif "/f" in m: fib_to(m[1])
elif m == ["/x"]: tables()
else: print">>",str(ops[m[1]](float(m[0]),float(m[2])))
except IndexError:
print "Unknown command '%s'" % str(m[0])
except KeyError:
print "Invalid syntax: "+" ".join(m)
interface()
print "Nevermore's CLI Calculator:\n/? for help"
interface()
Commands (other than equations):
/? Help
/e Exit
/f <n> Fibonacci series to <n>
/x Multiplication tables