[Tutor] Automaton/transitional grammar query

Dave Angel davea at ieee.org
Mon Oct 12 17:06:50 CEST 2009


kevin parks wrote:
>
> On Oct 12, 2009, at 8:02 PM, Dave Angel wrote:
>
>> Often, when a combination of existing stdlib collection types gets 
>> too confusing, it's time to consider classes and objects.  Not 
>> necessarily to make the program "object oriented," but to make the 
>> program data structure understandable.
>
>
> That's sage advice.... I just dislike and resist OO. But i do 
> eventually need to make steps in that direction.
>
>
>
Well, an object is just a container, and a class is standardized way to 
make similar objects.  But in Python, there are few restrictions on what 
you can do with such objects.  So just start with data and without 
inheritance, which makes it very simple to understand.  Then C++ would 
commonly call it struct, instead of class, and in fact struct already 
existed in C, which is not object oriented.


class ProbableValue(object):
    def __init__(self, probability, newvalues):
        """probability is a float   0.0<=prob < 1.0.   newvalues is a 
tuple of one or more values"""
        self.probability = probability
        self.newvalues= newvalues


Is all you really need.  Now you can create objects of this class by 
simply saying:

  val1 = ProbableValue(.3, (1, 4))
  val2 = ProbableValue(.5, (12,))

and you can access the data by     val1.probability,     or   val2.newvalues

Now you can initialize the original rules table by something like:

rules = {}
val1 = ProbableValue(.3, (1,4))
val2 = ProbableValue(.25, (5))
val3 = ProbableValue(.45, (1,3,5))      #note that .3 + .25 + .45 == 1
rules[1] = (val1, val2, val3)    #one dictionary rule

and repeat those last four lines as needed to build up the dictionary


Can you see where you might go from here?

DaveA


More information about the Tutor mailing list