📜 ⬆️ ⬇️

Interval-associative array

A great thing is an associative array . Various tasks are solved with its help easily, pleasantly and quickly. But what about when the value should belong not to one key, but to be “smeared” for some interval?
Imagine that you need to make a program for scheduling the duty managers of an online store. Working with him should be as simple as possible, like this:
#
>>> timetable[ '08:00' : '12:00' ] = ''
>>> timetable[ '12:00' : '16:00' ] = ''

# 13:51 ?
>>> print timetable[ '13:51' ]


#
>>> for interval, person in timetable.items(): print interval, person
( '08:00' , '12:00' )
( '12:00' , '16:00' )

# ...
>>> print timetable
{[ '08:00' , '12:00' ] => '' , [ '12:00' , '16:00' ] => '' }



#
>>> del timetable[ '15:00' : '16:00' ]
>>> print timetable
{[ '08:00' , '12:00' ] => '' , [ '12:00' , '15:00' ] => '' }

# ...
>>> del timetable[ '12:00' : '16:00' ]
>>> print timetable
{[ '08:00' , '12:00' ] => '' }

#
>>> timetable[ '11:00' : '15:00' ] = ''
>>> print timetable
{[ '08:00' , '11:00' ] => '' , [ '11:00' , '15:00' ] => '' }

# ,
# , 15 17,
# ,
>>> timetable[ '15:00' : '17:00' ] = ''
>>> print timetable
{[ '08:00' , '11:00' ] => '' , [ '11:00' , '17:00' ] => '' }

#
>>> timetable[ '17:00' : '20:00' ] = ''
>>> timetable[ '21:00' : '23:00' ] = ''
>>> timetable
{[ '08:00' , '11:00' ] => '' , [ '11:00' , '17:00' ] => '' ,
[ '17:00' , '20:00' ] => '' , [ '21:00' , '23:00' ] => '' }

# , ,
# . , .
>>> timetable.shrink()
>>> print timetable
{[ '08:00' , '20:00' ] => '' , [ '21:00' , '23:00' ] => '' }


#
# .


Approximately the task I faced in the project. Googling gave one interesting recipe , which lacked several important features. After completion of the file, everything fell into place.

Who needs - feel free to take it. Any comments, questions, bug reports are welcome. If you have ideas for development - write!
')
UPD: Unfortunately, after the Visual Code Highlighter and Habraparser, the formatting of the code has thoroughly deteriorated, so I remove it from here and upload it to Google: code.google.com/p/intervalmap/source/browse/trunk/intervalmap.py

Source: https://habr.com/ru/post/43731/


All Articles