Home > OS >  Get higher granularity for a list while setting 0 to the corresponding element in the other list for
Get higher granularity for a list while setting 0 to the corresponding element in the other list for

Time:01-18

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 !

CodePudding user response:

Edit: Since the question is edited as the list contains only float values, the previous answer will never work. Here is my edited answer. This may not be a perfect solution but you can try as an alternative.

import numpy as np

A = [100.44 , 101.05, 103.25, 105.78] #Modified the list with float values
B = [20, 20, 5, 50 ]

arr = np.array(A) // 1 #just for comparing with a rounded(1) array.

sequences = np.arange(min(A), max(A)) // 1 # Rounding to 1 since we need only that value to be compared
sequences = sequences.tolist() # Converting to list so that we can get the index of the element

# Now we need to find out the indices of newly added prices in the sequences array.
indices = [sequences.index(p) for p in sequences if not p in arr]

[B.insert(i, 0)  for i in indices] 
print(B)

Output:

[20, 20, 0, 5, 0, 50]

CodePudding user response:

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]
  •  Tags:  
  • Related