Home > OS >  Python Nested Loops questions python3.0
Python Nested Loops questions python3.0

Time:09-12

I'm trying to write a nested loop that calculates (x y)^2 for every value of y where the outer loop should print (x y)^2. Here is my code so far:

x = [2,4,6,8,10,12,14,16,18]

y = [10,8.25,7.5,7,6.5,7,7.5,8.25,10]


for i in range(0 , len(x)):
# nested
    
    #for j in range(0, len(y)):
    for j in range(0, len(y)):
            
    
        print( (x[i]   y[j])**2)
        

My output keeps printing repeated values like so:

144
105.0625
90.25
81
72.25
81
90.25
105.0625
144

CodePudding user response:

Maybe you could try this:

NB - it works by zipping through two lists (same size) and do the math. If the size is unequal, then you should try zip_longest with some other default number (for this shorter list).


outs = []

for a, b in zip(x, y):
    outs.append(pow((a b), 2))

Example 2: one list is longer -

x = [2,4,6,8,10,12,14,16,18, 20]       # adding 20 as extra number

y = [10,8.25,7.5,7,6.5,7,7.5,8.25,10]

from itertools import zip_longest #(a, b, fillvalue=0)

outs = []

for a, b in zip_longest(x, y, fillvalue=0):
    outs.append(pow((a b), 2))

CodePudding user response:

Without using any library:

print([((x[i] if i < len(x) else 0)   (y[i] if i < len(y) else 0))**2 for i in range(max(len(x), len(y)))])

OUTPUT

[144, 150.0625, 182.25, 225, 272.25, 361, 462.25, 588.0625, 784]
  • Related