Home > database >  How to find distinct values that occur to right of the index i
How to find distinct values that occur to right of the index i

Time:09-25

Given Arr=[7,7,3,2,3] The number of distinct elements that occur to the right of index i will be ans = [2,2,1,0,0]

CodePudding user response:

from collections import Counter
from typing import List

ll: List = [7,7,3,2,3] #your list
idx: int = 3 # your index value


Counter(ll[:idx]) 

OUTPUT:

Counter(ll[:idx])

CodePudding user response:

Get the length of the set of elements in the array minus the element on the right of each index using a list comprehension on the range of indexes.

Solution based on your sample result:

[len(set(Arr)-set(Arr[:i 1])) for i in range(len(Arr))]

[2, 2, 1, 0, 0]

Solution based on your stated problem:

[len(set(Arr[i 1:])) for i in range(len(Arr))] 

[3, 2, 2, 1, 0]
  • Related