Home > Back-end >  Offset positive and negative numbers in two lists and get the rest in Python
Offset positive and negative numbers in two lists and get the rest in Python

Time:04-27

I have two lists consisting of a series of positive or negative numbers, and two lists may have unequal lengths, like this:

lst1 = [2, 3, 3, 5, 6, 6, 6, 8, 10]
lst2 = [-1, -2, -2, -3, -6, -10, -11]

The result I want to get is:

lst_ofs = [-1, -2, 3, 5, 6, 6, 8, -11]

Positive and negative numbers with equal absolute value in the two lists are offset by quantity, is there any easy way to do this?

CodePudding user response:

This solution counts the number of the positive and negative instances of each number up to the maximum. The output list is extended on each iteration as necessary.

lst1 = [2, 3, 3, 5, 6, 6, 6, 8, 10]
lst2 = [-1, -2, -2, -3, -6, -10, -11]

lst_ofs = []
for i in range(max(max(lst1), -min(lst2))   1):
    n = lst1.count(i) - lst2.count(-i)
    if abs(n) > 0:
        lst_ofs.extend([int(i * n / abs(n))] * abs(n))
print(lst_ofs)

Output:

[-1, -2, 3, 5, 6, 6, 8, -11]

CodePudding user response:

result = lst1   lst2
# keep checking for pairs until none are left
while True:
    for v in result:
        if -v in result:
            # if v and -v are in the list, remove them both
            # and restart the for loop
            result.remove(v)
            result.remove(-v)
            break
    else:
        # if the for loop made it all the way to the end,
        # break the outer loop
        break

This isn't the most efficient solution, because the for loop starts over each time two values are removed. But it should work.

  • Related