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.

Asclepius
  • 57,944
  • 17
  • 167
  • 143
Jonathan Spirit
  • 569
  • 3
  • 7
  • 14
  • 4
    Is there something wrong with `def nand(a, b): return not (a and b)`? – Henry Keiter Dec 17 '13 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 '13 at 17:17

4 Answers4

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?

Asclepius
  • 57,944
  • 17
  • 167
  • 143
jcklie
  • 4,054
  • 3
  • 24
  • 42
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)
Eric
  • 95,302
  • 53
  • 242
  • 374
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
Alex Moore-Niemi
  • 2,913
  • 2
  • 24
  • 22
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
Asclepius
  • 57,944
  • 17
  • 167
  • 143