If i mention the word ‘state machine’ , most people would go for state machine design. So i’d like to simplify the case to focus on the point.
Suggested here is a text flow, it’s very long or it’s frequently brought to current stage.
Each time I process a single character from the sequence and decide what the next state is. Here are two solutions:
textflow = iter(text)
endFlag = False
while True:
process()
if endFlag:break
then the process method would be like this
def process0():
for x in textflow:
do something
if condition1:
process = process1
break
elif cond2:
process = process2
break
def process1():
for x in textflow:
do something
if cond0:
process = process0
break
elif cond2:
process = process2
break
...
or
for x in text:
process(x)
then the process method would be like this
def process0(x):
do something
if cond1:
process = process1
elif cond2:
process = process2
def process1(x):
do something
if cond0:
process = process0
elif cond2:
process = process2
....
In the first solution, each process method does the iteration by its own way and ends the process until the state is changed. In the second, the main loop does the iterations and each time process would be called.(map() could be use, but since the process would be changed everytime, it doesn’t help.)
The state change would be like this:
0 1 2 1 0 2 1 0 1 2 0 1 2 0 ....
or like this:
0 0 0 0 0 ...many 0 .. 0 1 ...many 1 ... 1 2......2 1 ..... 1
A more common case would be:
0 1 1 1 1 1 0 0 2 1 1 1 1 2 0 2 3 1 1 1 1 3 1 1 1 2 0 ....
I need an advisor to tell me which solution is more efficient.
It will mostly depend on how many items you want to process, as function calls are expensive. If you have a large number of items, then embedding the loop inside the function is the better option. If it’ll only iterate over a few items, I usually go with whichever is clearest in expressing intent.