javascript - python small algorithm
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-06-15 09:21:43
0
3
1117

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? ?

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(3)
typecho

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.

漂亮男人

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)
伊谢尔伦

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!