How to divide time interval into parts of varying length?

二次信任 提交于 2019-12-05 19:46:14

You could use a generator:

def interval(start, stop):
    cur = start
    yield cur                # return the start value
    while cur < stop:
        for increment in (2.25, 2.25, 1.5):
            cur += increment
            if cur >= stop:  # stop as soon as the value is above the stop (or equal)
                break
            yield cur
    yield stop               # also return the stop value

It works for the start and stop you proposed:

>>> list(interval(0, 19))
[0, 2.25, 4.5, 6.0, 8.25, 10.5, 12.0, 14.25, 16.5, 18.0, 19]

You could also use itertools.cycle to avoid the outer loop:

import itertools

def interval(start, stop):
    cur = start
    yield start
    for increment in itertools.cycle((2.25, 2.25, 1.5)):
        cur += increment
        if cur >= stop:
            break
        yield cur
    yield stop

Not the cleanest. But it works.

>>> start = 0
>>> stop = 19
>>> step = [2.25, 2.25, 1.5]
>>> L = [start]
>>> while L[-1] <= stop:
...    L.append(L[-1] + step[i % 3])
...    i += 1
... 
>>> L[-1] = stop
>>> L
[0, 2.25, 4.5, 6.0, 8.25, 10.5, 12.0, 14.25, 16.5, 18.0, 19]

Keep your step values in a list. Just iterate over and keep adding them in rotation till you hit the cap.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!