Ritchie Ramnial Ritchie Ramnial - 5 months ago 7
Python Question

Python- Most efficient way to return batches of numbers

Background

I am working on some REST JSON calls via python to get a list of users. Unfortunately, the server can only return a maximum number of 50 users at a time.
e.g.

call "[0:49]" returns the first 50 users

call "[51:99]" returns the next batch of 50 users

The server does return the total number of users therefore, i am able to write some logic to get all users with multiple rest calls.

Problem

I have written a very messy function that prints the data in a dictionary format:

def get_all_possible_items(max_no_users):
dict={}
base=0
values=max_no_users//50
if max_no_users>49:
dict[base]=base+49
base+=49
else:
base-=1
for i in range(values-1):
base+=1
dict[base]=base+49
base+=49
dict[base+1]=max_no_users

print dict

get_all_possible_items(350)


The output looks like:

If max_no_users is 350:


{0: 49, 100: 149, 200: 249, 300: 349, 50: 99, 150: 199, 250: 299, 350: 350}


if max_no_users is 351:


{0: 49, 100: 149, 200: 249, 300: 349, 50: 99, 150: 199, 250: 299, 350: 351}


Is there a better way of writing this (there must be!)?

Answer

You can simply use python's range(start, stop, step). You can set step to be 50. ie,

>>> for i in range(0, max_no+1, 50):
...     print i, i+49
...
0 49
50 99
100 149
150 199
200 249
250 299
300 349
350 399

Then possibly have an extra if statement for the last number to ensure that it doesn't exceed the max number, ie.

>>> for i in range(0, max_no+1, 50):
...     print i, i+49 if i+49 < max_no else max_no
...
0 49
50 99
100 149
150 199
200 249
250 299
300 349
350 350

edit: To specifically address how you can use this, do something like this:

def get_all_possible_items(max_no_users):
    range_dict = {}
    for i in range(0,max_no_users+1, 50):
        if i+49 < max_no_users:
            range_dict[i] = i+49
        else:
            range_dict[i] = max_no_users
    return range_dict

or if you want it all in one line:

def get_all_possible_items(max_no_users):
    return {i:i+49 if i+49 < max_no_users else max_no_users for i in range(0, max_no_users, 50)}
Comments