0

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))])
4
  • 1
    Having an assignment inside the list comprehension doesn't make sense, and you don't seem to be using math.prod at all. Start smaller, try making b with a list comprehension or converting [1, 2, 2, 1] to 4 with math.prod, then put the pieces together. Commented Aug 24, 2022 at 15:52
  • @jonrsharpe b=[sum(element<=i for element in c) for i in range(len(c))] Commented Aug 24, 2022 at 15:59
  • Great, keep going, step by step. Commented Aug 24, 2022 at 16:03
  • @jonrsharpe thanks, I got the answer now. a=[(b[i]-i) for i in range(len(c))] and then return(math.prod(a)). Commented Aug 24, 2022 at 16:10

1 Answer 1

1

[[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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.