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 ?
CodePudding user response:
As I commented, I first log all discontinuity indexes, then insert '...' from higher to lower (since modifying an iterable you're looping through will cause problems otherwise):
a = list(range(50))
a.remove(6)
a.remove(23)
a.remove(45)
indexes = []
for i in range(1,len(a)):
if a[i] != a[i-1] 1:
indexes.append(i)
for i in indexes[::-1]:
a.insert(i,'...')
a
# [0, 1, 2, 3, 4, 5, '...', 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, '...', 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, '...', 46, 47, 48, 49]
CodePudding user response:
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))