Home > OS >  Replace nested for loop with list comprehension in Python
Replace nested for loop with list comprehension in Python

Time:08-25

Given a list of integers c, I want to perform the following:

  1. Count how many elements of c are less than index i, where i is from 0 to len(c). For example: c=[1, 0, 2, 1], then the output to the above will be b=[1, 3, 4, 4] because only the 1 element of c is less than or equal to i=0, then there are 3 elements of c less than or equal to i=1, then there are 4 elements of c less than or equal to i=2, and lastly there are 4 elements of c less than or equal to i=3.

  2. Find a=[b[0] b[1]-1 b[2]-2 ... ]

  3. Find math.prod(a)


I manage to do it using nested for loops, but I am learning the list comprehensions and want to transform them into nested for loops inside the list comprehensions.

#this code works
def solve(c):
    a=1
    for i in range(len(c)):
        a=a*(sum(element<=i for element in c)-i)
    return(a)
#input c=[1, 0, 2, 1]
#output 4

But this one fails:

$this code does not work
def solve(c):
    a=1
    return([(a=a*(sum(element<=i for element in c)-i)) for i in range(len(c))])

CodePudding user response:

[[item for item in c if item <= ind] for ind in range(len(c))] give you the list of item that are < for the index.

[len([item for item in c if item <= ind]) - ind for ind in range(len(c))] will give you your second point.

  • Related