Subtract a list of lists from a list of lists with conditional arguments

I have my own complex problem that I find it difficult to move my head around.

I have two lists of lists:

firstList = [[0, 9], [0, 4], [0]]
secondList = [[18], [19, 7], [20]]

      

I would like to subtract the value (s) in firstList

from the values ​​in secondList

in ascending order, but only if the values ​​in firstList

have not yet been "used". For example:

thirdList = [0,4]
fourthList = [19,7]
emptyList = []

emptyList.append(fourthList-thirdList]
print(emptyList)
>>>[7,3]

      

19

Was not used in this case because the third list had no values ​​between the previous value in fourList and19

I think something like this (although it quickly decays to pseudocode)

firstList = [[0, 9], [0, 4], [0]]
secondList = [[18], [19, 7], [20]]
emptyList = [ [] for y in range(3) ]

for x in range(3) :
    #for smallest value in secondList[x], subtract all smaller values in firstList and then delete them, append values to emptyList[x]
    #for next smallest value in secondList[x], subtract all smaller values in firstList and then delete them, append values to emptyList[x]
    #repeat until firstList is empty, then exit loop

print(emptyList)
>>>[[9, 18], [3, 7], [20]]

      

this would preclude use 19

in the second list [1], since 0

and 4

have already been removed after subtracting from7

+3


source to share


1 answer


firstList = [[0, 9], [0, 4], [0]]
secondList = [[18], [19, 7], [20]]
all_results = []

for x in range(0, len(firstList)):  
    values_of_first = firstList[x]
    values_of_second = secondList[x]
    values_of_first.sort()
    values_of_second.sort()  
    tmp_results = []

    for subtractor in values_of_second:    
        used_values = []
        for subtracted in values_of_first:
            if subtracted >= subtractor:
                break
            else:
                used_values.append(subtracted)
                tmp_results.append(subtractor - subtracted)

        for used_value in used_values:
            values_of_first.remove(used_value)

    tmp_results.sort()
    all_results.append(tmp_results)

      



It produces all_results == [[9, 18], [3, 7], [20]]

+1


source







All Articles