Skip to content

Instantly share code, notes, and snippets.

@ninlith
Last active February 8, 2021 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ninlith/a75824f243593905e02d8e4d77a644d8 to your computer and use it in GitHub Desktop.
Save ninlith/a75824f243593905e02d8e4d77a644d8 to your computer and use it in GitHub Desktop.
External calculation for Gedit
#!/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