【问题标题】:Overlapping time and dates重叠时间和日期
【发布时间】:2017-08-03 04:08:23
【问题描述】:

所以我写了这个来检测数字(时间)之间的重叠并且它工作正常,现在我想添加检查它是否在一周中的同一天但是当我尝试添加这个条件时没有打印任何内容。

intervals = [[100,200, "M", "math"],[100,200, "T", "calc"], [150,250, "M", "eng"],[300,400, "W", "design"], [50,250, "T", "bio"]]
# s = start    e = end   d = day
overlapping = [ [s,e,d] for s in intervals for e in intervals for d in intervals if s is not e and s[1]>e[0] and s[0]<e[0] and d[1] == d[0] or s[0]==e[0] and s[1]==e[1] and d[1] == d[0] and s is not e]

for x in overlapping:
    print '{0} overlaps with {1}'.format(x[0],x[1])


'''
expected:

[100,200, "M", "math"] overlaps with [150,250, "M", "eng"]
[100,200, "T", "calc"] overlaps with [50,250, "T", "bio"]

'''

知道我的逻辑有什么问题吗?

【问题讨论】:

    标签: python python-2.7 logic


    【解决方案1】:

    我认为两个循环就足够了,可以检查两个类之间的时间重叠。

    intervals = [[100,200, "M", "math"],[100,200, "T", "calc"], [150,250, "M", "eng"],[300,400, "W", "design"], [50,250, "T", "bio"]]
    
    # not same object
    # same weekday
    # time overlap
    overlapping = [[s,e] for s in intervals for e in intervals 
              if s is not e
               and s[2]==e[2]
               and (s[0]<e[1] and s[1]>e[0])]
    
    for x in overlapping:
        print('{0} overlaps with {1}'.format(x[0],x[1]))
    

    会得到,(如果要删除重复项,则需要多一步)

    [100, 200, 'M', 'math'] overlaps with [150, 250, 'M', 'eng']
    [100, 200, 'T', 'calc'] overlaps with [50, 250, 'T', 'bio']
    [150, 250, 'M', 'eng'] overlaps with [100, 200, 'M', 'math']
    [50, 250, 'T', 'bio'] overlaps with [100, 200, 'T', 'calc']
    

    【讨论】:

      【解决方案2】:

      我在 Wonjin 的答案中添加了一些内容,以便能够说明是否有多个上课时间,以防有人正在寻找这种类型的迭代,这是我的代码:

      intervals = [ [[100,200, "M", "math"],[100,200, "T", "math"]], [[100,200, "M", "eng"]], [[300,400, "W", "design"]], [[50,250, "T", "bio"]] ]
      
      # not same object
      # same weekday
      # time overlap
      overlapping = [ [s,e] for s in intervals for x in s for e in intervals for y in e if s is not e and x[2]==y[2] and (x[0]<y[1] and x[1]>y[0]) ]
      
      for x in overlapping:
          print('{0} overlaps with {1}'.format(x[0],x[1]))
      
      
      Output:
      [[100, 200, 'M', 'math'], [100, 200, 'T', 'math']] overlaps with [[100, 200, 'M', 'eng']]
      [[100, 200, 'M', 'math'], [100, 200, 'T', 'math']] overlaps with [[50, 250, 'T', 'bio']]
      [[100, 200, 'M', 'eng']] overlaps with [[100, 200, 'M', 'math'], [100, 200, 'T', 'math']]
      [[50, 250, 'T', 'bio']] overlaps with [[100, 200, 'M', 'math'], [100, 200, 'T', 'math']]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-03
        • 1970-01-01
        • 1970-01-01
        • 2020-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多