ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Meta programming for generating combination (anagram) of a string
Submitter: bussiere bussiere (other recipes)
Last Updated: 2008/03/24
Version no: 1.1
Category: Algorithms

 

Not Rated yet


Description:

making a program that will write a program to find all the combinaison of a string

Source: Text Source

import string
#the string that we want to test the combination
strng = "131"
#the size of the string
size = len(strng)
#the string that will contain the program generated
prog = ""
#here we will stock the tabulation
tab = ""
#the variable that will count and b used for the meta variable
i = 0
#the first str meta variable must be initialised
str0 = strng
# a meta variable that will stock the sum of the l meta variable
result = ""


while i < size :
    #we generate a for with l in str meta variable string
    prog+= """%sfor l%s in str%s:\n"""%(tab,i,i)
    if (i+1 != size):
        #then we substract one letter in the sequence
        prog+= """%sstr%s = string.replace(str%s,l%s,"",1)\n"""%(tab+"    ",i+1,i,i)
    # here we stock the sum of the meta variable ex : l0+l1 etc ...
    result += "l%s+"%i
    prog += "%sprint %s\n"%(tab+"    ",result[0:len(result)-1])
    #at the end of the loop
    tab += "    "
    i = i +1

#we print the program
print prog
#we execute the program
exec(prog)
print "the end"

#please note that there could be some doublon in the resultat

Discussion:

Some times it's useful to test all the combination of a string and using meta programmation is truly a good exercice. It develops a different way of thinking about algorythm. I did it because for a math problem i had to find all the possibility of a sequence of number



Add comment

No comments.



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Treat the Win32 Registry ...

4. Watching a directory ...

5. Union Find data structure

6. Function Decorators by ...

7. MS SQL Server log monitor

8. Table objects with ...

9. wx twisted support using ...

10. More accurate sum




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.