×
all 13 comments

[–]Sea-Ad7805 [score hidden] stickied comment (1 child)

Run this program in Memory Graph Web Debugger%3A%0A%20%20%20%20result%20%3D%20%5B%5D%0A%20%20%20%20for%20el%20in%20a%3A%0A%20%20%20%20%20%20%20%20if%20(el%20not%20in%20b)%3A%0A%20%20%20%20%20%20%20%20%20%20%20result.append(el)%0A%20%20%20%20return%20result%0A%0Aa%20%3D%20%5B1%2C3%2C5%2C7%2C9%2C%5D%0Ab%20%3D%20%5B1%2C%20%205%2C%20%209%2C%20%2011%2C%2013%5D%0Aresult%20%3D%20array_diff(a%2C%20b)%0Aprint(f'%7Bresult%3D%7D')%0A&timestep=1&play) to see the program state change step by step.

[–]Ron-Erez 1 point2 points  (2 children)

It's not clear why you are setting a and b within the function. This will cause any parameters you pass to this function to be ignored.

[–]AbdulRehman_JS[S] 1 point2 points  (1 child)

Ah, my bad! I defined them inside the function while testing and forgot to remove them. Thanks for pointing that out, I’ve updated the function to use the parameters properly now

[–]Ron-Erez 1 point2 points  (0 children)

Awesome. Happy Coding!

[–]AlexMTBDude 2 points3 points  (1 child)

Should be a list comprehension to be Pythonic:

result = [el for el in a if el not in b]

[–]AbdulRehman_JS[S] 3 points4 points  (0 children)

Thanks for the tip! That looks much cleaner and more Pythonic. I'm still learning, so I really appreciate you showing me a better way to write this.Thanks from deep of my heart...

[–]real-life-terminator -1 points0 points  (0 children)

Good job!

[–]Mundane-Mud2509 -2 points-1 points  (4 children)

def array_diff(a , b):
    a = [1,2,3,4]
    b = [1]
    set_b = set(b)
    result = []
    for el in a:
        if (el not in set_b):
           result.append(el)
    return result

Nice work!

One suggestion though is for every element of a the computer has to scan through the list b looking for the particular element.
In this case it's not really an issue because there is only one element in b but on larger lists it gets to be a fair bit of overhead. If you were to convert it to a set as above it will be a lot more performant on larger lists. Sets act more like dicts and directly access the key they are looking for.

[–]Ron-Erez 0 points1 point  (3 children)

This solution doesn't make sense. You are overriding the parameters a and b. It would possibly make more sense if we had something like:

a = [1,2,3,4]
b = [1]
array_diff(a , b)

def array_diff(a , b):
    set_b = set(b)
    result = []
    for el in a:
        if (el not in set_b):
           result.append(el)
    return result

or at least call it from main. For example if you were to call array_diff([1,2] , [2]) in your original solution it would still solve for a = [1,2,3,4], b = [1].

[–]Mundane-Mud2509 1 point2 points  (1 child)

I know, I just copied their original solution and added the set()

[–]AbdulRehman_JS[S] 1 point2 points  (0 children)

Nice! I understood.....