Expression interpreter written in Python

Overview

Calc Interpreter

Python Package other branches Python Version Python Implementation

An interpreter modeled after a calculator implemented in Python 3. The program currently only supports basic mathematical expressions. The package uses Reverse Polish Notation also known as postfix expression internally to easily represent mathematical expressions. This is powerful as it allows operators to be organised in such a way that precedence is absolute meaning an operator that is encountered first will always be executed first.

However, it is obvious that postfix is not normal or rather not usually taught in schools and thus infix expression is still the way for the user to write expressions. The interpreter uses a modified Shunting-Yard algorithm to produce Abstract Syntax Trees. Evaluation of ASTs is trivial, and they are flexible making it easy to extend the grammar and functionality later on.

Installation

The package is available in PyPI and can be installed via pip.

pip install expr-calc
#or
python3 -m pip install expr-calc

Usage

The best way to run the program currently is to execute the REPL and can be done in a python file or through your terminal.

Assuming your present working directory is inside the cloned repo, you can run the following command without the comment.

# inside /clone_path/expr_calc/
python -m expr_calc

The test suite can also be ran with pytest when inside the cloned repo

pytest  # or python -m pytest

Example

Once inside the REPL, you can start evaluating expressions. Currently, only operators listed in Features are supported.

calc> 1 + 1
2

calc> 345--500
845

calc> -2
-2

calc> 123 ^ 4
228886641

calc> 32 / 1.5
21.33333333333333333333333333

calc> 123 * 456
56088

calc> 34 % 5
4

calc> 4 ^ 1/2
0.5

calc> 4 ^ (1/2)
2.0

Features

  • Infix expressions
  • Basic operators such as +, -, *, /, %, ^
  • Tokens created from an expression can also be fetched to be manipulated if one wanted to do so
  • Expressions are transformed into m-ary Tree objects connected to each other

Features I want to add later

  • variable support
  • custom functions
  • more mathematical functions such as sin, cos, tan, etc
  • and possibly a simple symbolic computation support

Resources

You might also like...
Structural basis for solubility in protein expression systems

Structural basis for solubility in protein expression systems Large-scale protein production for biotechnology and biopharmaceutical applications rely

PyDy, short for Python Dynamics, is a tool kit written in the Python
PyDy, short for Python Dynamics, is a tool kit written in the Python

PyDy, short for Python Dynamics, is a tool kit written in the Python programming language that utilizes an array of scientific programs to enable the study of multibody dynamics. The goal is to have a modular framework and eventually a physics abstraction layer which utilizes a variety of backends that can provide the user with their desired workflow

Simple, high-school-leveled sequence library written in Python / 간단한 고등학교 수준 수열 라이브러리 (Python)
Msgpack serialization/deserialization library for Python, written in Rust using PyO3 and rust-msgpack. Reboot of orjson. msgpack.org[Python]

ormsgpack ormsgpack is a fast msgpack library for Python. It is a fork/reboot of orjson It serializes faster than msgpack-python and deserializes a bi

Synthetik Python Mod - A save editor tool for the game Synthetik written in python

Synthetik_Python_Mod A save editor tool for the game Synthetik written in python

MiniJVM is simple java virtual machine written by python language, it can load class file from file system and run it.

MiniJVM MiniJVM是一款使用python编写的简易JVM,能够从本地加载class文件并且执行绝大多数指令。 支持的功能 1.从本地磁盘加载class并解析 2.支持绝大多数指令集的执行 3.支持虚拟机内存分区以及对象的创建 4.支持方法的调用和参数传递 5.支持静态代码块的初始化 不支

Pygments is a generic syntax highlighter written in Python

Welcome to Pygments This is the source of Pygments. It is a generic syntax highlighter written in Python that supports over 500 languages and text for

Retrying is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just about anything.

Retrying Retrying is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just

A full-featured, hackable tiling window manager written and configured in Python
A full-featured, hackable tiling window manager written and configured in Python

A full-featured, hackable tiling window manager written and configured in Python Features Simple, small and extensible. It's easy to write your own la

Comments
  • Better lexing(and scanning) and parsing

    Better lexing(and scanning) and parsing

    There is currently an issue with the lexing strategy for unary operators. Because i have only partially implemented it, constructs that uses unary operators are note exactly recognised. For example

    > -(1)
    1  # should be -1 
    

    This is problematic because it affects expressions such as to give wrong the answer

    > -1^2
    1  # should be -1
    > -(1^2)
    1  # should be -1
    

    The main reason for this is that unary operators are not actually lexed themselves, when an expression such as -1 is passed, the program checks if the immediately succeeding character is a number and immediately binds the sign to the number after it, a bracket/parentheses is not a number and thus the operator doesn't get lexed independently at all disabling the parser to not recognise have any knowledge of it.

    Also note that + and - are always initially tokenised as Token.BINARY_OPs and I believe this should change.

    see this line

    bug enhancement 
    opened by lestherll 2
  • Support for high precision floating-points

    Support for high precision floating-points

    Currently, the interpreter uses raw Python as the engine for evaluating mathematical expressions. This is good in normal cases but as you may already know, computers aren't so good at dealing with high precision floating-points. It would be good to be able to utilise perhaps some module to deal with this.

    > 9.999999800000001 * 10^15
    9999999800000002.0   # should be 9999999800000001
    
    bug enhancement 
    opened by lestherll 0
  • Create custom error codes

    Create custom error codes

    Currently, there are no custom error codes. Adding one would make the project more concrete and robust.

    Example

    # inside REPL
    > 1.1.1
    SyntaxError: Numbers can only have one decimal point
    
    enhancement 
    opened by lestherll 0
