Skip to content

Instantly share code, notes, and snippets.

@Friedjof
Created January 11, 2023 17:35
Show Gist options
  • Save Friedjof/ac5a4fbeb530059e151cf5b6e44e0439 to your computer and use it in GitHub Desktop.
Save Friedjof/ac5a4fbeb530059e151cf5b6e44e0439 to your computer and use it in GitHub Desktop.
"""
The script Bool Function:
This is a smale python script to generate a truth table for a boolean function.
The function can be defined by the user as a lambda function or by using the predefined functions.
The predefined functions are: AND, OR, XOR, Implikation, Äquivalenz.
The script can also be used to test the predefined functions with the run_tests() method.
Example:
>>> a = Variable()
>>> b = Variable()
>>> c = Variable()
>>> f = Function("AND", lambda x, y: x and y, a, b)
>>> print(f)
+----------------------------+
| Wahrheitstabelle für 'AND' |
+--------+--------+----------+
| a | b | AND |
+--------+--------+----------+
| False | False | False |
| False | True | False |
| True | False | False |
| True | True | True |
+--------+--------+----------+
Syntax:
- AND = lambda x, y: x and y
- OR = lambda x, y: x or y
- XOR = lambda x, y: x ^ y
- Implikation = lambda x, y: x / y
- Äquivalenz = lambda x, y: x // y
Classes:
Variable: A variable that can be used in a boolean function.
- value: The value of the variable.
- name: The name of the variable.
- __init__(value: bool = True, name: str = None) -> None
Initializes the variable.
- set_value(value: bool) -> None
Sets the value of the variable.
- __bool__() -> bool
Returns the value of the variable.
- __and__(other: 'Variable') -> 'Variable'
Returns the result of the AND operation.
- __or__(other: 'Variable') -> 'Variable'
Returns the result of the OR operation.
- __xor__(other: 'Variable') -> 'Variable'
Returns the result of the XOR operation.
- __truediv__(other: 'Variable') -> 'Variable'
Returns the result of the Implikation operation.
Function: A boolean function.
- name: The name of the function.
- func: The function.
- __init__(name: str, func: Callable, *args: Variable) -> None
Initializes the function.
- __call__() -> bool
Calls the function witch is defined by the func attribute.
- __bool__() -> bool
Returns the result of the function with the current values of the arguments.
- __str__() -> str
Returns the truth table of the function.
- get_table() -> str
Returns the truth table of the function.
- _set_values(*values: bool) -> None
Sets the values of the arguments.
- run_tests() -> None
Runs the predefined functions with the current arguments.
I hope you enjoy the script.
"""
from typing import Callable
import random
import string
from prettytable import PrettyTable
def random_name() -> str:
return ''.join(random.choice(string.ascii_uppercase) for _ in range(5))
class Variable:
def __init__(self, value: bool = True, name: str = None) -> None:
if name is None:
name = random_name()
self.name = name
self._value: bool = value
def set_value(self, value: bool) -> None:
self._value = value
def __bool__(self) -> bool:
return self._value
def __and__(self, other: 'Variable') -> 'Variable':
return Variable(self._value and other._value)
def __or__(self, other: 'Variable') -> 'Variable':
return Variable(self._value or other._value)
def __xor__(self, other: 'Variable') -> 'Variable':
return Variable(self._value ^ other._value)
def __truediv__(self, other: 'Variable') -> 'Variable':
return Variable(not (self._value and not other._value))
def __floordiv__(self, other: 'Variable') -> 'Variable':
return Variable(not (self._value ^ other._value))
def __invert__(self) -> 'Variable':
return Variable(not self._value)
def __str__(self) -> str:
return f"{self._value}"
class Function:
def __init__(self, name: str, func: Callable, *args: Variable) -> None:
self.name = name
self.func: Callable = func
self.args: tuple = args
def __call__(self) -> bool:
return self.func(*self.args)
def __bool__(self) -> bool:
return self()
def __str__(self) -> str:
return self.get_table()
def get_table(self) -> str:
table = PrettyTable()
table.title = f"Truth Table for '{self.name}'"
table.field_names = [arg.name for arg in self.args] + [self.name]
for i in range(2 ** len(self.args)):
self._set_values(*[bool(int(u)) for u in f"{i:0{len(self.args)}b}"])
table.add_row([str(arg) for arg in self.args] + [str(self())])
return table.get_string()
def _set_values(self, *values: bool) -> None:
for value, arg in zip(values, self.args):
arg.set_value(value)
def run_tests(self) -> None:
if len(self.args) < 2:
raise ValueError("Function must have at least two arguments")
current_func = self.func
funcs = {"AND": lambda x, y: x and y, "OR": lambda x, y: x or y, "XOR": lambda x, y: x ^ y, "Implikation": lambda x, y: x / y, "Äquivalenz": lambda x, y: x // y}
for name, func in funcs.items():
self.name = name
self.func = func
print(self.get_table())
self.func = current_func
if __name__ == '__main__':
a, b, c = Variable(name="a"), Variable(name="b"), Variable(name="c")
print(Function("F", lambda: None, a, b).run_tests())
print(Function("F1", lambda x, y, z: x and y or z / y // x, a, b, c))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment