python - 在 Python 中查找下一个最近的时间

标签 python algorithm date data-structures time

我有一个问题,我必须找到下一个最接近的时间,其中给定时间的格式为 HH:MM。

我写了下面的算法:

def nextClosestTime(time):
    time = list(time)
    c = (int(time[0])*10 + int(time[1]))*60 + int(time[3])*10 + int(time[4])
    digits = [time[0],time[1],time[3],time[4]]

    diff = 24*60
    # there are 4 x 4 x 4 x 4 permutations 
    ans = []
    ans = ans + time

    one = [x for x in digits if int(x)<3]
    two = [x for x in digits]
    three = [x for x in digits if int(x)<6]
    four = [x for x in digits]

    for i in range(len(one)):
        time[0] = one[i] 
        for j in range(len(two)):
            time[1] = two[j]
            if time[0]==2 and time[1]>4:
                continue
            for k in range(len(three)):
                time[3] = three[k]
                for l in range(len(four)):
                    time[4] = four[l]                    
                    t = (int(time[0])*10 + int(time[1]))*60 + int(time[3])*10 + int(time[4])
                    if t>c and t-c< diff:
                        diff = t-c 
                        ans = time

    return "".join(x for x in ans)

print(nextClosestTime("19:34"))    

但是,我的回答是 14:44,即使 ans 在时间值为 19:39 时仅更新一次。

之后 ans 永远不会更新,因为 19:39 具有最小的 diff。那么,为什么 ans 会发生变化?

这是 python 中的浅拷贝还是深拷贝问题?

我是这么想的,因此我在定义变量时不是只做 ans = time,而是做 ans = [] 然后 ans = ans + time 进行初始化。

任何帮助都会很棒。另外,欢迎任何更好的方法。谢谢。

最佳答案

实际上,在将 time 分配给 ans 之后,您继续更改 time 元素的内容。这些元素与您在 ans 中看到的元素相同,因为 anstime 指的是同一个列表.

time 分配给 ans 时需要复制一份:

               if t>c and t-c< diff:
                    diff = t-c 
                    ans = time[:] # take a copy

现在您的函数将输出:

19:39

优化

一个更有效的算法会首先检查哪个是唯一的数字列表,对它们进行排序并确定每个原始数字在该排序列表中的位置。

然后,从最后一位数字开始,查找该排序列表中的下一个可用数字。如果有,并且结果时间有效,则将其作为解决方案返回。

如果它已经是排序列表中的最后一位,或者结果时间无效,请将该数字更改为最小的可用值(排序列表中的第一个数字)。然后对剩余的数字重复上述操作。

代码:

def nextClosestTime(time):
    digits = [int(digit) for digit in time if digit.isdigit()]
    uniques = sorted(set(digits))
    pos = [uniques.index(digit) for digit in digits]

    for i in range(3, -1, -1):
        pos[i] += 1
        if pos[i] < len(uniques):
            digits[i] = uniques[pos[i]]
            if digits[2] < 6 and digits[0]*10+digits[1] < 24:
                return "{}{}:{}{}".format(*digits)
        digits[i] = uniques[0]

    return "no solution"

print(nextClosestTime("15:56")) # 16:11

关于python - 在 Python 中查找下一个最近的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48721391/

相关文章:

javascript - 在 Safari 中使用 Javascript 的 new Date()

python - 关键字: is and == in python有什么区别

ruby - 优化的字符串插入算法

Java 按最大可能的 AABB 对图 block 矩阵进行分组

algorithm - Numberlink/Flow 游戏 : How to spot NP-Complete problems?

Javascript Date 对象奇怪的行为/错误?

sql - Postgres - 是一组日期中的日期

python - 如何在 python 中将 ctypes.c_uint32 转换为 int?

python - 在 Linux 上将 Python 编译为 .EXE 而不是 .ELF

Python 3.4 : How to import a module given the full path?