user17096936
user17096936

Reputation:

one element from list pair with other elements

get one element from list and print it with all next elements according to condition.

l = [0,1,2,3]
count = 0
def ab():   
    for index, elem in enumerate(l):
        global count 
        if (index+1 <= len(l) and count+1 < len(l)):
            print('finding from', str(l[count]) ,'to',l[index])         
            if index == len(l)-1:
                count += 1 
                print('pass',count)
                ab()
ab()

output of above function

pass 0
finding from 0 to 0
finding from 0 to 1 # expect pass 0 to start from here 
finding from 0 to 2
finding from 0 to 3

pass 1
finding from 1 to 0
finding from 1 to 1
finding from 1 to 2  #  expect to start from here  
finding from 1 to 3
pass 2
finding from 2 to 0
finding from 2 to 1
finding from 2 to 2
finding from 2 to 3  #  expect to start from here

what i expect - get element from list and pair with values after it not before

pass 0
finding from 0 to 1 
finding from 0 to 2
finding from 0 to 3
pass 1
finding from 1 to 2         
finding from 1 to 3
pass 2
finding from 2 to 3  

Upvotes: 0

Views: 158

Answers (1)

user2668284
user2668284

Reputation:

You've made this more complicated than it needs to be. You just need a loop within a loop like this:

L = [0,1,2]

for i in range(len(L)):
    print(f'pass {i}')
    for j in range(i, len(L)):
        print(f'finding from {i} to {j+1}')

Upvotes: 1

Related Questions