1

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 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

It needs to work with any number of inputs. And I was expecting things like special classes or functions or libraries.
Also, N is sixteen bits, but the variable bit is only four, so somehow that doesn't seem like it matches up properly.
@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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.