├── .gitignore ├── LICENSE ├── README.md ├── TruthTableGenerator.exe ├── TruthTableGenerator.py ├── gui.png └── gui.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # Jetbrains 132 | .idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 xehoth 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TruthTableGenerator 2 | 3 | Generate truth table according to logic expressions. 4 | 5 | ## Logic Expressions 6 | 7 | - `!`, `~`, `not`, `¬` are the same. 8 | - `&`, `*`, `and`, `∧`, are the same. 9 | - `|`, `+`, `or`, `∨`, `v` are the same. 10 | - `<->`, `↔` are the same. 11 | - `->`, `→` are the same. 12 | - `^`, `⊕` are the same. 13 | 14 | ## Usage for python3 environment 15 | 16 | Python3 is required, see help using `python TruthTableGenerator.py` or `python3 TruthTableGenerator.py` 17 | 18 | ``` bash 19 | usage: [-h | --help] [-i | --input ] 20 | [-o | --output ] [-c | --console] 21 | [-m | --markdown] [-r | --reverse ] 22 | [-i | --input ] 23 | input from 24 | [-o | --output ] 25 | output the result to 26 | [-c | --console] 27 | console mode (default) 28 | [-m | --markdown] 29 | generate markdown table 30 | [-r | --reverse] 31 | reverse the enumerate order (default F -> T) 32 | 33 | ``` 34 | 35 | ## Usage for others 36 | 37 | using `TruthTableGenerator.exe` to use a GUI calculator to calculate directly. 38 | 39 | You only need to download the `TruthTableGenerator.exe` and click it. 40 | 41 | ![avatar](gui.png) 42 | 43 | ## Feature 44 | 45 | - It can input expressions from a file and generate tables for expressions in each line. 46 | - It can generate a markdown table by using command. 47 | - You can copy your table by clicking the `copy` button on GUI. 48 | 49 | 50 | ## Notice 51 | - You cannot use variable names that contain numbers. 52 | - You'd better use no more than four variables, otherwise the GUI will not display properly. 53 | -------------------------------------------------------------------------------- /TruthTableGenerator.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xehoth/TruthTableGenerator/7c91af08cc83d891d07cbcb9b7960e8793acf8a7/TruthTableGenerator.exe -------------------------------------------------------------------------------- /TruthTableGenerator.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (c) 2020, xehoth 3 | # All rights reserved. 4 | # 5 | # @file TruthTableGenerator.py 6 | # @author: xehoth 7 | from typing import List 8 | import re 9 | import sys 10 | 11 | 12 | class Proposition: 13 | def __init__(self, value=False): 14 | self.value = value 15 | 16 | # -> 17 | def __rshift__(self, rhs): 18 | return Proposition(not (self.value and not rhs.value)) 19 | 20 | # or 21 | def __add__(self, rhs): 22 | return Proposition(self.value or rhs.value) 23 | 24 | # and 25 | def __mul__(self, rhs): 26 | return Proposition(self.value and rhs.value) 27 | 28 | # not 29 | def __invert__(self): 30 | return Proposition(not self.value) 31 | 32 | # <-> 33 | def __eq__(self, rhs): 34 | return Proposition((self.value and rhs.value) or (not self.value and not rhs.value)) 35 | 36 | # ^ 37 | def __ne__(self, rhs): 38 | return Proposition(self.value != rhs.value) 39 | 40 | 41 | def getTableElement(s: str, markdown=False, l = -1) -> str: 42 | l = (len(s) if (l == -1 or markdown == True) else l) 43 | if markdown: 44 | s = "$" + s + "$" 45 | s = s.center(l + 2) 46 | return s + "|" if markdown else s 47 | 48 | 49 | def getPropositions(s: str) -> List[str]: 50 | return list(sorted(set(re.findall(r'\w+', s.replace("T", "").replace("F", ""))))) 51 | 52 | 53 | def getEvalExpression(s: str): 54 | # not 55 | s = s.replace("!", "~").replace("not", "~").replace( 56 | "¬", "~").replace(r"\neg", "~") 57 | # and 58 | s = s.replace("&", "*").replace(r"\wedge", "*").replace("and", 59 | "*").replace("∧", "*") 60 | # or 61 | s = s.replace("|", "+").replace(r"\vee", "+").replace("or", 62 | "+").replace("∨", "+").replace("v", "+") 63 | # <-> 64 | s = s.replace("<->", "==").replace("↔", 65 | "==").replace(r"\leftrightarrow", "==") 66 | # -> 67 | s = s.replace("->", ">>").replace("→", ">>").replace(r"\rightarrow", ">>") 68 | 69 | # ^ 70 | s = s.replace("^", "!=").replace("⊕", "!=") 71 | return s 72 | 73 | 74 | def getLatexExpression(s: str) -> str: 75 | return s.replace("~", r" \neg ").replace("*", r" \wedge ").replace( 76 | "+", r" \vee ").replace("==", r" \leftrightarrow ").replace(">>", r" \rightarrow ").replace("!=", r" \oplus ") 77 | 78 | 79 | def generateTruthTable(expression: str, reverse=False, markdown=False, file=sys.stdout) -> None: 80 | # True 81 | T = Proposition(True) 82 | # False 83 | F = Proposition(False) 84 | # strip 85 | expression = expression.strip() 86 | # eval string 87 | s = getEvalExpression(expression) 88 | 89 | # tautology & conflict 90 | tautology = True 91 | conflict = False 92 | 93 | if markdown: 94 | expression = getLatexExpression(s) 95 | 96 | props = getPropositions(s) 97 | n = len(props) 98 | # prop eval buffer 99 | buf = [Proposition() for i in range(n)] + [T, F] 100 | 101 | if markdown: 102 | print("|", end='', file=file) 103 | 104 | for i in props + [expression]: 105 | print(getTableElement(i, markdown=markdown), sep='', end='', file=file) 106 | print(file=file) 107 | if markdown: 108 | print("|", end='', file=file) 109 | for i in range(n + 1): 110 | print(" :--: |", end='', file=file) 111 | print() 112 | 113 | states = range(0, 1 << n) 114 | 115 | for state in reversed(states) if reverse else states: 116 | if markdown: 117 | print("|", end='', file=file) 118 | for i in range(n): 119 | buf[i].value = (state >> (n - i - 1)) & 1 == 1 120 | print(getTableElement( 121 | "FT"[buf[i].value], markdown=markdown, l = len(props[i])), end='', file=file) 122 | res = eval("(" + s + ").value",{v: buf[i] for i, v in enumerate(props + ['T', 'F'])}) 123 | print(getTableElement("FT"[res], markdown=markdown, l = len(expression)), file=file) 124 | tautology = tautology and res 125 | conflict = conflict or res 126 | if tautology: 127 | print("\nIt's tautological.\n", file=file) 128 | if not conflict: 129 | print("\nIt's conflict.\n", file=file) 130 | 131 | def main(inputFile=sys.stdin, outputFile=sys.stdout, reverse=False, markdown=False) -> None: 132 | for s in inputFile: 133 | generateTruthTable(s, reverse=reverse, 134 | markdown=markdown, file=outputFile) 135 | 136 | 137 | def printHelp() -> None: 138 | print("""Truth Table Generator 139 | usage: [-h | --help] [-i | --input ] 140 | [-o | --output ] [-c | --console] 141 | [-m | --markdown] [-r | --reverse ] 142 | [-i | --input ] 143 | input from 144 | [-o | --output ] 145 | output the result to 146 | [-c | --console] 147 | console mode (default) 148 | [-m | --markdown] 149 | generate markdown table 150 | [-r | --reverse] 151 | reverse the enumerate order (default F -> T) 152 | """) 153 | 154 | 155 | if __name__ == "__main__": 156 | args = sys.argv 157 | if len(args) == 1: 158 | main() 159 | elif "-h" in args or "--help" in args: 160 | printHelp() 161 | elif "-c" in args or "--console" in args: 162 | main() 163 | else: 164 | markdown = "-m" in args or "--markdown" in args 165 | reverse = "-r" in args or "--reverse" in args 166 | inputFile = '' 167 | outputFile = '' 168 | if "-i" in args: 169 | inputFile = args[args.index("-i") + 1] 170 | if "--input" in args: 171 | inputFile = args[args.index("--input") + 1] 172 | if "-o" in args: 173 | outputFile = args[args.index("-o") + 1] 174 | if "--output" in args: 175 | outputFile = args[args.index("--output") + 1] 176 | if not inputFile and not outputFile: 177 | main(reverse=reverse, markdown=markdown) 178 | elif not inputFile and outputFile: 179 | with open(outputFile, "w", encoding='utf-8') as o: 180 | main(outputFile=o, reverse=reverse, markdown=markdown) 181 | elif inputFile and not outputFile: 182 | with open(inputFile, "r", encoding='utf-8') as i: 183 | main(inputFile=i, reverse=reverse, markdown=markdown) 184 | else: 185 | with open(inputFile, "r", encoding='utf-8') as i, open(outputFile, "w", encoding='utf-8') as o: 186 | main(inputFile=i, outputFile=o, 187 | reverse=reverse, markdown=markdown) 188 | -------------------------------------------------------------------------------- /gui.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xehoth/TruthTableGenerator/7c91af08cc83d891d07cbcb9b7960e8793acf8a7/gui.png -------------------------------------------------------------------------------- /gui.py: -------------------------------------------------------------------------------- 1 | import tkinter as TK 2 | import pyperclip 3 | import io 4 | from tkinter.constants import INSERT 5 | from TruthTableGenerator import generateTruthTable 6 | import tkinter.messagebox 7 | 8 | import os,sys 9 | BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 10 | sys.path.append(BASE_DIR) 11 | 12 | # 主窗口 13 | root = TK.Tk( ) 14 | root.title("Truth table Caculator") 15 | root.resizable(0, 0) 16 | root.geometry('320x620') 17 | 18 | result = TK.StringVar( ) 19 | equation = TK.StringVar( ) 20 | result.set(' ') 21 | equation.set(' ') 22 | 23 | # get the char 24 | def getnum(num): 25 | temp = equation.get( ) 26 | temp2 = result.get( ) 27 | print(temp) 28 | print(temp2) 29 | if temp2 != ' ' : 30 | temp = '' 31 | temp2 = ' ' 32 | result.set(temp2) 33 | temp = temp + num 34 | equation.set(temp) 35 | print(equation) 36 | 37 | # delete the last char 38 | def back( ): 39 | temp = equation.get( ) 40 | equation.set(temp[:-1]) 41 | 42 | # clear the string 43 | def clear( ): 44 | equation.set(' ') 45 | result.set(' ') 46 | 47 | # get the truth table for the string 48 | def run( ): 49 | temp = equation.get( ) 50 | print(temp) 51 | buffer = io.StringIO() 52 | generateTruthTable(temp, reverse=False, markdown=False, file=buffer) 53 | print(buffer.getvalue()) 54 | result.set(buffer.getvalue()) 55 | 56 | def copy_ans(): 57 | pyperclip.copy(result.get()) 58 | tkinter.messagebox.showinfo("successful!", "The result has been copied") 59 | 60 | # show the result 61 | show_uresult = TK.Label(root, bg = 'white', fg = 'black', font = ('Arail', '15'), bd = '0', textvariable = equation, anchor = 'se') 62 | show_dresult = TK.Label(root, bg = 'white', fg = 'black', font = ('Arail', '10'), bd = '0', textvariable = result, anchor = 'se') 63 | # show_dresult = TK.Text(root,bg='white',fg = 'black',font = ('Arail','10'),bd='0',) 64 | show_uresult.place(x = '10', y = '10', width = '300', height = '50') 65 | show_dresult.place(x = '10', y = '60', width = '300', height = '250') 66 | 67 | # bottom 68 | # first line 69 | button_back = TK.Button(root,text = 'del',bg = 'DarkGray',command = back) 70 | button_back.place(x = '10', y = '350', width = '60', height = '40') 71 | button_double_bracket = TK.Button(root, text = '<->',bg = 'DarkGray',command = lambda : getnum('<->')) 72 | button_double_bracket.place(x = '90', y = '350', width = '60', height = '40') 73 | button_rbracket = TK.Button(root,text = '->', bg = 'DarkGray', command = lambda : getnum('->')) 74 | button_rbracket.place(x = '170', y = '350', width = '60', height = '40') 75 | button_copy = TK.Button(root, text = 'copy', bg = 'DarkGray', command = lambda : copy_ans()) 76 | button_copy.place(x = '250', y = '350', width = '60', height = '40') 77 | # second line 78 | button_h = TK.Button(root, text = 'h', bg = 'DarkGray', command = lambda : getnum('h')) 79 | button_h.place(x = '10', y = '405', width = '60', height ='40') 80 | button_i = TK.Button(root, text = 'i', bg = 'DarkGray', command = lambda : getnum('i')) 81 | button_i.place(x = '90', y = '405', width = '60',height = '40') 82 | button_j = TK.Button(root, text = 'j', bg = 'DarkGray', command = lambda : getnum('j')) 83 | button_j.place(x = '170', y ='405', width = '60', height = '40') 84 | button_and = TK.Button(root, text = '&', bg = 'DarkGray', command = lambda : getnum('&')) 85 | button_and.place(x = '250', y = '405', width = '60', height = '40') 86 | # third line 87 | button_e = TK.Button(root,text = 'e',bg = 'DarkGray',command = lambda : getnum('e')) 88 | button_e.place(x = '10',y = '460',width = '60',height = '40') 89 | button_f = TK.Button(root,text = 'f', bg = 'DarkGray', command = lambda : getnum('f')) 90 | button_f.place(x = '90',y = '460',width = '60', height = '40') 91 | button_g = TK.Button(root,text = 'g', bg = 'DarkGray', command = lambda : getnum('g')) 92 | button_g.place(x = '170',y='460', width = '60',height='40') 93 | button_or = TK.Button(root, text = '|', bg = 'DarkGray', command = lambda : getnum('|')) 94 | button_or.place(x = '250', y = '460', width = '60', height = '40') 95 | # forth line 96 | button_b = TK.Button(root, text = 'b',bg = 'DarkGray', command = lambda : getnum('b')) 97 | button_b.place(x = '10',y = '515', width = '60', height = '40') 98 | button_c = TK.Button(root, text = 'c', bg = 'DarkGray', command = lambda : getnum('c')) 99 | button_c.place(x = '90', y = '515', width = '60', height = '40') 100 | button_d = TK.Button(root, text = 'd', bg = 'DarkGray', command = lambda : getnum('d')) 101 | button_d.place(x = '170',y = '515',width = '60', height = '40') 102 | button_xor = TK.Button(root, text = '^', bg = 'DarkGray', command = lambda : getnum('^')) 103 | button_xor.place(x = '250', y = '515', width = '60', height ='40') 104 | # fifth line 105 | button_MC = TK.Button(root, text = 'MC', bg = 'DarkGray', command = clear) 106 | button_MC.place(x = '10', y = '570', width = '60', height = '40') 107 | button_a = TK.Button(root, text = 'a', bg = 'DarkGray', command = lambda : getnum('a')) 108 | button_a.place(x = '90', y = '570', width = '60', height = '40') 109 | button_not = TK.Button(root, text = '¬', bg='DarkGray', command = lambda : getnum('¬')) 110 | button_not.place(x = '170', y = '570', width = '60', height = '40') 111 | button_done = TK.Button(root, text = 'done', bg = 'DarkGray', command = run) 112 | button_done.place(x = '250', y = '570', width = '60', height = '40') 113 | 114 | root.mainloop( ) --------------------------------------------------------------------------------