Creating Linked Lists in Python

Tim Chase python.list at tim.thechases.com
Sat Mar 21 13:03:39 EDT 2009


>>>    transitions = {
>>>      # values are tuples of (newstate, transition_function)
>>>      STATE_A: [
>>>        (STATE_B, lambda x: x > 5),
>>>        (STATE_C, lambda x: x > 10),
>>>        (STATE_D, lambda x: x > 100),
>>>        ],
>>>      STATE_B: [
>>>        (STATE_A, lambda x: x < 5),
>>>        (STATE_C, lambda x: x > 10),
>>>        ],
>>>      STATE_C: [
>>>        (STATE_B, lambda x: x < 10),
>>>        (STATE_D, lambda x: x > 100),
>>>        ],
>>>      STATE_D: [],
>>>      }
>>
>> And if you don't mind me asking. How do you invoke lambda from
>> transitions?
> 
> 
> Disregard that. I think I figured it out.
> 
> If you had something like...
> 
>>>> transitions = {1: [2, lambda x: 2*x]}
> 
> You would probably call it like...
> 
>>>> transitions[1][1](4)
> 8

I tend to use them with tuple assignment which I find reads more 
cleanly than directly indexing:

   for input in source():
     available_states = []
     for new_state, function in transitions[state]:
       if function(input):
         available_states.append(new_state)
     do_something(available_states)

-tkc







More information about the Python-list mailing list