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)
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)
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)
Finding factors of a number
import math
def find_factors(n):
factors = set() # Using a set to avoid duplicate factors
for i in range(1, int(math.sqrt(n)) + 1):
if n % i == 0:
factors.add(i) # i is a factor
factors.add(n // i) # n // i is also a factor
return sorted(factors) # Return factors in sorted order
# Example usage
n = 36
factors = find_factors(n)
print(f"Factors of {n}: {factors}")
Comments
Post a Comment