2 # vim: set fileencoding=utf8
6 # Trinary expression evaluator
9 from Trits
import Trits
18 u
"∇": Trits("1ii"), u
"└": Trits("1ii"),
19 u
"∆": Trits("11i"), u
"┘": Trits("11i"),
29 # Ternary-logic-minimization-literature-based
33 def evaluate_unary(function
, inputs
):
34 """Given a unary function number in a Trits object, f, pass
35 all the trits in the inputs object through the function."""
37 assert isinstance(function
, Trits
), \
38 "Need to pass a Trits object as function"
39 assert isinstance(inputs
, Trits
), \
40 "You must pass a Trits object in inputs"
53 def __init__(self
, s
):
54 assert len(s
) > 0, "Empty string can't evaluate"
57 assert variable
.isalpha(), "Only accept expressions of form xxxxA, where x=unary operators, A=variable"
58 if DEBUG
: print "Variable:", variable
60 # Evaluate gates from right-to-left
61 unary_gates
= reversed(s
[:-1])
63 # Start with identity function
64 total_unary
= Trits("i01")
66 # Evaluate with unary function on the identity
67 for gate
in unary_gates
:
68 if DEBUG
: print "Gate:", gate
.encode('utf8')
69 total_unary
= evaluate_unary(unary_functions
[gate
], total_unary
)
71 # Now total_unary is the function# of all the unary gates
72 self
.total_unary
= total_unary
74 def evaluate(self
, inputs
):
75 return evaluate_unary(self
.total_unary
, inputs
)
77 if __name__
== "__main__":
79 print "Expression:", s
.encode('utf8')
81 print "Total unary function is:", e
.total_unary
84 ins
= Trits("iiiiiiiii00000001111111")
85 print "Passing in trit vector as 'a':"
87 print s
.encode('utf8') + ":\t", e
.evaluate(ins
)