Search code examples
pythonpython-3.xnested-loops

Print common elements of two lists with two nested for loops


I'm new to python and I have this code that programs to print out the intersection between two sequences.

the code works fine, but I'm trying to convert it into nested loops kind of code. I tried many things, but non worked, could you please help me?

here is the code

print("This program finds the common elements of two lists")

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

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

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

print('The intersection of these two lists is {' +(", ".join(str(i) for i in listOfIntersection))+'}')

Output:

This program finds the intersection of two sets
Please enter the space-separated elements of the first set: 12 k e 34 1.5 12 hi 12 0.2
Please enter the space-separated elements of the second set: 1.5 hi 12 0.1 54 12 hi hi hi
The intersection of these two sets is {12, 1.5, 12, hi}

Solution

  • This is a code with nested for loops, which keeps duplicated values.

    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:
         for j in sequenceTwo:
             if (i==j):
                 listOfIntersection.append(i)
    
    print('The intersection of these two sets is {' +(", ".join(str(i) for i in listOfIntersection))+'}')
    

    Here is second solution, which mimics exactly what you did first:

    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:
         for j in sequenceTwo:
             if (i==j):
                 listOfIntersection.append(i)
                 sequenceTwo.remove(i)
                 break
        
    
    print('The intersection of these two sets is {' +(", ".join(str(i) for i in listOfIntersection))+'}')