44.Example Programs using set

Write a program to do basic set operations
na=int(input('Enter number of elements of the set A ..'))
A=set()
print("Enter the elements of set A...")
for i in range(na):
    x=int(input())
    A.add(x)
nb=int(input('Enter number of elements of the set B ..'))
B=set()
print("Enter the elements of set B...")
for i in range(nb):
    x=int(input())
    B.add(x)
print("set operations..")
print("union")
print(A|B)
print("Intersection")
print(A&B)
print("Difference A-B and B-A")
print(A-B)
print(B-A)
print("symmetric Difference")
print(A^B)

The simple way to remove duplicate elements from a list is to convert into a set and then convert back to list
lst=[]
n=int(input("enter how many numbers.."))
print("Enter elements...")
for i in range(n):
    x=int(input())
    lst.append(x)
nlst=list(set(lst))
print("new list after removing duplicates")
print(nlst)

This program will completely remove duplicate elements without keeping any copy.
n=int(input('Enter number of elements of the list ..'))
lst=[]
print("Enter the elements...")
for i in range(n):
    x=int(input())
    lst.append(x)
nlst=list(set(lst)) # new list with only one copy
nlwd=[] # new list without duplicates
for i in nlst:
    if lst.count(i)==1: #non duplicate element
        nlwd.append(i)
print("New list after removing duplicates completely...")
print(nlwd)

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

46.Classes and Objects in Python- Accessors and mutators

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020