Home > Enterprise >  How to create a list of lower and upper bound values based on range in Python via for loop?
How to create a list of lower and upper bound values based on range in Python via for loop?

Time:12-17

I have max range (x) that I need to create increments of and generate lists of values that increases by 1 from the previous value.

Example of hardcoding scenerio:

x = 50000
max_val = 16384

id1 = pd_ID.loc[0:16384,]
id2 = pd_ID.loc[16385:32768]
id3 = pd_ID.loc[32769:49152]
id4 = pd_ID.loc[49152:50000]

Goal of this exercise is to replicate this above example in a more automated approach given that x changes given each account I am working through.

Below is my current approach but you see that my first value in lower bound variable starts at 1 and not 0 (which I need it to start at first row [0].

import math
x = 50000
increment = math.ceil(x/16384)
print("increment",increment)
for i in range(increment):
  print("i=",i)
  upper_bound = (16384 * (i 1)) if i < increment-1 else x
  lower_bound = upper_bound - 16384   1 if i < increment-1 else ((16384 * (i)))   1
  print(lower_bound)
  print(upper_bound)

#####[1:16384]
#####[16385:32768]
#####[32769:49152]
#####[49152:50000]

Desired output

#####[0:16384]
#####[16385:32768]
#####[32769:49152]
#####[49152:50000]

CodePudding user response:

You can try something on those lines.

max_ = 50000

step = 16384
lower_bound = 0
upper_bound = 0
i = 0
while upper_bound < max_:
    if i != 0:
        lower_bound = upper_bound   1
        upper_bound = lower_bound   step - 1
    else:
        upper_bound = lower_bound   step
    if upper_bound > max_:
        upper_bound = max_
    print("lower", lower_bound)
    print("upper", upper_bound)
    print()
    i  = 1

lower 0
upper 16384

lower 16385
upper 32768

lower 32769
upper 49152

lower 49153
upper 50000

CodePudding user response:

You can modify this as appropriate to match how you want the range start and stop to be defined. In your example output it is not consistent.

def create_range(upper_lim: int, range_size: int):
    current = 0
    output = []
    while current < upper_lim:
        if current   range_size > upper_lim:
            output  = [range(current , upper_lim)]
        else:
            output  = [range(current, (current   range_size - 1))]    
        current  = range_size
    return output

create_range(50000, 16384)

[range(0, 16383),
 range(16384, 32767),
 range(32768, 49151),
 range(49152, 50000)]
  • Related