Home > Mobile >  Return range of integer list based on input number
Return range of integer list based on input number

Time:05-23

I found this question in my test today, I have been trying to find correct answer for this but failing to do so.

Question is:

Imagine we have range of page numbers lets say 0, 100. When we click on page lets say 15, we only what to show 10 pages on UI i.e. from page 10 to 20

more example input: 50 output: returns list

[46,47,48,49,50,51,52,53,54,55]

input: 15 output: returns list

[11,12,13,14,15,16,17,18,19,20] 

also list should include first page and last page i.e. 0 and 50

so the actual output would be for first example

[0,46,47,48,49,50,51,52,53,54,55,100]

Below is what I have tried

def get_thread_page_num(num, max_page_num):
    # Returns 10 numbers dynamically
    new_lst =[1,50]
    
    # default list
    # defult_lst = [1,2,3,4,5,6,7,8,9,10]
    num -4 > 0
    num 5 <max_page_num
    i = 10
    m = 4
    p = 5
    while i != 0:
        if num-1 >0 and m !=0:
            new_lst.append(num-m)
            i=i-1
            m = m-1
        elif num 1<max_page_num and  p != 0:
            new_lst.append(num p)
            i=i-1
            p = p-1
    
    print(sorted(new_lst))

    get_thread_page_num(9, 50)

CodePudding user response:

In your code m and p starts with value 4 and 5 respectively. In every iteration, either of them decreases by 1. So, after 9 iteration both of them are 0 and new_lst contains 9 elements. Also i becomes 10-9 = 1. But i never becomes 0 and the loop becomes infinite.

You can try below code instead. Please refer to the comments.

def get_thread_page_num(num, max_page_num):
    # low and high denotes the low and high end of the list
    # where middle element is num
    low = max(0, num - 4)
    high = min(num   5, max_page_num)

    lst = []
    if max_page_num < 9:
        # 10 element list is not possible
        return lst

    # In case high is same as max, just make the list as
    # high-9, high -8, ..., high
    if high == max_page_num:
        lst = list(range(max(0, high - 9), high   1))
    else:
        # Just create a list starting from low like -
        # low, low   1, ..., low   9
        lst = list(range(low, low 10))

    # Add 0 and max if not already present
    if 0 not in lst:
        lst.append(0)
    if max_page_num not in lst:
        lst.append(max_page_num)

    # return sorted lst
    return sorted(lst)

Call to get_thread_page_num():

print(get_thread_page_num(15, 50))
print(get_thread_page_num(0, 50))
print(get_thread_page_num(2, 50))
print(get_thread_page_num(50, 50))
print(get_thread_page_num(43, 50))

Output:

[0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 50]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 50]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 50]
[0, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
[0, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50]
  • Related