2

I have a code snippet like this in Python:

#list_1 have a previous value that we dont know
n = 40 #This value can change

list_2 = [0, 0, 0, 0]

#We are trying all the values possibles for 4 positions and 40 different numbers

for a in range(n):
    for b in range(n):
        for c in range(n):
            for d in range(n):
                list_2[0] = a
                list_2[1] = b
                list_2[2] = c
                list_2[3] = d
                if list_1 == list_2:
                   print("Ok")

I want to change the nested for loops into something simpler; what can I do?

2 Answers 2

2

Use itertools.product() with the repeat parameter to reduce the amount of nesting:

from itertools import product

for a, b, c, d in product(range(n), repeat=4):
    list_2 = [a, b, c, d] # Can condense the assignments into one line as well.
    if list_1 == list_2:
        print("Ok")

You can generalize this for lists of size greater than 4 by doing the following:

from itertools import product
x = # length of lists to find matches for
for item in product(range(n), repeat=x):
    list_2 = list(item)
    if list_1 == list_2:
        print("Ok")
Sign up to request clarification or add additional context in comments.

2 Comments

Thants for the answer, but I have another question. What happen if de "repeat" it is a variable too? I can code "repeat=x" but, how i do the assignments then?
Edited answer. Let me know if you have any other questions.
0

A few ways, some using itertools.product...

for [*list_2] in product(range(n), repeat=4):
    if list_1 == list_2:
        print("Ok")
list_2 = []
for list_2[:] in product(range(n), repeat=4):
    if list_1 == list_2:
        print("Ok")
if tuple(list_1) in product(range(n), repeat=4):
    print("Ok")
if list_1 in map(list, product(range(n), repeat=4)):
    print("Ok")
if len(list_1) == 4 and all(x in range(n) for x in list_1):
    print("Ok")
if len(list_1) == 4 and set(list_1) <= set(range(n)):
    print("Ok")

2 Comments

Thanks !!!, the code works fine, but I forgot to say that the repeat its a variable too, so, how can I get the assignements?
@Daxan Just replace 4 with your variable?

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.