带动态指针的递归 for

发布于 2025-01-06 11:01:12 字数 2952 浏览 2 评论 0 原文

我还没有找到这个问题的答案。抱歉,如果这很常见。我有点新手。

我正在创建这样的 for 循环(以创建字典脚本):

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]

我想创建一个递归版本,在其中我可以选择循环数。所以如果我有一个更大的单词,它就会足够循环。 稍后我将需要指针变量(用于创建该词),所以我考虑使用动态变量[但不知道是否可能]

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

所以..我想要像 var1、var2、var3 等变量放入我的。 欢迎任何帮助/指示! 提前致谢!

编辑: 很抱歉在尝试理解它时遇到麻烦。 好吧,我不确定我是否应该这样做(我应该删除上面的内容吗?)。我设法创建了我想要的迭代版本:输入一个字符串并打印一个列表,其中包含这些字符的所有可能组合。

通过以下函数,我得到了我想要的输出,但它仅限于 6 个字符。我想使用递归版本它将能够获取任何输入并根据需要创建尽可能多的循环。 [现在更好解释了?]

我的实际脚本如下(我确实知道有更好的方法来进行过滤/检查):

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)

我的“eeeeee”输出只是一个字符串,只是作为示例。 第一个徽章是: 徽章 巴德塞 徽章 巴德斯格 徽章 巴德塞格 巴格德斯 巴格德塞 袋装的 巴格斯德 巴格德 袋装的 baedgs

非常感谢您的反馈!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黎歌 2025-01-13 11:01:12

我们制作了一个脚本,在类中创建列表中的所有排列,它可以帮助您:

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

这段代码以递归方式构造,它将列表的第 i 个字符放在末尾,进行交换,然后排列其余的当其余元素的 len 大于 1 时,它会在正确的位置替换第一个元素,然后转到下一个元素。

您可以使用以下方式调用此类:

text = "abc"
text_list = []
for i in range(len(text)):
    text_list.append(text[i])
permu_text = Permutations(text_list)
print permu_text

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
深海不蓝 2025-01-13 11:01:12

我不能 100% 确定您在这里尝试实现的目标。在您当前的代码中您想做什么?

例如,如果您有单词“CAT”,您将得到以下结果:

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

这将是每次迭代的单词结果(仅当您在每次分配后打印时),但作为所说的单词最终等于 TTT。

您能否详细说明您想要的最终结果。

python 中还有更好的方法来处理字符串,请查看此文档以获取更多信息 http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange

问候

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文