Replace nested for loop with list comprehension in Python
Question:
Given a list of integers c
, I want to perform the following:
-
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
.
-
Find a=[b[0] b[1]-1 b[2]-2 ... ]
-
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))])
Answers:
[[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.
Given a list of integers c
, I want to perform the following:
-
Count how many elements of
c
are less than indexi
, wherei
is from0
tolen(c)
.
For example:c=[1, 0, 2, 1]
, then the output to the above will beb=[1, 3, 4, 4]
because only the1
element ofc
is less than or equal toi=0
, then there are3
elements ofc
less than or equal toi=1
, then there are4
elements ofc
less than or equal toi=2
, and lastly there are4
elements ofc
less than or equal toi=3
. -
Find
a=[b[0] b[1]-1 b[2]-2 ... ]
-
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))])
[[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.