我试图找到一个优雅的算法,以检查两个年度重复周期是否重叠.这个时期与年份无关,但一年可能总是闰年.

例如,期间A =(3月1日至5月1日)和期间B =(4月1日至9月1日)重叠.

此外,期间A =(10月1日至2月1日)和期间B =(1月1日至3月1日)重叠.

但是,我发现这比我预想的要困难得多.复杂性来自于跨越年底的时期.

我有一个有效的解决方案(参见下面的doOverlap(A,B)方法),但我发现它令人沮丧.

# for the rest of the MWE context code, see further

# WORKING, but a bit convulted

def doesOverlap(A, B):

'''returns True if yearly period A and B have overlapping dates'''

# list to track if day in year is part of a period A

# (this could probably be done a bit cheaper with a dictionary of tuples, but not relevant for my question)

yeardayCovered = [False for x in range(366)] # leap year

# mark the days of A

for d in range(A.start, A.start A.length):

yeardayCovered[d % 366] = True

# now check each of the days in B with A

for d in range(B.start, B.start B.length):

if yeardayCovered[d % 366]:

return True

return False

我相信应该可以用更少的支票和更优雅的方式来做到这一点.我已经尝试将其中一个开始日设置为零偏移,应用一些模运算符,然后是常规(非循环)范围重叠检查(Algorithm to detect overlapping periods).但我还没有为我的所有测试用例工作.

#NOT WORKING CORRECTLY!!

def doesOverlap(A, B):

'''determines if two yearly periods have overlapping dates'''

Astart = A.start

Astop = A.stop

Bstart = B.start

Bstop = B.stop

# start day counting at Astart, at 0

offset = Astart

Astart = 0

Astop = (Astop - offset) % 366

Bstart = (Bstart - offset) % 366

Bstop = (Bstop - offset) % 366

# overlap?

# https://stackoverflow.com/a/13513973

return (Astart <= Bstop and Bstart <= Astop)

