"""Advanced_Calculator_-_-_"""
import time as t
from functools import reduce
def timing() -> str:
hour = int(t.strftime("%H"))
if 6 <= hour < 12:
return "Morning"
elif 12 <= hour < 17:
return "Afternoon"
elif 17 <= hour < 20:
return "Evening"
else:
return "Night"
class Calculator:
"MAin CAlCulaTOr"
version: str = "1.8.8"
symbols = {1: "*", 2: "@", 3: "#", 4: "$", 5: "%", 6: "^", 7: "&",
8: "-", 9: ".", 10: "=", 11: "+", 12: ":", 13: "!", 14: "`"}
def __init__(self, name="User") -> None:
self.name = name
def add(self, *args):
"""some nums"""
return sum(args)
def mul(self, *args):
"""some nums"""
return reduce((lambda x, y: x*y), args)
def div(self, *args):
"""Performs division, ensuring no division by zero."""
try:
return reduce((lambda x, y: x / y), args)
except ZeroDivisionError:
return "Error: Division by zero is not allowed."
def sub(self, *args):
return reduce((lambda x, y: x-y), args)
def exp(self, n, power):
"""n for the number and power for exponent"""
return float(n**power)
def tetrate(self, n: int, tetration: int):
"""n for the number and tetration for repeated exponenting"""
if tetration < 0:
raise ValueError("Tetration must be non-negative.")
if tetration == 0:
return 1
if tetration == 1:
return n
return n ** self.tetrate(n, tetration - 1)
def pentate(self, n , pentation):
"""n for the number and pentation for repeated tetration"""
if pentation < 0:
raise ValueError("Tetration must be non-negative.")
if pentation == 0:
return 1
if pentation == 1:
return n
return self.tetrate(n,self.pentate(n,pentation-1))
def hexate(self,n, hexation):
"""Pythonic implemetation of the 6 level hyperoperation, namely hexation. PLEASE!!! USE WITH CAUTION AT YOUR OWN RISK"""
def tet( n: int, tetration: int):
"""n for the number and tetration for repeated exponenting"""
if tetration < 0:
raise ValueError("Tetration must be non-negative.")
if tetration == 0:
return 1
if tetration == 1:
return n
ans = n
for _ in range(1, tetration):
ans = n**ans
return ans
def pen(n, pentation):
if pentation < 0:
raise ValueError("Pentation must be non-negative.")
if pentation == 0:
return 1
if pentation == 1:
return n
ans = n
for _ in range(1, pentation):
ans = tet(n, ans)
return ans
if hexation < 0:
raise ValueError("Hexation must be non-negative.")
if hexation == 0:
return 1
if hexation == 1:
return n
ans = n
for _ in range(1, hexation):
ans = pen(n, ans)
return ans
def getpi(self, dplaces: int = 3):
"Gives a π rounded to dplaces"
from math import pi
return round(pi, dplaces) if dplaces <= 15 else pi
def square(self, n):
"squares a number."
return n**2
def cube(self, n):
"cubes a number."
return n**3
def squareroot(self, n, dplaces=2):
"square roots a number."
return round(n**(1/2), dplaces)
def cuberoot(self, n, dplaces=2):
"cube roots a number."
return round(n**(1/3), dplaces)
def remainder(self, n, divisor):
"Returns remainder of n/divisor"
return n % divisor
def factorial(self, n: int or float):
"returns n!"
n = int(n)
result = 1
if n == 0 or n == 1:
return 1
for i in range(1, n+1):
result = result*i
return result
def clearmemory(self):
with open("vars.txt", "w")as f:
f.write("")
def show_all_variables(self):
with open('vars.txt', "r") as f:
return (f.read())
def get_variable(self, name: str, onlyreturnvalue: bool = True, clearmemoryafteroutput=False):
with open('vars.txt', "r") as f:
varslist = f.readlines()
for var in varslist:
if name in var:
if clearmemoryafteroutput:
self.clearmemory()
if onlyreturnvalue:
return int(var[len(name)+1:len(var)-1])
return var
def storeinROM(self, name, value: int):
"Stores your variable in memory(ROM)."
with open("vars.txt", "a") as f:
f.write(f'{name}={value}\n')
def randominteger(self, start, end):
"Returns a random integer from start to end."
from random import randint
start = round(start)
end = round(end)
return randint(start, end)
def construct_right_angled_triangle(self, height, symbol=1):
height = int(height)
for i in range(0, height):
for _ in range(0, i+1):
print(Calculator.symbols[symbol], end=" ")
print("")
return ""
def construct_square(self, length, symbol=1):
length = int(length)
for i in range(0, length):
for _ in range(length):
print(Calculator.symbols[symbol], end=" ")
print("")
return ""
def construct_rectangle(self, height, length, symbol=1):
height = int(height)
length = int(length)
for i in range(height):
for _ in range(length):
print(Calculator.symbols[symbol], end=" ")
print("")
return ""
def average(self, *numbers):
"Just average."
return sum(numbers)/len(numbers)
def shuffle(self, lst):
from random import shuffle
shuffle(lst)
return lst
def shuffle2(self, lstinstr: str, integerit=True):
from random import shuffle
lstinstr = lstinstr[1:-1]
lst = lstinstr.split(",")
if integerit:
items = [int(item.strip()) for item in lst]
shuffle(items)
return items
shuffle(lst)
return lst
def construct_pyramid_triangle(self, height, symbol=1):
"""Constructs pyramid triangle"""
# A little complex code
# for i in range(1,height+1):
# print(" "*(height-i)+"*"*(2*i-1))
height = int(height)
for i in range(0, height):
for _ in range(height-i):
print(" ", end=" ")
for _ in range(0, i+1):
print((Calculator.symbols[symbol]), end=" ")
for _ in range((i)):
print((Calculator.symbols[symbol]), end=" ")
print("")
return ""
def formula_mapper(self, *args):
"""Maps integers into formulas"""
from FormulaMapper import formulamapper
lst = [*args]
del lst
formulamapper()
return ""
def percentage(self, obtained_number: float or int, total: int or float):
"""Percentage of obtained_number/total"""
result = (100*(obtained_number/total))
return result
def percentage2(self, str_of_numbers: str, ndigits="3", *others):
"""Made for the run function."""
others = []
del others
obtained_number = float(str_of_numbers.split('/')[0])
total = float(str_of_numbers.split('/')[1])
return str(round(self.percentage(obtained_number, total), int(ndigits)))+"%"
def satisfying_number(self, number=100):
"""A random, mAssive, huge, enormous, big, giant number.\nAnd the number is integer :)"""
from random import randint, choice
number = int(number)
note = "Larger numbers may take some time..."
if number > 80:
print(note)
for _ in range(number+randint(0, number)):
if number < 0:
print("-",end = "")
print((str(randint(number, number*2))*int(str(randint(number+number, (number*number)+1))[0]))
+ str(self.factorial(randint(0, number)))+(str(randint(number, number*2))*int(str(randint(number+number, (number*number)+1))[0]))+str(randint(0,number*randint(1,9)))
, end="")
if number < 80:
t.sleep(choice([0.1, 0.14, 0.2, 0.1, 0.1, 0.04,
0.02, 1, 0.2, 0.5, 0.4, 0.3, 0.1, 0.1, 0.12]))
elif number> 80:
t.sleep(choice([0.09,0.9,0.0894,0.9,0.3,0.2,0.1,0.002,1,0.4,0.02,2]))
elif number > 9999:
t.sleep(0.002)
elif number > 999999:
t.sleep(0.0002)
else:
t.sleep(choice([0.1, 0.03, 0.05, 0.12, 0.09]))
print("")
return ""
def SumOfnNaturalNumbers(self, n):
"""sum({1,...,n})"""
n = int(n)
if n < 1:
raise ValueError("n should be a natural number.")
return n*(n+1) // 2
def grade_calculator(self, obtained_marks, total_marks):
"""An exam-inspired grade system."""
percentage = self.percentage(float(obtained_marks), float(total_marks))
if percentage >= 90:
return "Ex Grade"
elif percentage >= 80 and percentage < 90:
return "A Grade"
elif percentage >= 70 and percentage < 80:
return "B Grade"
elif percentage >= 60 and percentage < 70:
return "C Grade"
elif percentage >= 50 and percentage < 60:
return "D Grade"
return "F Grade"
def superfactorial(self, n: int or float) -> int or float:
"""returns sf(n) if n is a positive integer"""
ans = self.factorial(n)
for num in range(n - 1,1, -1):
ans *= self.factorial(num)
return ans
def hyperfactorial(self, n) -> int:
"""returns H(n) if n is a positive integer"""
n = int(n)
if n <0:
raise ValueError("Function defined for positive ints only...")
ans = 1
lst = [i**i for i in range(1,n+1)]
for n in lst:
ans *= n
return ans
def Subset_Generator(self,*args):
from SubsetGenerator import SubsetGenerator
del args
SubsetGenerator()
return ""
def solve_linear_equation(self, *args):
from linear_equation_solver import main_function
del args
solution = main_function()
return solution
def count_digits(self, number: str or int):
return len(str(number))
def __str__(self) -> str:
return "Calculator Belongs To "+self.name
def run(self):
"""Main method for user interaction."""
print(f"Good {timing()}, {self.name}.\n")
print("Welcome To Our Advanced Python Calculator.\n")
commands = {1: self.add, 2: self.sub, 3: self.mul, 4: self.div, 5: self.exp, 6: self.tetrate, 7: self.square,
8: self.cube, 9: self.squareroot, 10: self.cuberoot, 11: self.remainder, 12: self.getpi, 13: self.randominteger, 14: self.construct_right_angled_triangle, 15: self.construct_square, 16: self.construct_rectangle, 17: self.average,
18: self.shuffle2, 19: self.construct_pyramid_triangle, 20: self.formula_mapper, 21: self.percentage2,22: self.factorial, 23: self.satisfying_number, 24: self.SumOfnNaturalNumbers, 25: self.pentate,
26: self.grade_calculator, 27: self.count_digits,28: self.superfactorial, 29: self.hyperfactorial, 30: self.hexate,
31: self.Subset_Generator, 32: self.solve_linear_equation}
info = {
1: "addition",
2: "subtraction",
3: "multiplying",
4: "dividing",
5: "exponentiation",
6: "tetration, results may be overwhelming for the CPU to control so use with caution.",
7: "squaring",
8: "cubing",
9: "squareroot",
10: "cuberoot",
11: "remainder",
12: "pi",
13: "RAndom Integer between a and b.",
14: "constructing right angled triangle",
15: "constructing square",
16: "constructing rectangle",
17: "average",
18: "shuffle list",
19: "constructing pyramid triangle",
20: "Formula Mapper Program, enter any number to continue",
21: "Percentage",
22: "Factorial(x!)",
23: "Satisfying Number; use with caution!",
24: "Sum(n Natural numbers)",
25: "Pentation, results may be overly overwhelming for the CPU to control so use with caution.",
26: "Grade for obtained_marks/total_marks",
27: "Count The digits/elements",
28: "superfactorial, use with caution...",
29: "hyperfactorial, use with caution...",
30: "hexate, use with extreme level of caution, only for testing purposes. The inputs should peak only to hexate(2,2)",
31: "Generating Subsets, enter any number to continue",
32: "Solve any equation in the form ax + b = c"}
menu = """Commands:
1 for addition; 2 for subtraction;
3 for multiplying; 4 for dividing;
5 for exponentiation; 6 for tetration;
7 for squaring; 8 for cubing;
9 for squareroot; 10 for cuberoot;
11 for remainder; 12 for pi;
13 for randominteger; 14 for constructing right angled triangle;
15 for constructing square; 16 for constructing rectangle;
17 for average; 18 for shuffle list;
19 for constructing a triangle; 20 for Formula Mapper;
21 for percentage; 22 for Factorial;
23 for a weird number; 24 for sum of first n natural numbers;
25 for a Pentation; 26 for Calculating your grade;
27 for counting digits; 28 for Superfactorial;
29 for hyperfactorial; 30 for hexate;
31 for Generating Subsets; 32 for solution to linear equations"""
while True:
try:
print(menu)
command = (
input("\nEnter your desired one command or q to exit: ")).lower()
if command == "q":
break
print(f"Using Command No.{int(command)}", info[int(command)])
arguments = (
input(f"Enter arguments for command No.{int(command)}: ")).split(" ")
time = t.time()
if int(command) == 18:
if "".join(arguments) == "[]":
print([])
else:
print(commands[int(command)](
*arguments), end=f"\nComputed in {t.time()-time} seconds.\n")
elif int(command) == 21:
print(commands[int(command)](
*arguments), end=f"\nComputed in {t.time()-time} seconds.\n")
elif int(command) == 26:
print(commands[int(command)](float(("".join(arguments)).split("/")[0]), float(
("".join(arguments)).split("/")[1])), end=f"\nComputed in {t.time()-time} seconds.\n")
elif int(command) == 27:
print(commands[int(command)]("".join(arguments)),
end=f"\nComputed in {t.time()-time} seconds.\n")
elif int(command) == 28:
print(commands[int(command)](
int(arguments[0])), end=f"\nComputed in {t.time()-time} seconds.\n")
elif int(command) == 30:
print(commands[int(command)](
int(arguments[0]), int(arguments[1])), end=f"\nComputed in {t.time()-time} seconds.\n")
elif int(command) == 32:
commands[int(command)]()
print(f"Computed in {t.time()-time} seconds.")
else:
arguments = tuple(map(float, arguments))
print(commands[int(command)](
*arguments), end=f"\nComputed in {t.time()-time} seconds.\n")
if input("").lower() == "q":
break
except Exception as ex:
print("Error occured...", ex)
print(f"\nHave a Good {timing()}, {self.name}.")
print("Thanks For Using...")
if __name__ == "__main__":
Calculator("--YOUR NAME--").run()
This code receives frequent updates so it may not look like when it was published for the first time, so track the version.
ReplyDeleteThe overall code is good and nicely organized into seperate methods but i think you should improve the store in rom function because it uses very basic file io. Any ways this calculator is a gift for mathematicans, statistics person and coders due to diverse features that a typical calculator doesnt offer
ReplyDeleteGlad you liked it and thanks for the observation in the storeinrom function, I'll try to improve it in the next update.
DeleteNice, ideal for most python and mathematical users!
ReplyDelete9/10
Thanks for the reveiw! Appreciate it.
DeletePerfect code perfect keep it up my lad
ReplyDeleteDamn, Nice! Hashir Brand!
ReplyDeleteThanks bro, i plan to extend the scope of this blog in the future with programs that might be useful in the real world, any suggestions and advice is appreciated.
DeleteGood bro khunays here perfect organised code which others can understand easily due to your organization skills exceptional keep it up lad
ReplyDeleteThanks Bro. Appreciate the review! I have plans to enhance the functionality of the calculator in the future. Stay tuned!
DeleteGood bro khunays here perfect organised code which others can understand easily due to your organization skills exceptional keep it up lad
ReplyDelete