search

Home  >  Q&A  >  body text

javascript - python small algorithm

There is a list of date strings, as follows:


lst = ['2017-06-01', '2017-06-08', '2017-06-15', '2017-06-22', '2017-06-29', ...]

Seeking s = ['2017-06-09']Which date string between and lst is most similar

Idea 1: Convert the values ​​​​of s and lst into dates, traverse and compare the difference in seconds, and the smallest one is the date string you are looking for.

Is there a better way to achieve this? ?

曾经蜡笔没有小新曾经蜡笔没有小新2750 days ago1168

reply all(3)I'll reply

  • typecho

    typecho2017-06-15 09:23:43

    I will give you an idea for your reference
    lst.append(s)
    lst.sort()
    num=lst.index(s)
    Then compare lst[num-1] and lst[num+1] The smaller number of seconds difference is the result, so there is no need to traverse and calculate the timestamp.
    If you think it’s good, please give it to Zanga and adopt it.

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-15 09:23:43

    Convert the date into an integer by removing -, and then subtract the dates in s respectively. The number with the smallest absolute value is the closest date.

    
    # Python code
    lst = ['2017-06-01', '2017-06-08', '2017-06-15', '2017-06-22', '2017-06-29']
    s = ['2017-06-09']
    date = [''.join(x.split('-')) for x in lst]
    datetoint = [int(x) for x in date]
    gaps = [abs(x - int(''.join(s[0].split('-')))) for x in datetoint]
    mostrecentdate = lst[gaps.index(min(gaps))]
    print(mostrecentdate)

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-15 09:23:43

    I feel that lz means not to traverse lst. Whether it is sort or subtraction, traversal actually occurs
    I should use the dichotomy method. This is probably what it means

    i = 0
    j = len(list)
    while True:
        index = (i + j) / 2
        if s > lst[index]:
            i = index
        else:
            j = index
        continue

    Just read it as pseudo code, that’s what it means anyway, this way the number of traversals is the least.

    reply
    0
  • Cancelreply