-1

I have two lists of numbers list A and list B

I want to map every number in list A to a number in list B. That number is the closest number that list A exceeds in list B.

So for example, if i have the number 5 in list A and there are the numbers 3 and 6 in list B, then I want the number 5 to map to 3.

I realize I could do this by taking the difference between each number in list A with each number in list B then indexing and such but my list A and list B are extremely long and was wondering if there was a more efficient way to go about this.

Thanks!

user136482
  • 79
  • 1
  • 1
  • 4

1 Answers1

0

You say you are looking for something faster than getting the difference. If you look at this answer, which computes the closest value for a single item in O(n), your list would only take O(n^2), which is really quick. Your solution would look like this:

>>> A = [100, 7, 9]
>>> B = [2, 5, 6, 8, 123, 12]
>>> [min(A, key=lambda x: 2**16 if x > y else abs(x-y)) for y in B]
[12, 6, 8]

The 2**16 is slightly dirty, but gets the job done.

Community
  • 1
  • 1
Jorick Spitzen
  • 1,559
  • 1
  • 13
  • 25