pythonnumpydiscrete-mathematicstruthtable

Dynamic Loops for Arrays


I want to create a TruthTable maker. So If I have some n variables I will have 2^n rows. With Each Statement conatining only zeros and ones.

For example, Consider A^B. Possible values of A are [0, 1] and for B also [0, 1]. I want to apply AND for A and B. I don't want to appproach in a routine loop way because, In case Variables are greater than 2, I should hardcode loops for every possibility.

Is there any numpy way for my requirement? I mean to apply an Operation for each elements of two arrays.


Solution

  • This should work for you-

    import numpy as np
    
    # the resulting table need not be square
    A = np.array([[0, 1]])
    B = np.array([[0, 1, 1]])
    # repeat B 'row' times
    rows = A.shape[1]
    B = np.tile(B, (rows, 1))
    # transpose A to columns and perform element wise logical and operation
    print A.T & B
    
    print (A.T & B) != 0
    

    output

    [[0 0 0]
     [0 1 1]]
    
    [[False False False]
     [False  True  True]]
    

    ps-I would say that the title of the question doesn't quite capture the essence of your question