Skip to content Skip to sidebar Skip to footer

Count Number Of Element In A Array That Is Less Than The Element In Another Array

I am not sure whether this is the right place to ask this question, but I am struggling to get to the right answer myself. I have done a programming test and I can not figure why m

Solution 1:

Pseudocode:

Sort number array
Sort maximum arraycreate a list counts
for max elem in max array
      find first elem in number array that is greater than or 
      equal to max elem and save its (index+1) in counts

So now counts will be a parallel array to the sorted number array. At index 0 of counts we have the number of elements smaller than the number at index 0 of max array.

You can do the below if you need your data in a dictionary form (as you did in your solution) as opposed to two parallel lists.

Set index to 0formax elem inmax array:
    dictionary[max elem] = counts[index]
    index += 1

Note you can use enumerate above but I wasn't sure you knew about it yet so I tried to give the simplest solution.

Solution 2:

Here's a simplified version of what you need to do

nums = [1, 4, 2, 4]
maxes = [3,5]

result = [0]*len(maxes)
for index, max_val in enumerate(maxes):
    for num in nums:
        if num <= max_val:
            result[index] += 1

print(result)

Solution 3:

I'd just write this as

[sum(1forxin nums if x < m) formin maxes]

Demo:

>>>nums = [2, 10, 5, 4, 8]>>>maxes = [3, 1, 7, 8]>>>>>>[sum(1for x in nums if x < m) for m in maxes]
[1, 0, 3, 3]
>>>>>>nums = [1, 4, 2, 4]>>>maxes = [3, 5]>>>>>>[sum(1for x in nums if x < m) for m in maxes]
[2, 4]

It's readable, memory efficient, uses fast comprehensions implemented in C and you would have to work hard to find an example where further microoptimizations are justified.

Solution 4:

def find_total_matches(team_a, team_b):
    if not team_b:
        return []
    if not team_a:
        return [0]*len(team_b)
    team_a.sort()
    team_b_sorted = sorted(team_b)
    a_i = 0
    b_i = 0
    c_sum = 0
    cnt = dict()
    while a_i <len(team_a) and b_i < len(team_b_sorted):
        val= team_b_sorted [b_i]
        ifval not in cnt:
            while a_i < len(team_a) and val >= team_a[a_i]:
                c_sum += 1
                a_i += 1
            cnt[val] = c_sum
        b_i += 1
    result = []
    forvalin team_b:
        result.append(cnt[val])

    return result

Post a Comment for "Count Number Of Element In A Array That Is Less Than The Element In Another Array"