-2
def max_zero_sequence(arr): 
    # your code here
    sequence = list()
    answers = list()
    start = 0

    while start < len(arr):
    
        for i in arr[start:]:
        
            sequence.append(i)
            if sum(sequence) == 0:
                answers.append(sequence)

        sequence = []
        start += 1 
    
    print(answers)

Trying to get the longest sequence of integers, that theirs sum equal zero. In this case, if arr is equal to [1, 2, -3, 7, 8, -16], answer must be [1, 2, -3]. So, can someone explain why python returns [[[1, 2, -3, 7, 8, -16]] ???? The sequence that should be appended to the answers list is [1, 2, -3].

  • 1
    Because you always append `sequence` and then continue mutating *that* `sequence`. Store a copy of `sequence` within your `answers`. – luk2302 Jul 30 '23 at 18:02
  • 1
    Does this answer your question? [How do I clone a list so that it doesn't change unexpectedly after assignment?](https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment) – Michael Butscher Jul 30 '23 at 18:10
  • Yes, the sequence list is still mutating, but the condition to append it to the answers list is supposed to be when the sum of their numbers is equal to zero... – juangalicia Jul 30 '23 at 18:22

3 Answers3

2

The following code should do what you are looking for. You have to store a copy of your sequence list into answers, otherwise answers just contains a reference the the original sequence list which you keep appending to.

def max_zero_sequence(arr):
    seq = list()
    ans = list()
    start = 0
    while start < len(arr):
        for i in arr[start:]:
            seq.append(i)
            if sum(seq) == 0 and len(seq) > len(ans):
                ans = seq.copy()
        seq = list()
        start += 1
    print(ans)
binaryescape
  • 105
  • 6
2

sequence still changes after you append it to answers. Changing line 13 from answers.append(sequence) to answers.append(sequence.copy()) solves your issue.

Nonlinear
  • 684
  • 1
  • 12
2

Once you've identified a sequence that sums to zero you should compare its length to any previously observed sequence that meets the criterion. If the new sequence is longer than the previous one then note it.

Something like this:

def max_zero_sequence(lst):
    result = []

    for s in range(len(lst)):
        for e in range(len(lst), s, -1):
            seq = lst[s:e]
            if sum(seq) == 0 and len(seq) > len(result):
                result = seq

    return result

print(max_zero_sequence([1, 2, -3, 7, 8, -16]))
print(max_zero_sequence([1, 2, -3, 7, 1, -1, 0, 0, 0, 2, -1, -1, 8, -16]))

Output:

[1, 2, -3]
[1, -1, 0, 0, 0, 2, -1, -1]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22