+ 2

🐚 [Exercise] Collections - Need help 💫 Python 🐍

Hello, I have some trouble with an exercise at school. Was wondering if you could help me solving this, and if possible explaining it as well ? We haven't really seen the Collections yet... ——————————- The following code sample is a naive implementation of the ​intersection function, where the intersection of two collections, A and B, is defined as a collection that contains all the elements that are common to both A and B. def​ intersection​(​A​,​ B​): intersection ​=​ ​[] for​ a ​in​ A​: ​ if​ a ​in​ B​: intersection​.​append​(a​ ​) ​ return​ intersection Write code for each function listed below (union and difference), where: 🌟 The ​union ​of two collections, A and B, is defined as a collection that contains all the elements that are in either A or B 🌟 The ​difference ​of two collections, A and B, is defined as a collection that contains the elements that are in either A or B, but ​not​ both. def union(A, B): ... def difference(A, B): ...

13th Feb 2019, 10:46 AM
Jin 🌙
Jin 🌙 - avatar
8 Antworten
+ 2
Where is your try?
13th Feb 2019, 10:50 AM
KrOW
KrOW - avatar
+ 2
Okay Jin 🌙 . For the & operator, you can iterate through A to see if it is in B. Then, remove 1 copy of that element in both A and B. Repeat until completion. For the difference, you need to combine both A and B, remove A&B twice.
13th Feb 2019, 11:00 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
Jin 🌙 You tried. This is a not so naive implementation. https://code.sololearn.com/crUR9AY4tR8x/?ref=app
24th Feb 2019, 2:45 PM
Louis
Louis - avatar
+ 1
Jin 🌙 Are the elements in the collection unique? If they are, Python has a unique solution: sets. Correct me if the collections have repeated elements.
13th Feb 2019, 10:49 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 1
Prometheus: In the exercise, I understood that they have common elements, so not unique then ? I believe they have repeated one. Are the Collections like the Array in C ? KrOW: I need to understand the exercise before attempt it.
13th Feb 2019, 10:58 AM
Jin 🌙
Jin 🌙 - avatar
+ 1
I think that the exercises are only for make you thinking about the algorithm assuming than a collection is a simple list.
13th Feb 2019, 11:05 AM
KrOW
KrOW - avatar
+ 1
My attempt is below, hope it makes sense ? ========= def union(A, B): union= [] for a in A: union.append(a) for b in B: union.append(b) return union def difference(A, B): difference = [] Union= union(A,B) Intersection= intersection(A,B) for u in Union if not u in Intersection difference.append(u) return difference
14th Feb 2019, 12:34 PM
Jin 🌙
Jin 🌙 - avatar
0
The union is not right... You add to it every item of either collections but wouldnt be the case... At example: A=[1, 2, 3] B= [3,4,5] Your code return like union: [1,2,3,3,4,5] but it would return [1,2,3,4,5] This is because you have to make sure to include into union only items not yet included
14th Feb 2019, 1:16 PM
KrOW
KrOW - avatar