Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Or Functional Dict solution in Clear category for Boolean Algebra by Infini7y
OPERATION_NAMES = ("conjunction", "disjunction", "implication", "exclusive", "equivalence")
def boolean1(x, y, operation):
"""Returns: 1 or 0
Classical 'elif' implementation
"""
if operation == OPERATION_NAMES[0]: # x and y
return 1 if x and y else 0
elif operation == OPERATION_NAMES[1]: # x or y
return 1 if x or y else 0
elif operation == OPERATION_NAMES[2]: # x imp y
return 1 if not x or y else 0
elif operation == OPERATION_NAMES[3]: # x xor y
return 1 if (x or y) and not (x and y) else 0
elif operation == OPERATION_NAMES[4]: # x !xor y
return 1 if x == y else 0
#return 1 if not (x or y) or (x and y) else 0
else:
raise ValueError("Operation not defined: '{}'".format(operation))
# ------------
def boolean2(x, y, operation):
"""Returns: 1 or 0
Function lookup implementation
"""
op_func = [
lambda x, y: x and y,
lambda x, y: x or y,
lambda x, y: not x or y,
lambda x, y: (x or y) and not (x and y),
lambda x, y: x == y,
]
try:
return op_func[OPERATION_NAMES.index(operation)](x, y)
except ValueError:
raise ValueError("Operation not defined: '{}'".format(operation))
# ------------
OPERATION_NAMES2 = {
"conjunction": lambda x, y: x and y,
"disjunction": lambda x, y: x or y,
"implication": lambda x, y: (not x) or y,
"exclusive": lambda x, y: (x or y) and not (x and y),
"equivalence": lambda x, y: x == y,
}
def boolean3(x, y, operation):
"""Returns: 1 or 0
Function lookup implementation
"""
return OPERATION_NAMES2[operation](x, y)
# ------------
boolean = boolean3
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert boolean(1, 0, "conjunction") == 0, "and"
assert boolean(1, 0, "disjunction") == 1, "or"
assert boolean(1, 1, "implication") == 1, "material"
assert boolean(0, 1, "exclusive") == 1, "xor"
assert boolean(0, 1, "equivalence") == 0, "same?"
Sept. 13, 2018
Comments: