python3面试题:输入一个时间段,a=202103,b=202105
面试题
输入一个时间段,a=202103,b=202105,
输出列表:["2021-03","2021-04","2021-05"]
实现代码
# 输入一个时间段,a=202103,b=202105,
# 输出列表["2021-03","2021-04","2021-05"]
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
def out(a=202103, b=202105):
if len(str(a)) != 6 or len(str(b)) != 6:
print("参数不合法")
return []
if not str(a).isdigit() or not str(b).isdigit():
print("a,b需传纯数字类型")
return []
a1 = str(a)[:4]
a2 = str(a)[4:]
b1 = str(b)[:4]
b2 = str(b)[4:]
# print(a1, a2, b1, b2)
result = []
if int(b1) == int(a1):
if int(a2) <= int(b2):
for i in range(int(a2), int(b2)+1):
result.append('%s-%02d'%(b1, i))
else:
print("起始月份不能大于结束月份")
elif int(b1) > int(a1):
for i in range(int(a1), int(b1)+1):
# 判断是起始年
if int(a1) == i:
for j in range(int(a2), 12+1):
result.append('%s-%02d'%(a1, j))
# 判断是最后一年
elif int(b1) == i:
for j in range(1, int(b2)+1):
result.append('%s-%02d'%(b1, j))
# 中间的年份
else:
for j in range(1, 12+1):
result.append('%s-%02d'%(i, j))
else:
print("起始年份不能大于结束年份")
return result
if __name__ == '__main__':
print(out())
print(out(a=202001, b=202103))
运行结果
['2021-03', '2021-04', '2021-05']
['2020-01', '2020-02', '2020-03', '2020-04', '2020-05', '2020-06', '2020-07', '2020-08', '2020-09', '2020-10', '2020-11', '2020-12', '2021-01', '2021-02', '2021-03']