Next / Previous / Contents / Shipman's homepage

21.5. YearCollection.neighbors(): Find previous and next month

For a given month key expressed as a 'yyyy-mm' string, this method finds the preceding and following months, and returns a two-element tuple containing the month keys of its immediate neighbors, using None for the predecessor of the first month in the set, or for the successor of the last month.

# - - -   Y e a r C o l l e c t i o n . n e i g h b o r s

    def neighbors ( self, yyyy_mm ):
        '''Find the previous/next months to yyyy_mm in sequence

Because we use a two-level structure of years and months, and because the predecessor or successor of a month may be in a different year, we'll use this algorithm to find the predecessor.

  1. If year yyyy has any months before mm, the predecessor is the last such month.

  2. Work backwards through years yyyy-1, yyyy-2, until we find a year that has at least one month in it. When we do, the predecessor is the last month in that year.

  3. If we run out of years, the predecessor is None.

The algorithm to find the successor is symmetric. See Section 21.6, “YearCollection.__findPrev(): Find predecessor month” and Section 21.7, “YearCollection.findNext(): Find successor month”.

        #-- 1 --
        # [ if yyyy_mm has a predecessor in self ->
        #     prev  :=  that predecessor's 'yyyy-mm' month key
        #   else ->
        #     prev  :=  None ]
        prev  =  self.__findPrev ( yyyy_mm )

        #-- 2 --
        # [ if yyyy_mm has a successor in self ->
        #     next  :=  that successor's 'yyyy-mm' month key
        #   else ->
        #     next  :=  None ]
        next  =  self.__findNext ( yyyy_mm )

        #-- 3 --
        return (prev, next )