-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefix_calc.py
92 lines (69 loc) · 2.08 KB
/
prefix_calc.py
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
#!/usr/bin/env python3
"""Prefix Calculator.
This program calculates the result of a prefix expression.
Example of usage:
python prefix_calc.py sum 1 2
3
python prefix_calc.py sub 1 2
-1
python prefix_calc.py mul 2 3
6
python prefix_calc.py div 4 2
2
"""
__version__ = '0.1.0'
__author__ = 'Vicente Marçal'
__license__ = 'GPLv3+'
import os
import sys
from datetime import datetime
from pathlib import Path
def sum_(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
if b == 0:
print('Division by zero is not allowed.')
sys.exit(1)
return a / b
arguments = sys.argv[1:]
if len(arguments) != 3:
print('Invalid number of arguments.\nExample of usage:\n$ python prefix_calc.py sum 1 2')
sys.exit(1)
if not arguments:
operation = input('Enter the operation: ')
operand1 = input('Enter the first operand: ')
operand2 = input('Enter the second operand: ')
arguments = [operation, operand1, operand2]
operation, *nums = arguments
valid_nums = []
operations = {'sum': sum_, 'sub': sub, 'mul': mul, 'div': div}
if operation not in operations:
print(
f'"{operation}" is not recognized as a valid Operation.'
'\nAvailable operations are: `sum`, `sub`, `mul`, and `div`.'
'\nExample of usage: \n$ python prefix_calc.py sum 1 2'
)
sys.exit(1)
for num in nums:
if not num.replace('.', '').isdigit():
print(f'"{num}" is not a valid number.')
sys.exit(1)
if '.' in num:
num = float(num)
else:
num = int(num)
valid_nums.append(num)
operand1, operand2 = valid_nums
result = operations[operation](operand1, operand2)
# Log the operation
file_path = Path.cwd() / Path('prefix_calc.log')
user = os.getenv('USER', 'anonymous')
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open(file_path, 'a') as file:
file.write(f'{timestamp} - {user.upper()} - {operation} {operand1} {operand2} = {result}\n')
# Show the result to the user
print(f'The result of {operation} {operand1} {operand2} is {result}')