Last active
February 8, 2021 06:48
-
-
Save ninlith/a75824f243593905e02d8e4d77a644d8 to your computer and use it in GitHub Desktop.
External calculation for Gedit
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
#!/usr/bin/env python3 | |
# [Gedit Tool] | |
# Name=Calculate | |
# Input=selection | |
# Output=replace-selection | |
# Applicability=always | |
# Save-files=nothing | |
# Shortcut=<Primary><Alt>c | |
# Languages= | |
import re | |
import sys | |
import sympy | |
input_string = sys.stdin.read() | |
output = [input_string] | |
try: | |
evaluation = sympy.sympify(input_string, rational=True, evaluate=True) | |
numerical_evaluation = evaluation.evalf(15) | |
except sympy.SympifyError: | |
output.extend(["=", "?"]) | |
else: | |
e = str(evaluation) | |
if evaluation.is_integer or re.sub(r"\s+", "", input_string) != e: | |
output.extend(["=", e]) | |
if evaluation.is_zero and e != "0": | |
output.extend(["=", "0"]) | |
n = re.sub(r"\.0+$", "", re.sub(r"(\d+\.\d+?)0+($|e.*)", r"\1\2", | |
str(numerical_evaluation))) | |
if not evaluation.is_integer and n not in output: | |
if sympy.sympify(f"{e}-{n}", rational=True, evaluate=True).is_zero: | |
output.extend(["=", n]) | |
else: | |
output.extend(["≈", n]) | |
finally: | |
print(" ".join(output), end="") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment