Search code examples
pythonpandasnumpyflip-flop

Is it possible to implement RS flip flop truth table in Python?


I am new to Python. i am using Spyder (pandas and numpy) to run an algorithm for data analysis. This requires implementation of an RS flip flop on two variables in the data. something like this in C:

((R_b) != FALSE) ? (*(State_pb) = FALSE) : (((S_b) != FALSE) ? (*(State_pb) = TRUE) : *(State_pb));

Here R_b is the R input to the flip-flop and S-b is the S input. Note the use of pointer to the previous state of the flip flop to retain previous state . Could this be implemented in Python as well?


Solution

  • Here is a function that's a fairly direct translation of your C code, using Python's conditional operator.

    from itertools import product
    
    def flipflop(state, r, s):
        return False if r else (True if s else state)
    
    # test
    
    print('state : r, s -> new_state')
    for state, r, s in product((False, True), repeat=3):
        print('{!s:5} : {!s:5}, {!s:5} -> {!s:5}'.format(state, r, s, flipflop(state, r, s)))
    

    output

    state : r, s -> new_state
    False : False, False -> False
    False : False, True  -> True 
    False : True , False -> False
    False : True , True  -> False
    True  : False, False -> True 
    True  : False, True  -> True 
    True  : True , False -> False
    True  : True , True  -> False
    

    Note that neither this code nor your C code correctly handle the forbidden r == s == True input.