random / lists

Russell Blau russblau at hotmail.com
Mon Aug 16 16:34:25 CEST 2004

"M. Clift" <noone at here.com> wrote in message
news:cformj$vso$1 at newsg2.svr.pol.co.uk...
> Hi Wes,
> Thanks for responding.
> What I want is a system that controls the direction in a generated list.
> the user selects a number a letter is choosen for each number from at
> from an array. That's fine and easy to do. The hard part is, is that no
> letter can be repeated with only one letter interveining and the letters
> only follow each other under certain rules.
>  These being :
> 1. 'a' can be followed by any letter
> 2. 'b' can only be followed by 'c'
> 3. 'c' can be followed by 'a' or 'd'
> 4 'd' can be followed by 'a' or 'c'
> Really it doesn't matter what these rules are for the time being it's just
> working out a way to control the outcome of a list of unknown size.

How about if you define a dictionary mapping each letter to a list of the
letters that are allowed to follow it, then use random.choice() to pick one
member of the list.  For example,

mapping = {'a': ['b', 'c', 'd'], 'b': ['c'], 'c': ['a', 'd'],
           'd': ['a', 'c']}

then after you added the last letter to l, you could just do

allowed = mapping[l[-1]][:]    # nneds to be a copy because it may get
if l[-2] in allowed:           # no letter can appear two out of three

Of course, this doesn't account for every case (like, it won't work if l is
the empty list), and it may not satisfy all your desired rules, but it's a

I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.

More information about the Python-list mailing list