Next / Previous / Contents / Shipman's homepage

21.7. YearCollection.findNext(): Find successor month

This method is the mirror image of Section 21.6, “YearCollection.__findPrev(): Find predecessor month”. The algorithm is discussed in Section 21.5, “YearCollection.neighbors(): Find previous and next month”.

noteweb
# - - -   Y e a r C o l l e c t i o n . _ _ f i n d N e x t

    def __findNext ( self, yyyy_mm ):
        '''Find the next month chronologically after yyyy_mm.

          [ yyyy_mm is a month in self with key string 'yyyy-mm' ->
              if self has any months after yyyy_mm ->
                return the month key of the immediate successor
              else -> return None ]
        '''
        #-- 1 --
        # [ yyyy  :=  year part of yyyy_mm
        #   mm    :=  month part of yyyy_mm ]
        yyyy, mm  =  yyyy_mm.split('-')

        #-- 2 --
        # [ yyyy is a year in self ->
        #     yearRow  :=  YearRow instance for year yyyy ]
        yearRow  =  self[yyyy]

        #-- 3 --
        # [ if yearRow has a successor to month mm ->
        #     return that month's key as a string 'mm'
        #   else -> I ]
        try:
            next  =  yearRow.successor ( mm )
            return '%s-%s' % (yyyy, next)
        except KeyError:
            pass

        #-- 4 --
        # [ yyyyList  :=  all year key strings in self, sorted
        #                 in ascending order ]
        yyyyList  =  self.__yearMap.keys()
        yyyyList.sort()

        #-- 5 --
        # [ yyyy is an element of yyyyList ->
        #     pos  :=  yyyy's position in yyyyList ]
        pos  =  yyyyList.index ( yyyy )

For the function that returns the first month of a given year, see Section 22.4, “YearRow.firstMonth(): Return the first month”.

noteweb
        #-- 6 --
        # [ if any year with a key in yyyyList[pos+1:] has at
        #   least one month in it ->
        #     return the yyyy-mm key of the first month in
        #     the first such year
        #   else -> I ]
        for nextYear in yyyyList[pos+1:]:
            nextRow =  self[nextYear]
            if len(nextRow) > 0:
                firstMM  =  nextRow.firstMonth()
                return '%s-%s' % (nextYear, firstMM)

        #-- 7 --
        return None