1

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?

VinayakR
  • 33
  • 1
  • 5

1 Answers1

1

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.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
  • Thanks for the snippet! It does need the initial state then to begin with. And about the r==s==True , it is ensured in the system design that it doesn't occur. – VinayakR Dec 05 '16 at 14:33
  • @VinayakR The Python version has to work a little differently to the C version, since Python doesn't have pointers, per se. In fact, it doesn't have C-like variables. Please see [Other languages have "variables", Python has "names"](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables). – PM 2Ring Dec 05 '16 at 15:10
  • @VinayakR I guess you _could_ do this using a custom class to hold the state, with a method that handles the updating; the class constructor would initialise the flip-flop to a known state. It would only be a few lines of code, but IMHO that's probably overkill for this application. – PM 2Ring Dec 05 '16 at 15:11
  • You are right. It would be overkill. I think, for now, I can just initialize the state to 0 or use proper indexing in the data to assign the previous state . Thanks for the help. PS: the article u shared is awesome – VinayakR Dec 05 '16 at 15:35