Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

python - 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 my code fails in certain test cases.

The problem is that given an unsorted array of elements, e.g [1, 4, 2, 4] and an array of maximum, e.g [3,5], gives the solution of the count of elements in the first array that is less than the maximums in the second array. i.e [2, 4]

some example would be

inputs

nums = [2, 10, 5, 4, 8]
maxes = [3, 1, 7, 8]

outputs

solution = [1, 0, 3, 4]

inputs

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

outputs

solution = [2, 4]

since there is one element is that is less than or equal to 3, and 0 element that is less than or equal to 1 and 3 element that is less than or equal to 3 and 4 element that is less than or equal to 8

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Pseudocode:

Sort number array
Sort maximum array
create 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 0
for max elem in max 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...