所以我写这个来检测数字之间的重叠(时间)并且它工作正常,现在我想添加检查它是否在一周的同一天但是当我试图添加这个条件时没有打印任何内容。< / p>
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"]
'''
我的逻辑有什么问题吗?
答案 0 :(得分: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']
答案 1 :(得分:0)
我向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']]