Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For each element of the list find closest date from a different list

Tags:

python

list

I have 2 lists:

l1 = [ '09/12/2017', '10/24/2017' ]
l2 = [ '09/15/2017', '10/26/2017', '12/22/2017' ]

For every ticker in l1 I want to find the closest element from l2 after it, so the output should be

l3 = [ '09/15/2017', '10/26/2017' ]

The right way seems to be to explicitely iterate in parallel over both lists in reverse order, but I was hoping for a more "pythonic" solution..

EDIT: I do want an optimal complexity solution, which (assuming the lists are sorted), I think is O(max(len(l1), len(l2))).

like image 970
LazyCat Avatar asked Dec 24 '22 03:12

LazyCat


1 Answers

You could use a list comprehension in combination with min method by passing a lambda expression.

from datetime import datetime
l1 = [ '09/12/2017', '10/24/2017' ]
l2 = [ '09/15/2017', '10/26/2017', '12/22/2017' ]

l1 = [min(l2, key=lambda d: abs(datetime.strptime(d, "%m/%d/%Y") - datetime.strptime(item, "%m/%d/%Y"))) for item in l1]

Output

['09/15/2017', '10/26/2017']

If you want a more efficient solution you can write your own insert sort algorithm.

def insertSortIndexItem(lst, item_to_insert):
  index = 0
  while index < len(lst) and item_to_insert > lst[index]:
    index = index + 1
  return lst[index]

l2 = sorted(l2, key=lambda d: datetime.strptime(d, "%m/%d/%Y"))
l1 = [insertSortIndexItem(l2, item) for item in l1]
like image 113
Mihai Alexandru-Ionut Avatar answered Apr 15 '23 04:04

Mihai Alexandru-Ionut