0

I try to avoid nested loops in Python. In general, I manage to do so by using some itertools utility, the zip function, etc. However, there is still one case for which I have not been able to eliminate the classic nested loop structure: the case where, while iterating through a list, you want to append elements to that same list, and you want those elements to be part of the loop.

Here is an example:

a = [1,5,21]

for i1, val1 in enumerate(a):
  for i2 in range(i1+1, len(a)):
    val2 = a[i2]
    if (val1+val2)%3==0 and abs(val1-val2)<30:
      a.append(val1+val2)
    
print("final", a) #[1, 5, 21, 6, 27, 33, 60, 93]

Can someone help me rewrite this without using a nested loop?

2
  • 6
    I'd say you can't and that isn't a problem at all, sometimes you need 2 nested loops, sometimes 3, that' ok Commented May 15, 2021 at 21:25
  • Why do you avoid nested loops? Any specific reason? Commented May 15, 2021 at 21:51

2 Answers 2

1

Here is a solution with a while loop.

expected = [1, 5, 21, 6, 27, 33, 60, 93]
a = [1,5,21]

val1, val2 = a[0], a[1]
idx = 0
while abs(val1-val2) < 30: 
    if (val1 + val2) % 3 == 0:
        a.append(val1+val2)
    idx += 1
    val1, val2 = a[idx], a[idx+1]
a == expected # True
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect.
0

Is there any specific reason, you are not going with nested loop approach?

However, under the assumption you want to try something apart from loop. I’ve created similar program using recursion. Hope this helps! 😊

def fn_recur(a,i1,i2):
    val1 = a[i1]
    val2 = a[i2]
    if (val1+val2)%3 == 0 and abs(val1-val2) < 30:
      a.append(val1+val2)
    if(i2+1 < 3):
        i2 = i2+1
    elif(i1+2 < len(a)):
        i1 = i1+1
        i2 = i1+1
    else:
        print(a)
        return a
    fn_recur(a,i1,i2)
fn_recur([1,5,21],0,1)
#output [1, 5, 21, 6, 27, 33, 60, 93]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.