How to divide a time interval into parts of different lengths?

I have a time interval from 0 to t

. I want to divide this interval into a cumulative sequence in loop 2.25, 2.25 and 1.5 like this:

input:

start = 0
stop = 19

      

output:

sequence = [0, 2.25, 4.5, 6, 8.25, 10.5, 12, 14.25, 16.5, 18, 19] 

      

How can I do this in Python?


The idea is to divide the time period into cycles of 6 hours, each cycle consisting of three consecutive operations that last 2.25 hours, 2.25 hours and 1.5 hours, respectively. Or is there an alternative to using "stages" for this purpose?

+3


source to share


2 answers


You can 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 to start and stops:

>>> 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 can 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

      

+3


source


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]

      



Store the step values ​​in a list. Just loop over and keep adding them to the spin until you hit the cap.

+1


source







All Articles