注意:我已经用Python完成了代码,但理想情况下解决方案应该不是特定于Python的(即不使用通常只在Python中可用的函数,而不是在C或C#中)

# MWE (Minimal Working Example)

import datetime

import unittest

class TimePeriod:

def __init__(self, startDay, startMonth, stopDay, stopMonth):

self.startDay = startDay

self.startMonth = startMonth

self.stopDay = stopDay

self.stopMonth = stopMonth

def __repr__(self):

return "From " str(self.startDay) "/" str(self.startMonth) " to " str(self.stopDay) "/" str(self.stopMonth)

def _dayOfYear(self, d, m, y=2012):

'''2012 = leap year'''

date1 = datetime.date(year=y, day=d, month=m)

return date1.timetuple().tm_yday

@property

def start(self):

'''day of year of start of period, zero-based for easier modulo operations! '''

return self._dayOfYear(self.startDay, self.startMonth) - 1

@property

def stop(self):

'''day of year of stop of period, zero-based for easier modulo operations! '''

return self._dayOfYear(self.stopDay, self.stopMonth) - 1

@property

def length(self):

'''number of days in the time period'''

_length = (self.stop - self.start) % 366 1

return _length

def doesOverlap(A, B):

# code from above goes here

class TestPeriods(unittest.TestCase):

pass

def test_generator(a, b, c):

def test(self):

self.assertEqual(doesOverlap(a, b), c)

return test

if __name__ == '__main__':

#some unit tests, probably not complete coverage of all edge cases though

tests = [["max", TimePeriod(1, 1, 31, 12), TimePeriod(1, 1, 1, 1), True],

["BinA", TimePeriod(1, 3, 1, 11), TimePeriod(1, 5, 1, 10), True],

["BoverEndA", TimePeriod(1, 1, 1, 2), TimePeriod(10, 1, 3, 3), True],

["BafterA", TimePeriod(1, 1, 1, 2), TimePeriod(2, 2, 3, 3), False],

["sBoutA", TimePeriod(1, 12, 2, 5), TimePeriod(1, 6, 1, 7), False],

["sBoverBeginA", TimePeriod(1, 11, 2, 5), TimePeriod(1, 10, 1, 12), True],

["sBinA", TimePeriod(1, 11, 2, 5), TimePeriod(1, 1, 1, 2), True],

["sBinA2", TimePeriod(1, 11, 2, 5), TimePeriod(1, 12, 10, 12), True],

["sBinA3", TimePeriod(1, 11, 2, 5), TimePeriod(1, 12, 1, 2), True],

["sBoverBeginA", TimePeriod(1, 11, 2, 5), TimePeriod(1, 10, 1, 12), True],

["Leap", TimePeriod(29, 2, 1, 4), TimePeriod(1, 10, 1, 12), False],

["BtouchEndA", TimePeriod(1, 2, 1, 2), TimePeriod(1, 2, 1, 3), True]]

for i, t in enumerate(tests):

test_name = 'test_%s' % t[0]

test = test_generator(t[1], t[2], t[3])

setattr(TestPeriods, test_name, test)

# unittest.main()

suite = unittest.TestLoader().loadTestsFromTestCase(TestPeriods)

unittest.TextTestRunner(verbosity=2).run(suite)

解决方法:

def overlap(a0, a1, b0, b1):

首先,如果在开始日期之前结束,则可以通过调整结束日期将“年”圈中的间隔“提升”到时间“线”…

if a1 < a0: a1 = 365

if b1 < b0: b1 = 365

如果两个规则间隔相交,则存在交叉点

if a1 > b0 and a0 < b1: return True

或者如果他们确实移动[a0 … a1 [前进一年或后退一年

if a1 365 > b0 and a0 365 < b1: return True

if a1-365 > b0 and a0-365 < b1: return True

否则没有交集

return False

来源:https://www.icode9.com/content-1-361101.html

python设置循环范围_python – 如何检查循环范围的重叠(重叠的年度循环周期)相关推荐

  1. python设置环境变量_Python设置环境变量

    python设置环境变量 We can set an environment variable in Python using os module. Python os module environ ...

  2. python变量如何用循环定义_Python学习日记1(变量定义,分支,循环)

    学习历程按照Github上jackfrued的100天学习python的进度来进行,再辅上一些自己查找的相关资料. 对应传送门:https://github.com/jackfrued/Python- ...

  3. python设置文件权限_PYTHON学习之文件操作;

    PYTHON学习之文件操作: 文件内容替换 for line in flielinput.input("filepath",inplace=1): line = line.repa ...

  4. Python设置画布大小_Python第25课:海龟绘图_自定义函数的应用

    本节知识点 1. 设置画布大小 2. 两个案例对比分析 3. 复习自定义函数 案例:餐布桌布设计 课堂笔记 作业布置 1.完成视频中两款餐布桌布的图案设计. 2.自己设计一款餐布桌布(可参考网上的图案 ...

  5. python设置excel自动换行_python操作excel

    python操作Excel openpyxl模块 0.介绍 openpyxl是一个Python库,用于读取/写入Excel 2010 xlsx / xlsm / xltx / xltm文件. 它的诞生 ...

  6. python代码质量检查工具_python代码检查工具pylint 让你的python更规范

    复制代码 代码如下: #coding:utf-8 ''' a test function module ''' import urllib import time def fetch(url): '' ...

  7. python 设置 初始值_Python初始值表示为无穷大

    之前只知道设置变量的初始值为0.今天在写网络路径分析的时候,为了找到离任意坐标距离最近的节点,初始设置最短距离为无穷大,然后不断的去替换,直到找到最近的节点. 刚开始设置是min_dis = 9999 ...

  8. python列表索引负数_python – 如何检查列表索引是否存在?

    你只需要检查你想要的索引是否在0的范围和列表的长度,像这样 if 0 <= index < len(list): 实际上是内部评估 if (0 <= index) and (inde ...

  9. python设置word背景色_Python数据可视化:WordCloud入门

    WordCloud是一种很好的展现数据的方式,网上也有不少小工具和在线网页. 但是有些不支持中文,有些安装复杂,所以决定用Python实现. 主要参考官网,通过官网的例子,讲一下WordCloud的制 ...

最新文章

  1. 炎炎夏日需要一个清凉的地 - 自制水冷系统
  2. 线性时间冰山查询算法(Linear-time Iceberg Query Algorithm )
  3. 详解GaussDB(for MySQL)服务:复制策略与可用性分析
  4. 读写文本文件时汉字乱码
  5. 拓端tecdat|matlab从ECG信号数据趋势项的消除
  6. DiskGenius(硬盘修复分区工具)5绿色专业版
  7. ChartControl应用tip
  8. 《Google软件测试之道》三、好的经验沉淀
  9. Android图形绘制之——简单的几何图形
  10. 一文读懂DeFi保险市场主要玩家及其运作机制 链捕手
  11. 想要学习丙烯画,这些地方要注意了~
  12. uniapp原生sdk插件极光短信·极光短信插件可快速对接收发短信·官方伙伴优雅草发布
  13. PotPlayer会造成obs录制声音忽大忽小
  14. 玩玩破解 01——入门
  15. python生成热度图_Python - 场景热力图绘制[转]
  16. iterator的用法及概念
  17. 直面大数据撞击这个时代——畅享网成功举办大数据应用沙龙
  18. 关于数据分析的一些实例报告
  19. 笔记本电脑显示rpc服务器不可用,Win7电脑RPC服务器不可用怎么办 RPC服务器不可用解...
  20. 关于深市市值打新的选择

热门文章

  1. 记录几款比较好用的jquery插件
  2. 总结和分析几种判断RecyclerView到达底部的方法
  3. php mvc和mvvm,mvvm模式和mvc模式的区别是什么
  4. python读取excel指定行列_pandas读取excel指定行列索引header和index_col参数
  5. 关于Google插件Postman的使用方法
  6. Android 百度地图-实现POI的搜索(搜索周边)附源码
  7. 【PowerShell语音计算器】
  8. 我的Python成长之路---第一天---Python基础(5)---2015年12月26日(雾霾)
  9. 用java进行LDAP用户登陆(用户认证)及修改密码
  10. Web前端一种动态样式语言-- Less