【问题标题】:Greatest Small date最大的小日期
【发布时间】:2020-11-26 12:39:01
【问题描述】:

我有两个日期列,假设 A 和 B 在两个单独的表中。 A 包含测试日期的信息,B 列包含工厂校准的日期。我想提取自上次校准工厂以来已经过去了多少天的信息。

例如:

A=['2020-02-26', '2020-02-27', '2020-02-28', '2020-02-29']

B=['2020-02-24', '2020-02-28']

Days_Passed自上次校准以来对应于A[2,3,0,1]

【问题讨论】:

  • 自适应合并 O(n) 中的列,为每一列保留一个指针。

标签: python arrays pandas algorithm binary-search


【解决方案1】:

以最小日期为参考0,将其他日期转换为相对于0(最小日期)的天数

A = [2,3,4,5]

B = [0,4]

对于 A 的每个值,执行二进制搜索以找到 B 中最接近的最小值或相等值...它们的减法将是自上次校准以来的 Days_Passed .

答案数组 = [2,3,0,1]。

【讨论】:

  • 我的专栏是熊猫专栏。能否请您帮忙实现 pandas?
  • 您可以轻松地将 pandas 列转换为列表。
【解决方案2】:

如果AB 中的日期按顺序,则可以在O(n+m) 中完成,其中nmA 和@987654327 的长度@。虽然你没有提到编程语言,但这是 C# 中的实现

主要部分:

foreach (var testedDate in testedDates)
{
    if (nextCalibratedDate.HasValue && (testedDate - nextCalibratedDate.Value).Days >= 0)
    {
        Console.WriteLine((testedDate - nextCalibratedDate.Value).Days);
        calibratedDate = nextCalibratedDate.Value;
        if (enumerator.MoveNext())
        {
            nextCalibratedDate = (DateTime?)enumerator.Current;
        }
    }
    else
    {
        Console.WriteLine((testedDate - calibratedDate).Days);
    }
}

这是完整的代码:

public static void Main(string[] args)
{
    string[] A = new[] { "2020-02-26", "2020-02-27", "2020-02-28", "2020-02-29" };
    string[] B = new[] { "2020-02-24", "2020-02-28" };

    var testedDates = A
        .Select(x => DateTime.Parse(x))
        .ToArray();
    var calibratedDates = B
        .Select(x => DateTime.Parse(x))
        .ToArray();

    var enumerator = calibratedDates.GetEnumerator();
    enumerator.MoveNext();
    var calibratedDate = (DateTime)enumerator.Current;
    DateTime? nextCalibratedDate = default;
    if (enumerator.MoveNext())
    {
        nextCalibratedDate = (DateTime?)enumerator.Current;
    }

    foreach (var testedDate in testedDates)
    {
        if (nextCalibratedDate.HasValue && (testedDate - nextCalibratedDate.Value).Days >= 0)
        {
            Console.WriteLine((testedDate - nextCalibratedDate.Value).Days);
            calibratedDate = nextCalibratedDate.Value;
            if (enumerator.MoveNext())
            {
                nextCalibratedDate = (DateTime?)enumerator.Current;
            }
        }
        else
        {
            Console.WriteLine((testedDate - calibratedDate).Days);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2015-12-12
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    相关资源
    最近更新 更多