Search code examples
pythonlistinsert

Inserting items in a list with python while looping


I'am trying to change the following code to get the following return :

"1 2 3 ... 31 32 33 34 35 36 37 ... 63 64 65"

def createFooter2(current_page, total_pages, boundaries, around) -> str:
    footer = []
    page = 1
    #Append lower boundaries
    while page <= boundaries:
        footer.append(page)
        page += 1
    #Append current page and arround
    page = current_page - around
    while page <= current_page + around:
        footer.append(page)
        page += 1
    #Append upper boundaries
    page = total_pages - boundaries + 1
    while page <= total_pages:
        footer.append(page)
        page += 1
    #Add Ellipsis if necessary
    for i in range(len(footer)):
        if i > 0 and footer[i] - footer[i - 1] > 1:
            footer.insert(i, "...")
    result = ' '.join(str(page) for page in result)
    print(result)
    return result

createFooter2(34, 65, 3, 3)

I want to insert an "..." between the pages if the next page is not directly next to it. However Iam having trouble inserting into the list.

How should I change the code to make it work ?


Solution

  • This produces a sorted list of page numbers in the first step and then adds "..." to gaps between the numbers. Nothing special, but it should produce a sane output even if there are not 3 intervals (i.e. 2 gaps between them), but some of the intervals overlap (1 gap, or no gap at all).

    def createFooter2(current_page, total_pages, boundaries, around) -> str:
        intervals = [ 
                (1, boundaries),
                (current_page - around, current_page + around),
                (total_pages - boundaries + 1, total_pages)
                ]   
        pages = set()
        for start, stop in intervals:
            pages.update(range(max(1, start), min(stop, total_pages) + 1))
    
        footer = []
        last = 0 
        for i in sorted(pages):
            if i != last + 1:
                footer.append('...')
            footer.append(str(i))
            last = i 
        print(" ".join(footer))