Search code examples
pythonfor-loopconditional-statementsnested-listssubtraction

subtract list of lists from list of lists with conditional arguments


I have sort of a tricky problem that I'm having a hard time wrapping 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 haven't already been "used". For example:

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

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

In this case, 19 wasn't used because there were no values in thirdList between the previous value in fourthList and 19

I'm thinking something like this (although it quickly decomposes into 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 exclude the use of 19 in secondList[1] because 0 and 4 had already been deleted after being subtracted from 7


Solution

  • 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]]