11

I'm making a function that makes 50 random trees in a 1000 by 1000 area.

I need to make sure that Tree 2's x and y both are not the same as Tree 1's x and y. This takes a NAND Gate. I'm okay with one of them being the same, I'm okay with neither being the same, but not with both being the same. I can't seem to find anything about making NAND Gates in python. I'm fine with defining a function to make a NAND.

2
  • 4
    Is there something wrong with def nand(a, b): return not (a and b)? Dec 17, 2013 at 17:11
  • I think the sentence "Tree 2's x and y both are not the same as Tree 1's x and y" is an incorrect (and meaningless) placement of "both"
    – Eric
    Dec 17, 2013 at 17:17

4 Answers 4

28

Since NAND is the negation of and,

not (a and b) 

should totally work, with a and b as inputs, or do I miss something?

7

Interpreting:

Tree 2's x and y both are not the same as Tree 1's x and y

As:

Tree 2's x and y are not both the same as Tree 1's x and y

return (t1.x, t1.y) != (t2.x, t2.y)
0

Equivalently, you can also use ~(a&b)+2, though I'm not sure why you would prefer it:

opts = [(0,0),(0,1),(1,0),(1,1)]
[print(f"{a} NAND {b} = {~(a&b)+2}") for a,b in opts]
0 NAND 0 = 1
0 NAND 1 = 1
1 NAND 0 = 1
1 NAND 1 = 0
0

This will provide all six logic gate functions (including nand) in a dictionary:

from operator import and_, or_, xor

gates = {g.__name__.rstrip('_'): g for g in (and_, or_, xor)}
gates = {**gates, **{f'n{k}': lambda a, b, _f=v: _f(a, b) ^ True for k, v in gates.items()}}

x ^ y means xor(x, y). x ^ True means xor(x, True) which means not x.

Usage
>>> gates
{'and': <function _operator.and_(a, b, /)>,
 'or': <function _operator.or_(a, b, /)>,
 'xor': <function _operator.xor(a, b, /)>,
 'nand': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function and_>)>,
 'nor': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function or_>)>,
 'nxor': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function xor>)>}

>>> gates['and'](True, True)
True

>>> gates['and'](1, 1)
1

>>> gates['nand'](True, True)
False

>>> gates['nand'](1, 1)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.