Given a list of integers c, I want to perform the following:
Count how many elements of
care less than indexi, whereiis from0tolen(c). For example:c=[1, 0, 2, 1], then the output to the above will beb=[1, 3, 4, 4]because only the1element ofcis less than or equal toi=0, then there are3elements ofcless than or equal toi=1, then there are4elements ofcless than or equal toi=2, and lastly there are4elements ofcless 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))])
math.prodat all. Start smaller, try makingbwith a list comprehension or converting[1, 2, 2, 1]to4withmath.prod, then put the pieces together.b=[sum(element<=i for element in c) for i in range(len(c))]a=[(b[i]-i) for i in range(len(c))]and thenreturn(math.prod(a)).