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))])
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.