Identify groups of continuous numbers in a list

前端 未结 13 2168
误落风尘
误落风尘 2020-11-22 01:12

I\'d like to identify groups of continuous numbers in a list, so that:

myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20])

Returns:

         


        
13条回答
  •  情话喂你
    2020-11-22 02:01

    Here's the answer I came up with. I'm writing the code for other people to understand, so I'm fairly verbose with variable names and comments.

    First a quick helper function:

    def getpreviousitem(mylist,myitem):
        '''Given a list and an item, return previous item in list'''
        for position, item in enumerate(mylist):
            if item == myitem:
                # First item has no previous item
                if position == 0:
                    return None
                # Return previous item    
                return mylist[position-1] 
    

    And then the actual code:

    def getranges(cpulist):
        '''Given a sorted list of numbers, return a list of ranges'''
        rangelist = []
        inrange = False
        for item in cpulist:
            previousitem = getpreviousitem(cpulist,item)
            if previousitem == item - 1:
                # We're in a range
                if inrange == True:
                    # It's an existing range - change the end to the current item
                    newrange[1] = item
                else:    
                    # We've found a new range.
                    newrange = [item-1,item]
                # Update to show we are now in a range    
                inrange = True    
            else:   
                # We were in a range but now it just ended
                if inrange == True:
                    # Save the old range
                    rangelist.append(newrange)
                # Update to show we're no longer in a range    
                inrange = False 
        # Add the final range found to our list
        if inrange == True:
            rangelist.append(newrange)
        return rangelist
    

    Example run:

    getranges([2, 3, 4, 5, 12, 13, 14, 15, 16, 17])
    

    returns:

    [[2, 5], [12, 17]]
    

提交回复
热议问题