pythonarraysmultiple-occurrence

Python Codewars: can someone explain how/why this happens?


I'm doing Codewars and got stuck at this simple question. The question was:

Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result. It should remove all values from list a, which are present in list b keeping their order. If a value is present in b, all of its occurrences must be removed from the other.

This is what I've tried:

def array_diff(a, b):
    if a == []: return b
    if b == []: return a
    for occurrence in b:
      if occurrence in a:
        a.remove(occurrence)
    return a

and for some reason I got 2 failed tests, the requirements for those failed tests are:

a was [1,2,2], b was [2], expected [1]: [1, 2] should equal [1]

a was [], b was [1,2], expected []: [1, 2] should equal []

can anyone help me and also explain if possible? any help is appreciated. edit: my excuse is that I'm a beginner to Python so, sorry if this question has super obvious errors/mistakes


Solution

  • I fixed it. Here's the code if anyone's stuck on the same question: The first code was provided by Matthias, which was much cleaner, please use it.

    def array_diff(a, b):    
        return [value for value in a if value not in b]
        # CREDITS TO MATTHIAS FOR THIS SIMPLE SOLUTION
    

    My code, if anyone's interested:

    def array_diff(a, b):
        #if a == []: return b
        #if b == []: return a
        # these if statements are replaced by the"for item in range" code below
        for occurrence in b:
          if occurrence in a:
            for item in range(a.count(occurrence)):
                a.remove(occurrence)
        return a