How to resolve the algorithm Ternary logic step by step in the Python programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Ternary logic step by step in the Python programming language

Table of Contents

Problem Statement

In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false. Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski. These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.

Note:   Setun   (Сетунь) was a   balanced ternary   computer developed in 1958 at   Moscow State University.   The device was built under the lead of   Sergei Sobolev   and   Nikolay Brusentsov.   It was the only modern   ternary computer,   using three-valued ternary logic

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Ternary logic step by step in the Python programming language

The provided Python code defines a custom type called Trit, which represents a ternary value (similar to a boolean but with an additional "maybe" state). It extends the built-in int type and provides various operators and methods to manipulate trits.

Class Definition (Trit):

  • Constructor (__new__): Takes a value and initializes the trit accordingly. It converts strings like "TRUE", "FALSE", and "MAYBE" to their respective numeric values.

  • Representation (__repr__ and __str__): Returns the string representation of the trit as "TRUE", "FALSE", or "MAYBE."

  • Boolean Conversion (__bool__): Defines how trits are converted to booleans. "TRUE" evaluates to True, "FALSE" to False, and "MAYBE" raises an error.

Operators:

  • Logical Operators (__and__, __or__, __xor__): Handle logical operations (AND, OR, XOR) for trits. They use a lookup table _ttable to determine the result based on the operands' values.

  • Logical Negation (__invert__): Implements logical negation (~) for trits using the same lookup table.

  • Flip Attribute (__getattr__): Provides a way to access the negation of a trit using the attribute _n or flip.

Global Variables:

  • TRUE, FALSE, MAYBE: Predefined trit constants representing "TRUE", "FALSE", and "MAYBE."

  • _ttable: A lookup table that stores the results of logical operations for various combinations of trits.

Usage:

The code demonstrates the use of the Trit type by performing logical operations and displaying the results. It shows the inverse, AND, OR, and XOR operations for different combinations of "FALSE", "TRUE", and "MAYBE."

This code is useful for working with ternary logic, which is an alternative to traditional binary logic. It allows for the representation of a third state, "maybe," which can be useful in situations where there is some uncertainty or incompleteness in the available information.

Source code in the python programming language

class Trit(int):
    def __new__(cls, value):
        if value == 'TRUE':
            value = 1
        elif value == 'FALSE':
            value = 0
        elif value == 'MAYBE':
            value = -1
        return super(Trit, cls).__new__(cls, value // (abs(value) or 1)) 

    def __repr__(self):
        if self > 0:
            return 'TRUE'
        elif self == 0:
            return 'FALSE'
        return 'MAYBE'

    def __str__(self):
        return repr(self)

    def __bool__(self):
        if self > 0:
            return True
        elif self == 0:
            return False
        else:
            raise ValueError("invalid literal for bool(): '%s'" % self)

    def __or__(self, other):
        if isinstance(other, Trit):
            return _ttable[(self, other)][1]
        else:
            try:
                return _ttable[(self, Trit(bool(other)))][1]
            except:
                return NotImplemented

    def __ror__(self, other):
        if isinstance(other, Trit):
            return _ttable[(self, other)][1]
        else:
            try:
                return _ttable[(self, Trit(bool(other)))][1]
            except:
                return NotImplemented

    def __and__(self, other):
        if isinstance(other, Trit):
            return _ttable[(self, other)][0]
        else:
            try:
                return _ttable[(self, Trit(bool(other)))][0]
            except:
                return NotImplemented

    def __rand__(self, other):
        if isinstance(other, Trit):
            return _ttable[(self, other)][0]
        else:
            try:
                return _ttable[(self, Trit(bool(other)))][0]
            except:
                return NotImplemented

    def __xor__(self, other):
        if isinstance(other, Trit):
            return _ttable[(self, other)][2]
        else:
            try:
                return _ttable[(self, Trit(bool(other)))][2]
            except:
                return NotImplemented

    def __rxor__(self, other):
        if isinstance(other, Trit):
            return _ttable[(self, other)][2]
        else:
            try:
                return _ttable[(self, Trit(bool(other)))][2]
            except:
                return NotImplemented

    def __invert__(self):
        return _ttable[self]
    
    def __getattr__(self, name):
        if name in ('_n', 'flip'):
            # So you can do x._n == x.flip; the inverse of x
            # In Python 'not' is strictly boolean so we can't write `not x`
            # Same applies to keywords 'and' and 'or'.
            return _ttable[self]
        else:
            raise AttributeError 


        
TRUE, FALSE, MAYBE = Trit(1), Trit(0), Trit(-1)

_ttable = {
    #    A: -> flip_A
         TRUE: FALSE,
        FALSE:  TRUE,
        MAYBE: MAYBE,
    #     (A, B): -> (A_and_B, A_or_B, A_xor_B)
        (MAYBE, MAYBE): (MAYBE, MAYBE, MAYBE),
        (MAYBE, FALSE): (FALSE, MAYBE, MAYBE),
        (MAYBE,  TRUE): (MAYBE,  TRUE, MAYBE),
        (FALSE, MAYBE): (FALSE, MAYBE, MAYBE),
        (FALSE, FALSE): (FALSE, FALSE, FALSE),
        (FALSE,  TRUE): (FALSE,  TRUE,  TRUE),
        ( TRUE, MAYBE): (MAYBE,  TRUE, MAYBE),
        ( TRUE, FALSE): (FALSE,  TRUE,  TRUE),
        ( TRUE,  TRUE): ( TRUE,  TRUE, FALSE),
    }


values = ('FALSE', 'TRUE ', 'MAYBE')

print("\nTrit logical inverse, '~'")
for a in values:
    expr = '~%s' % a
    print('  %s = %s' % (expr, eval(expr)))

for op, ophelp in (('&', 'and'), ('|', 'or'), ('^', 'exclusive-or')):
    print("\nTrit logical %s, '%s'" % (ophelp, op))
    for a in values:
        for b in values:
            expr = '%s %s %s' % (a, op, b)
            print('  %s = %s' % (expr, eval(expr)))


  

You may also check:How to resolve the algorithm Assertions step by step in the Forth programming language
You may also check:How to resolve the algorithm Factorial step by step in the Pebble programming language
You may also check:How to resolve the algorithm Unicode strings step by step in the Ring programming language
You may also check:How to resolve the algorithm Goldbach's comet step by step in the Raku programming language
You may also check:How to resolve the algorithm Anti-primes step by step in the Crystal programming language