Python Forum

Full Version: simple task with lists...
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Write the function equal(lst1, lst2), which for two given integer lists will give the result True if these lists are equal after compression and False otherwise. By compression in this task, we mean a replacement on the list
adjacent non-negative (negative) numbers by their sum.

Examples:
• equal([], []) == True
• equal([1], []) == False
• equal([], [1]) == False
• equal([1, -2, 3, -1], [1, -2, 3, -1]) == True

I have no idea how to do it, i have written this, but it seems bad...

def equal(lst1, lst2):
 j = 0
 for elt1 in lst1:
     for k in range(j, len(lst2)):
         if elt1 == lst2[k]:
            j = k+1
            break
     else: 
         return False
 return True
(Jun-27-2020, 11:12 AM)Maxwell123 Wrote: [ -> ]By compression in this task, we mean a replacement on the list adjacent non-negative (negative) numbers by their sum.

I have read this part a number of times and don't understand what it means? Huh
(Jun-27-2020, 11:28 AM)Yoriz Wrote: [ -> ]
(Jun-27-2020, 11:12 AM)Maxwell123 Wrote: [ -> ]By compression in this task, we mean a replacement on the list adjacent non-negative (negative) numbers by their sum.

I have read this part a number of times and don't understand what it means? Huh


you just sum elements ([1, -2, 3, -1], [1, -2, 3, -1]) in both lists and if they are equal then its True, if not False
1+(-2)+3-1 = 1+(-2)+3-1 = 1
If you just want to compare the sums of the elements in each list (and I agree with Yoriz that the wording is very confusing), then my recommendation would be to just iterate through each list in turn to get the sums and then compare those against each other.

For example, if you have a list like [1, -5, 7, 3], using a for loop will give you each of those elements in turn.
mylist = [1, -5, 7, 3]
for i in mylist:
    print(i)
Output:
1 -5 7 3
Sum those values as you iterate through them, then compare the sums to determine whether to return True or False in your function.