Skip to content

Instantly share code, notes, and snippets.

@rusty-snake
Created September 23, 2021 08:09
Show Gist options
  • Select an option

  • Save rusty-snake/db392affd0a5f5fe401f47fa4065b292 to your computer and use it in GitHub Desktop.

Select an option

Save rusty-snake/db392affd0a5f5fe401f47fa4065b292 to your computer and use it in GitHub Desktop.

Revisions

  1. rusty-snake created this gist Sep 23, 2021.
    73 changes: 73 additions & 0 deletions truth_table.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,73 @@
    #!/usr/bin/python3

    # Copyright © 2020,2021 rusty-snake
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy
    # of this software and associated documentation files (the "Software"), to deal
    # in the Software without restriction, including without limitation the rights
    # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    # copies of the Software, and to permit persons to whom the Software is
    # furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    # SOFTWARE.

    class Var:
    def __init__(self, flip_at):
    self.val = True
    self._i = 0
    self.flip_at = flip_at

    def __bool__(self):
    return self.val

    def __str__(self):
    return "1" if self.val else "0"

    def inc(self):
    if self._i < self.flip_at:
    self._i += 1
    else:
    self._i = 1
    self.val = not self.val


    class TruthTable:
    def __init__(self, n):
    self.n_sq = 2 ** n
    self.vars = {}
    for i in range(1, n + 1):
    name = chr(64 + i)
    self.vars[name] = Var(self.n_sq / 2 ** i)

    def tell_me_the_truth(self, expr):
    for var in self.vars:
    print(var, end=" ")
    print("│ EXPR")
    for _ in range(1, len(self.vars) + 1):
    print("──", end="")
    print("┼─────")

    for _ in range(1, self.n_sq + 1):
    for var in self.vars:
    self.vars[var].inc()
    print(self.vars[var], end=" ")
    print("│", "1" if expr(self.vars) else "0")


    def imp(p, q):
    return not p or q

    if __name__ == "__main__":
    def expr(v): return (v['A'] or v['B']) and v['C']
    TruthTable(3).tell_me_the_truth(expr)

    TruthTable(4).tell_me_the_truth(lambda v: imp(v['A'], v['B']) or imp(v['C'], v['D']))