1

i am trying to write a code as part of a simulator that will read a list of numbers and compare them to a secondary list of numbers and tell you how many numbers there are that are less then the first number. for example

X=[5,20,14,1,7]
Y=[2,12,9,5,4,6]

the code will take the first X value 5 and see how many of the Y values are less then 5. so the output Z would look something like

Z=[2,6,6,0,4]

i am not very familiar with these concepts at all, i am wondering how i would go about making a function for this type of work. how would i make a for loop that would go through and compare the numbers like that? also is it possible to combine and sort the lists from smallest to largest and then just search that list for the X value and print its position in the list?

noahdukehart
  • 109
  • 5

4 Answers4

1

You can do it using map and list comprehension in one line:

first = [5, 20, 14, 1, 7]
second = [2, 12, 9, 5, 4, 6]

z = map(lambda x: len([y for y in second if x > y]), first)

or without lambda (as @RobertB wrote):

z = [sum([x > y for y in second]) for x in first]

Result is:

[2, 6, 6, 0, 4]
Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
1

Something like:

[len(list(filter(lambda k: k<m, Y))) for m in X]
Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46
0

There are many ways to go about the above question. I will explain the easiest method, although it is not the most efficient method

Concept: Nested For Loop

for x in range (0, a1_len-1):
    for y in range (0, a2_len -1):
        if a[y] < a[x]:
            new_array.append(a[y])
    print (new_array)

Hope this helps

Abhay Nainan
  • 3,794
  • 2
  • 14
  • 14
0

Another answer using broadcasting with numpy:

import numpy as np
np.apply_along_axis(np.sum,0,np.array(Y).reshape((len(Y),1))<X)
Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46