I am trying to create a program which outputs all permutations of a string of length n whilst avoiding a defined substring, of length k. For example:
Derive all possible strings, up to a length of 5 characters, that can be generated from an initial empty set, which can either go to A or B, but the string cannot contain the substring “AAB” which is not allowed.
i.e. base case of [""] is the empty set.
The dictionary would be – A:{A}, B:{A,B}
From the empty set we can go to A, and we can go to B. We can not go to a B after an A but we can go to an A after a B. And both A and B can access themselves
example output: a,b,aa,bb,ba,aaa,bbb,baa,bba … etc
How would I go about prompting a user to define a substring to avoid, and from that generate a dictionary which abides to these rules?
Any help or clarification would be greatly received.
Regards,
rkhad
The
itertoolsmodule has a useful method calledpermutations():(from http://docs.python.org/library/itertools.html#itertools.permutations)
List comprehensions provide an easy way to filter generated permutations like this, but beware that if you are storing permutations of a large string that you will quickly get a very large list. You may want to therefore use a
setto whittle down your list to non-duplicates. Also, you may find the functionsortedto be useful if you intend to iterate through your “paths” in lexicographic order. Lastly, theinoperator, when applied to strings, checks for a substring (x in ychecks ifxis a substring ofy).I’m working on my dissertation right now too, in the area of Formal Languages. The concept of substring membership can be represented by a very simple regular grammar which corresponds to a deterministic finite automaton. To jog your memory:
http://en.wikipedia.org/wiki/Regular_grammar
http://en.wikipedia.org/wiki/Finite-state_machine
When you look into these you will find that you need to somehow keep track of the current “state” of your computation if you want it to have different “dictionaries” at different phases. I encourage you to read the wikipedia articles, and ask me some follow-up questions as I’d be happy to help you work through this.