Skip to content

Instantly share code, notes, and snippets.

@les-peters
Last active November 11, 2019 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save les-peters/f84b635b729bd4729d21194a45e630d1 to your computer and use it in GitHub Desktop.
Save les-peters/f84b635b729bd4729d21194a45e630d1 to your computer and use it in GitHub Desktop.
Cassidoo 2019-11-11 challenge
# Write a program that implements logic gs AND, OR, NOT, NAND, NOR, XOR, and XNOR.
# thanks to Ryan North ( https://www.howtoinventeverything.com/, Chapter 17 )
def lG(g, *a):
v = (0, 1)
for i in a:
if i not in v:
return -1
if g == 'NOT':
return (1 - a[0])
if g == 'OR':
if a[0]:
return(a[0])
else:
return(a[1])
if g == 'AND':
if lG('NOT', a[0]):
return 0
else:
if lG('NOT', a[1]):
return 0
else:
return 1
if g == "NAND":
return lG('NOT', lG('AND', a[0], a[1]))
if g == "NOR":
return lG('NOT', lG('OR', a[0], a[1]))
if g == "XOR":
return logicGate('AND', logicGate('NAND', a[0], a[1]), logicGate('OR', a[0], a[1]))
if g == "XNOR":
return logicGate('NOT', logicGate('AND', logicGate('NAND', a[0], a[1]), logicGate('OR', a[0], a[1])))
print('ERROR TESTING')
print('should be -1', logicGate('NOT', 2))
print('NOT')
print('should be 0', lG('NOT', 1))
print('should be 1', lG('NOT', 0))
print('OR')
print('should be 0', lG('OR', 0, 0))
print('should be 1', lG('OR', 1, 0))
print('should be 1', lG('OR', 0, 1))
print('should be 1', lG('OR', 1, 1))
print('AND')
print('should be 0', lG('AND', 0, 0))
print('should be 0', lG('AND', 1, 0))
print('should be 0', lG('AND', 0, 1))
print('should be 1', lG('AND', 1, 1))
print('NAND')
print('should be 1', lG('NAND', 0, 0))
print('should be 1', lG('NAND', 1, 0))
print('should be 1', lG('NAND', 0, 1))
print('should be 0', lG('NAND', 1, 1))
print('NOR')
print('should be 1', lG('NOR', 0, 0))
print('should be 0', lG('NOR', 1, 0))
print('should be 0', lG('NOR', 0, 1))
print('should be 0', lG('NOR', 1, 1))
print('XOR')
print('should be 0', logicGate('XOR', 0, 0))
print('should be 1', logicGate('XOR', 1, 0))
print('should be 1', logicGate('XOR', 0, 1))
print('should be 0', logicGate('XOR', 1, 1))
print('XNOR')
print('should be 1', logicGate('XNOR', 0, 0))
print('should be 0', logicGate('XNOR', 1, 0))
print('should be 0', logicGate('XNOR', 0, 1))
print('should be 1', logicGate('XNOR', 1, 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment