dimanche 13 juin 2021

How to compact the code and how to extend the code for more items [closed]

In the list, x is user input. The no of elements is higher than or equal to 4. list y is fixed and already given. (In the following case, no of elements is 5. I want to find 5 elements from the list y those satisfying the arguments) How can I extend this code to any no of input elements? And how can I make this code simple without repeating "if", "for" and some other statements?

x = [2, 4, 5, 7] y = [4, 5, 8, 9.4, 10, 14, 3, 20, 4.5]

x1 = [(i,j) for i in x for j in y]

values_of_z = []

for (a1, b1) in x1:

for (a2, b2) in x1:

    for (a3, b3) in x1:

        for (a4, b4) in x1:

            if a1 > a2 > a3 > a4:

                if b1 > b2 > b3 > b4:

                    if abs(((a1-a2)/(a3-a4))-((b1-b2)/(b3-b4))) < (.001*abs((b1-b2)/(b3-b4))):

                        z = [b1, b2, b3, b4]

                        values_of_z.append(z)

print(values_of_z)

Aucun commentaire:

Enregistrer un commentaire