0

I haven't found an answer for this. Sorry if it's common. I'm kinda newbie.

I'm creating for loops like this (to create a dictionary script):

for i1 in range(len(n)):
    for i2 in range(len(n)):
        for i3 in range(len(n)):
            for i4 in range(len(n)):
                for i5 in range(len(n)):
                    for i6 in range(len(n)):
                        word = n[i1] + n[i2] + n[i3] + n[i4] + n[i5] + n[i6]

And I would like to create a recursive version in which I could choose the number of loops. So if I have a bigger word, it'll loop enough. And I will need the pointer variables later (for that word creation), so I thought in using dynamic variables[Don't know if its possible, though]

n = len(string)
def loop(n): #'n' is a string and the length would be the number of recursions
    if n > 0:
        var1 [defining my dynam. var]
        for var1 in range(len(string)):
            loop(n-1)
    else:                
        return word() #I guess I know how to code this one

So.. I want to have variables like var1, var2, var3 etc. to put in my for. Any help/directions is welcome! Thanks in advance!

Edit: Sorry for the trouble trying to understand it. Ok, I'm not sure if I should do this (should I erase the above?). I managed to create a iterative version of what I want: To input a string and print a list with all the possible combinations with those characters.

With the following function I got the output I wanted, but it is limited to 6 char. I guess with a recursive version it would be able to get any input and create as many loops as needed. [Better explained now?]

My actual script is as follows (I do know that there are better ways of doing the filter/checks):

def rec():
    word = ""
    txtfile = open(arq,'w') #arq is the string input + .txt
    s=0 #Counts the number of words writen
    t=0 #tests if the word exists
    for i1 in range(len(n)):
        for i2 in range(len(n)):
            for i3 in range(len(n)):
                for i4 in range(len(n)):
                    for i5 in range(len(n)):
                        for i6 in range(len(n)):
                            #This is a filter for not repeating the same character in a word
                            if not (i1 == i2 or i1 == i3 or i1 == i4 or i1 == i5 or i1 == i6 \
                                or i2 == i3 or i2 ==i4 or i2 == i5 or i2 ==i6 \
                                or i3 == i4 or i3 == i5 or i3 == i6 \
                                or i4 == i5 or i4 == i6 \
                                or i5 == i6 ):
                                word = n[i1] + n[i2] + n[i3] + n[i4] + n[i5] + n[i6]
                                txtfile.close()
                                data_file = open(arq)
                                #This one search for the word in the file, for not having duplicates
                                for line in data_file:
                                    if line == word + "\n" :
                                        t = 1
                                    else:
                                        pass
                                data_file.close()
                                if not t == 1:
                                    s+=1
                                    txtfile = open(arq,'a')
                                    txtfile.writelines(word + "\n")
                                t=0

    print ("Number of words writen:",s)

My output for "eeeeee" is just that one string, just as example. And the first ones for badges is: badges badgse badegs badesg badsge badseg bagdes bagdse bageds bagesd bagsde bagsed baedgs

Thanks a lot for the feedbacks!

ramtoo
  • 130
  • 1
  • 2
  • 9
  • 2
    If you simply need to generate all possible strings, the pythonic way to accomplish this would be [this](http://stackoverflow.com/questions/7074051/is-there-any-best-way-to-generate-all-possible-three-letters-keywords) solution. – malloc47 Feb 17 '12 at 16:39
  • It's hard to understand what you are trying to do. Can you give a better definition of the problem you want to solve? – Dan Gerhardsson Feb 17 '12 at 16:40
  • I know you want a recursive version, but I'd use `itertools.combinations_wit_replacement` instead. Standard and much easier/faster :) – Ricardo Cárdenes Feb 17 '12 at 16:42
  • 2
    I don't understand. You're rewriting over the word variable each time. The only iteration that matters is the last one. That is, you could change the code at the top to read `word = n[len(n)-1] * 6`. All these loops make no sense to me. – Kris Harper Feb 17 '12 at 16:43
  • Could this be someone whose first language was Erlang or Haskell and now is learning imperative style? – wberry Feb 17 '12 at 22:07
  • Also, if this is Python 2.x, I'd replace those `range`'s with `xrange` - otherwise you're creating a list each time you recurse down. As far as I can tell, this doesn't happen in Python 3.x. – Hooked Feb 19 '12 at 04:15

2 Answers2

0

Im not 100% sure of what your trying achieve here. In your current code what are you trying to do?

For example what would happen it you had the word "CAT" you would get the following results:

CCC,CCA,CCT,CAC,CAA,CAT,CTC,CTA,CTT

ACC,ACA,ACT,AAC,AAA,AAT,ATC,ATA,ATT

TCC,TCA,TCT,TAC,TAA,TAT,TTC,TTA,TTT

that would be the result of word for every iteration (at thats only if you print after every assignment) but as stated word would ultimatley equal TTT.

Can you please expand on what you want the final result to be.

Also there are much better ways in python for handling strings take a look at this documentation for more information http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange

Regards Joe

Joe Doherty
  • 3,778
  • 2
  • 31
  • 37
0

We've made a script creating all the permutation in a list in class, it can help you:

class Permutations :
    def __init__( self , blist ) :
        self.alist=blist
        self.permut_list = []
        self.permutation(len(self.alist))

    def swap(self , blist , i , j ) :
        blist[i], blist[j] = blist[j] ,blist[i]

    def permutation(self, taille):
        if taille == 1 :
            self.tmp = self.alist[:]
            self.permut_list.append(self.tmp)
        else :
            for i in range(taille) :
                self.swap(self. alist , i , taille −1)
                self.permutation(taille −1)
                self.swap(self.alist , i , taille −1)

    def __repr__(self):
        repre = """"""
        for i in self.permut_list:
             repre += ''.join(i)+"\n"
        return repre

This code is constructed in a recursiv way, it put the ith character of the list at the end, with swap, and then permut the rest while the len of the rest is greater than 1, when it is, it replace t ith element at his correct position and go to the next element.

And you can call this class with:

text = "abc"
text_list = []
for i in range(len(text)):
    text_list.append(text[i])
permu_text = Permutations(text_list)
print permu_text
lpostula
  • 588
  • 1
  • 6
  • 22