0

I'm trying to write a program that finds the intersection of two sequences.

The program then generates a list of all the elements of the intersection of the two sequences (in any order), taking into account the replication of the values. This means that if a value 'i' appears twice in the first sequence and three times in the second sequence, then the intersection should contain two instances of 'I'

here is my code:

print("This program finds the intersection of two sets")

sequenceOne = input("Please enter the space-separated elements of the first set: ")
sequenceTwo = input("Please enter the space-separated elements of the second set: ")

sequenceOne = sequenceOne.split()
sequenceTwo = sequenceTwo.split()
listOfIntersection = []

for i in sequenceOne:
     if i in sequenceTwo:
        listOfIntersection.append(i)

print(listOfIntersection)

input:

sequence One: 12 k e 34 1.5 12 hi 12 0.2
sequence Two:1.5 hi 12 0.1 54 12 hi hi hi 

My output:

['12', '1.5', '12', 'hi', '12']

Desired output:

{12, 12, 1.5, hi}

how do I get only the numbers that occur in both sequences even if its the same number evenly? (I hope this makes sense). also how to get the curly brackets?

thank you.

MSS98
  • 15
  • 7
  • @mr_mooo_cow Yes, but I get [] as output instead of {}. how can I counter this? – MSS98 Mar 15 '21 at 18:14
  • Curly braces in Python are used for dictionaries and sets. Dictionary use a key: value pair so not what you want, but a set doesn't include duplicates. Can you explain what you're trying to do that you need the curly braces? – mr_mooo_cow Mar 15 '21 at 18:22
  • @mr_mooo_cow its a homework, and in the homework it said to strictly follow the format. the example's output is given in curly braces, so I need it to be like that I guess. – MSS98 Mar 15 '21 at 18:31
  • 1
    @mr_mooo_cow never mind, the curly braces where just a random input, and the output is not intended to be a set. But really thank you for your help, I was able to write the code – MSS98 Mar 15 '21 at 19:01

1 Answers1

1
from collections import Counter

c = list((Counter(a) & Counter(b)).elements())

From answer: Intersection of two lists including duplicates?

mr_mooo_cow
  • 1,098
  • 1
  • 6
  • 16