I know that given n inputs, there are 2^(2^n) possible Boolean functions. Is there some way in Python of encoding these functions, so that when, say, given a number between 0 and 65,535 and four Boolean values, I can get a corresponding Boolean value returned?
1 Answer
Use the bits of N as a truth-table, and then use the inputs to select a bit in it:
def boolFunc(N, *args):
bit = 0
for value in args:
bit = 2 * bit + int(value)
return N & (1 << bit) != 0
For example, with 4 bits of input, 27030 is the parity function:
>>> boolFunc( 27030, False, False, False, False )
False
>>> boolFunc( 27030, False, True, False, False )
True
>>> boolFunc( 27030, False, True, False, True )
False
>>> boolFunc( 27030, True, True, True, False )
True
For 5 bits, the parity function is 2523490710:
>>> boolFunc( 2523490710, True, False, True, False, True )
True
3 Comments
Melab
It needs to work with any number of inputs. And I was expecting things like special classes or functions or libraries.
Melab
Also, N is sixteen bits, but the variable
bit is only four, so somehow that doesn't seem like it matches up properly.Boojum
@Melab - No need for classes or libraries here. But you're right; I was missing a left shift. I also generalized it to any number of bits.