Get higher granularity for a list while setting 0 to the corresponding element in the other list for each new point
I have two lists of the same size, let's say:
A = [100.44 , 101.05, 103.25, 103.78] # product price
B = [ 20, 20, 50, 50] # quantity for the above product price (20 refers to price 100, etc)
I would like to be able to construct two new lists, for a given new granularity, let's say 0.2 for example:
A = [100.44, 100.64, 100.84, 101.04, 101.05, 101.25, etc] # higher granularity for list A
B = [ 20, 0, 0, 0, 20, 0, etc] # for each new element in list A, corresponding value in B should be set to 0
Remark: all numbers are 'float' type and the higher granularity I want can be anything, for example (0.1 , 0.12 ,etc).
Thanks for the help !
One approach:
def increase_granularity(A, B, size=0.2, rounding_digits=2):
# create a dictionary that maps price to quantity
input_dict = dict(zip(A,B))
new_A, new_B = [], []
# iteratively add size to price values to increase granularity between any consecutive prices
for a_min, a_max in zip(A, A[1:]):
while a_min < a_max:
new_A.append(round(a_min, rounding_digits))
# get the quantity that corresponds to a price if it exists; 0 otherwise
new_B.append((input_dict.get(a_min, 0)))
a_min += size
since `zip` does not read the last item in `A`, append it manually
new_A.append(A[-1])
new_B.append(B[-1])
return new_A, new_B
new_A, new_B = increase_granularity(A, B, 0.2)
Output:
>>>print(new_A)
[100.44, 100.64, 100.84, 101.04, 101.05, 101.25, 101.45, 101.65, 101.85, 102.05,
102.25, 102.45, 102.65, 102.85, 103.05, 103.25, 103.45, 103.65, 103.78]
>>>print(new_B)
[20, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 0, 0, 50]