'Take 2 random dates from list of dates based on days range condition

I would like to randomly choose 2 dates from the list of dates based on condition that if date range between 2 randomly choosen dates from the list is lower than 100 days we want to take them if not we look for other 2 random dates from the list.

Code below will not work but this is more or less what I would like to achieve:

dates = [date(2020, 1, 25), date(2020, 2, 23), date(2020, 3, 27)]

def get_2_random_dates_with_with_days_range_100():
   choosen_dates = random.choice([a, b for a, b in dates if a.days - b.days <= 100])

Also code above shows more or less what I've tried which is to use list comprehension with the condition but it would require me to unpack 2 values from the list

Thanks



Solution 1:[1]

Maybe first get one random date, next create list with dates which match condition(s), and next get second random date from this list. And if it can't find matching dates then start from the beginning and select first random date again, etc.

from datetime import date
import random

dates = [date(2020, 1, 25), date(2020, 2, 23), date(2020, 3, 27),
         date(1920, 1, 25), date(1920, 2, 23), date(1920, 3, 27), 
         date(2025, 1, 25), date(2025, 2, 23), date(2025, 3, 27)]

while True:
    first = random.choice(dates)
    print(' first:', first)

    matching = [x for x in dates if 0 < abs(x - first).days <= 100]
    print('matching:', matching)

    if matching:
        second = random.choice(matching)
        print('second:', second)
        break

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 furas