lundi 3 mai 2021

Recursion in for loops, Python

I have this code that in the function, it looks for all the permutations of a given string, then it looks for another string if any of these permutations are found.

Studying the recursion a little, I do not fully understand why the variable "i" sometimes subtracts when the recursion is executed (I commented the part that i did'nt understand).

Im new to the recursion concept and im trynna to understand it a little bit more.

Here's the code: import math

def permute(data, i, length,s):
    global d
    l=[]
    if i==length: 
        if d==1+math.factorial(length): #para que no vuelva repetir
            return None
        d=d+1
        l.append(''.join(data))
        if s.find(l[0]) != -1: 
            d=1+math.factorial(length) 
            return print('YES')
            
    if d == math.factorial(length):
        d=1+math.factorial(length)
        return print('NO')
        
    else: 
        for j in range(i,length): 
            #swap
            data[i], data[j] = data[j], data[i] 
            print(data,i,j) # I'd realize here that 'i' is substracting or adding 
            permute(data, i+1, length,s) 
            data[i], data[j] = data[j], data[i] 
            print(i)
se=[]
n1=[]
data1=[]
t = int(input())
if t >=1:
    if t <=100:
        for i in range(t):
            pattern=input()
            if len(pattern) >=1:
                if len(pattern) <=100:
                    n = len(pattern)
                    data = list(pattern)
                    data1.append(data)
                    n1.append(n)
                    search = input()
                    if len(search) >=1:
                        if len(search) <= 100000:
                            se.append(search)
for k in range(t):
    d=0
    permute(data1[k], 0, n1[k],se[k])

Here's an input example:

1 #number of words to permute
door #word to permute
closerood #word to search permutations

Here's the output example:

data, i,j

    ['d', 'o', 'o', 'r'] 0 0
    ['d', 'o', 'o', 'r'] 1 1
    ['d', 'o', 'o', 'r'] 2 2
    ['d', 'o', 'o', 'r'] 3 3
    ['d', 'o', 'r', 'o'] 2 3
    ['d', 'o', 'r', 'o'] 3 3
    ['d', 'o', 'o', 'r'] 1 2
    ['d', 'o', 'o', 'r'] 2 2
    ['d', 'o', 'o', 'r'] 3 3
    ['d', 'o', 'r', 'o'] 2 3
    ['d', 'o', 'r', 'o'] 3 3
    ['d', 'r', 'o', 'o'] 1 3
    ['d', 'r', 'o', 'o'] 2 2
    ['d', 'r', 'o', 'o'] 3 3
    ['d', 'r', 'o', 'o'] 2 3
    ['d', 'r', 'o', 'o'] 3 3
    ['o', 'd', 'o', 'r'] 0 1
    ['o', 'd', 'o', 'r'] 1 1
    ['o', 'd', 'o', 'r'] 2 2
    ['o', 'd', 'o', 'r'] 3 3
    ['o', 'd', 'r', 'o'] 2 3
    ['o', 'd', 'r', 'o'] 3 3
    ['o', 'o', 'd', 'r'] 1 2
    ['o', 'o', 'd', 'r'] 2 2
    ['o', 'o', 'd', 'r'] 3 3
    ['o', 'o', 'r', 'd'] 2 3
    ['o', 'o', 'r', 'd'] 3 3
    ['o', 'r', 'o', 'd'] 1 3
    ['o', 'r', 'o', 'd'] 2 2
    ['o', 'r', 'o', 'd'] 3 3
    ['o', 'r', 'd', 'o'] 2 3
    ['o', 'r', 'd', 'o'] 3 3
    ['o', 'o', 'd', 'r'] 0 2

Aucun commentaire:

Enregistrer un commentaire