Home > Software design >  Using methods inside list comprehension with multiple for loops and algorithm
Using methods inside list comprehension with multiple for loops and algorithm

Time:10-29

I'm practicing list comprehension in python. Trying to create a list of lists specifying some conditions. So i wrote this program:

def perm(x,y,z,n):
    a = range(x y z)
    b = []
    for i in a:
        for j in a:
            for k in a:
                if 0 <= i <= x and 0 <= j <= y and 0 <= k <= z and i j k != n:
                    b.append([i,j,k])
    return b
print(perm(1,1,2,3))

[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 2]]

Which is exactly the output i want. but if i try it using list comprehension:

return ([b.append(i) for i in a for j in a for k in a if 0 <= i <=x and 0 <= j <= y and 0 <= k <= z and i k j != n])
Or
return b.append[(i for i in a for j in a for k in a if 0 <= i <=x and 0 <= j <= y and 0 <= k <= z and i k j != n])

It returns a list of None or None.

How do i fix this? Also I'm looking into algorithms and trying to understand. I've read some articles but got confused. I've had questions like how do i calculate the efficiency of any given program like this one? Is there a standard way? How do i know if i have to change my code in order to get the best result? If someone can break it down for me in the most basic terms or if the topic is too big to cover then pointing towards some resources would be so much of a help. Thanks!

CodePudding user response:

list.append does return None. What you would have to do:

def perm(x,y,z,n):
    a = range(x y z)
    return [[i,j,k] for i in a for j in a for k in a if 0 <= i <= x and 0 <= j <= y and 0 <= k <= z and i j k != n]
   

In general, the following two are equivalent (the variable names are just random, they have nothing to do with your example):

lst = []
for a in x:
    for b in y:
        if c:
            lst.append(d)

lst = [d for a in x for b in y if c]
  • Related