Releases(v0.1.2)
Owner
BSc Comp Sci at Newcastle University
Ssma is a tool that helps you collect your badges in a satr platform

satr-statistics-maker ssma is a tool that helps you collect your badges in a satr platform 🎖️ Requirements python = 3.7 Installation first clone the

TheAwiteb 3 Jan 04, 2022
Eros is an expiremental programming language built using simple Python code.

Eros is an expiremental programming language built using simple Python code. Featuring an easy syntax and unique features like type slicing, the language remains an expirement that grows in down time

zxro 2 Nov 21, 2021
Python module for creating the circuit simulation definitions for Elmer FEM

elmer_circuitbuilder Python module for creating the circuit simulation definitions for Elmer FEM. The circuit definitions enable easy setup of coils (

5 Oct 03, 2022
Backend/API for the Mumble.dev, an open source social media application.

Welcome to the Mumble Api Repository Getting Started If you are trying to use this project for the first time, you can get up and running by following

Dennis Ivy 189 Dec 27, 2022
dta Convert Dict To Attributes!

dta (Dict to Attributes) dta is very small dict (or json) to attributes converter. It is only have 1 files and applied to every python versions.

Rukchad Wongprayoon 0 Dec 31, 2021
Dot Browser is a privacy-conscious web browser with smarts built-in for protection against trackers and advertisments online.

🌍 Take back your privacy with Dot Browser, the privacy-conscious web browser that protects you from being tracked and monitored online.

Dot HQ 1k Jan 07, 2023
HiSim - House Infrastructure Simulator

HiSim is a Python package for simulation and analysis of household scenarios using modern components as alternative to fossil fuel based ones.

FZJ-IEK3 17 Dec 17, 2022
A example project's description is a high-level overview of why you’re doing a project.

A example project's description is a high-level overview of why you’re doing a project.

Nikita Matyukhin 12 Mar 23, 2022
🤞 Website-Survival-Detection

- 🤞 Website-Survival-Detection It can help you to detect the survival status of the website in batches and return the status code! - 📜 Instructions

B0kd1 4 Nov 14, 2022
Service for working with open data of the State Duma of the Russian Federation

Сервис для работы с открытыми данными Госдумы РФ Исходные данные из API Госдумы РФ извлекаются с помощью Apache Nifi и приземляются в хранилище Clickh

Aleksandr Sergeenko 2 Feb 14, 2022
A repository for all ZenML projects that are specific production use-cases.

ZenFiles Original Image source: https://www.goodfon.com/wallpaper/x-files-sekretnye-materialy.html And naturally, all credits to the awesome X-Files s

ZenML 66 Jan 06, 2023
A PG3D API Made with Python

PG3D Python API A Pixel Gun 3D Python API (Public Ver) Features Count: 29 How To Use? import api as pbn Examples pbn.isBanned(192819483) - True pbn.f

Karim 2 Mar 24, 2022
Cup Noodle Vending Maching Ordering Queue

Noodle-API Cup Noodle Vending Machine Ordering Queue Install dependencies in virtual environment python3 -m venv

Jonas Kazlauskas 1 Dec 09, 2021
Aerial Ace is a helper bot for poketwo which provide various functionalities on top of being a pokedex.

Aerial Ace is a helper bot for poketwo which provide various functionalities on top of being a pokedex.

Devanshu Mishra 1 Dec 01, 2021
Utils to quickly evaluate many 🤗 models on the GLUE tasks

Utils to quickly evaluate many 🤗 models on the GLUE tasks

Przemyslaw K. Joniak 1 Dec 22, 2021
Pygments is a generic syntax highlighter written in Python

Welcome to Pygments This is the source of Pygments. It is a generic syntax highlighter written in Python that supports over 500 languages and text for

1.2k Jan 06, 2023
Fastest python library for making asynchronous group requests.

FGrequests: Fastest Asynchronous Group Requests Installation Install using pip: pip install fgrequests Documentation Pretty easy to use. import fgrequ

Farid Chowdhury 14 Nov 22, 2022
A comparison of mesh generators.

This repository creates meshes of the same domains with multiple mesh generators and compares the results.

Nico Schlömer 29 Dec 12, 2022
Catalogue CRUD Application

This Python program creates a relational SQL database hosted on the Snowflake platform, then opens a CRUD GUI to manipulate and view the data. In this application, it is used as a book catalogue. CUR

0 Dec 13, 2022
This is the old code for bitcoin risk metric, the whole purpose form it is to help you DCA your investment according to bitcoin risk.

About The Project This is the old code for bitcoin risk metric, the whole purpose form it is to help you DCA your investment according to bitcoin risk

BitcoinRaven 2 Aug 03, 2022