0% found this document useful (0 votes)
12 views6 pages

Python Lab Cycle 2

The document outlines various Python lab programs conducted at SRI SAI BABA NATIONAL DEGREE COLLEGE, including exercises on sets, directories, election winners, arithmetic operations, file handling, and variable scope. Each lab includes example code demonstrating specific Python functionalities and their outputs. The document serves as a practical guide for students learning Python programming.

Uploaded by

raghu_mustoor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views6 pages

Python Lab Cycle 2

The document outlines various Python lab programs conducted at SRI SAI BABA NATIONAL DEGREE COLLEGE, including exercises on sets, directories, election winners, arithmetic operations, file handling, and variable scope. Each lab includes example code demonstrating specific Python functionalities and their outputs. The document serves as a practical guide for students learning Python programming.

Uploaded by

raghu_mustoor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Python Lab Programs

SRI SAI BABA NATIONAL DERGEE COLLEGE


(AUTONOMOUS)
Python Programming :: Lab Cycle 2
Lab 6. Write a Python program to demonstrate working of Set in Python
# Python script to demonstrate working of Set in Python
# Set in Python
# Creating two sets
set1 = set()
set2 = set()
# Adding elements to set1
for i in range(1, 6):
[Link](i)
# Adding elements to set2
for i in range(3, 8):
[Link](i)

print("Set1 = ", set1)


print("Set2 = ", set2)
print("\n")
# Union of set1 and set2
set3 = set1 | set2# [Link](set2)
print("Union of Set1 & Set2: Set3 = ", set3)
# Intersection of set1 and set2
set4 = set1 & set2 # [Link](set2)
print("Intersection of Set1 & Set2: Set4 = ", set4)
print("\n")
# Checking relation between set3 and set4
if set3 > set4: # [Link](set4)
print("Set3 is superset of Set4")
elif set3 < set4: # [Link](set4)
print("Set3 is subset of Set4")
else : # set3 == set4
print("Set3 is same as Set4")

# displaying relation between set4 and set3


if set4 < set3: # [Link](set3)
print("Set4 is subset of Set3")
print("\n")

Department of Computer Science, SSBN Degree College, ATP 1


Python Lab Programs

# difference between set3 and set4


set5 = set3 - set4
print("Elements in Set3 and not in Set4: Set5 = ", set5)
print("\n")

# check if set4 and set5 are disjoint sets


if [Link](set5):
print("Set4 and Set5 have nothing in common\n")

# Removing all the values of set5


[Link]()

print("After applying clear on sets Set5: ")


print("Set5 = ", set5)
print([Link]())

Lab 7 (a) : Write a Python program to demonstrate working of Directory in


Python

# Function to find common elements in three sorted arrays


from collections import Counter

def commonElement(ar1,ar2,ar3):
# first convert lists into dictionary
ar1 = Counter(ar1)
ar2 = Counter(ar2)
ar3 = Counter(ar3)

# perform intersection operation


resultDict = dict([Link]() & [Link]() & [Link]())
common = []

# iterate through resultant dictionary


# and collect common elements
for (key,val) in [Link]():
for i in range(0,val):
[Link](key)

print(common)

# Driver program

Department of Computer Science, SSBN Degree College, ATP 2


Python Lab Programs

if __name__ == "__main__":
ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
commonElement(ar1,ar2,ar3)

Output:
[80, 20]

Lab 7 (b): Write a Python program to find winner of an election where votes are
represented as candidate names using dictionaries

# Function to find winner of an election where votes are represented as


candidate names
from collections import Counter

def winner(input):

# convert list of candidates into dictionary output will be likes


candidates = {'A':2, 'B':4}
votes = Counter(input)
# create another dictionary and it's key will be count of votes values will be
name of candidates
dict = {}

for value in [Link]():


# initialize empty list to each key to insert candidate names having same
number of votes
dict[value] = []

for (key,value) in [Link]():


dict[value].append(key)

# sort keys in descending order to get maximum value of votes


maxVote = sorted([Link](),reverse=True)[0]

# check if more than 1 candidates have same number of votes. If yes, then sort
the list first and print first element
if len(dict[maxVote])>1:
print (sorted(dict[maxVote])[0])
else:
print (dict[maxVote][0])

# Driver program
if __name__ == "__main__":
input =['john','johnny','jackie','johnny',

Department of Computer Science, SSBN Degree College, ATP 3


Python Lab Programs

'john','jackie','jamie','jamie',
'john','johnny','jamie','johnny',
'john']
winner(input)
Lab 8 : Write a Python program to perform arithmetic operations using modules.
# module with name operations ---------- [Link]
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b

# Main Program
import operations
x=int(input("Enter first number:"))
y=int(input("Enter second number"))
total=[Link](x,y)
difference=[Link](x,y)
product=[Link](x,y)
quotient=[Link](x,y)

print('Sum of {} and {} is....{}'.format(x,y,total))


print('Difference {} and {} is....{}'.format(x,y,difference))
print('product of {} and {} is....{}'.format(x,y,product))
print('Quotient of {} and {} is....{}'.format(x,y,quotient))

Lab 9(a). Write a program that inputs a text file. The program should print all
of the unique words in the file in alphabetical order.

# Program to should print all of the unique words in the file in alphabetical
order
fname=input("Enter file name with correct extension:")
file_opened=open(fname)
our_list=list() #creating an empty list
for line in file_opened:
word=[Link]().split() #rstrip for removing unwanted spaces
for element in word:
if element in our_list:
continue
else:

Department of Computer Science, SSBN Degree College, ATP 4


Python Lab Programs

our_list.append(element)
our_list.sort()
print(our_list)

Note: Create an input file with a line of text and save as [Link] in
sairam holder. Enter the same filename while reading…
Input:
[Link]
This is my first python lab program
Enter file name with correct extension:[Link]
Output: ['Python', 'first', 'is', 'lab', 'my', 'program', 'this']
Lab 9(b). Write a program to illustrate file operations

fruits = ['Apple\n', 'Orange\n', 'Grapes\n', 'Watermelon']


my_file = open('[Link]','w')
my_file.writelines(fruits)
my_file.close()
# appends the string ‘Apple’ at the end of the ‘[Link]’ file
my_file = open('[Link]','a+')
my_file.write ('Strawberry')
my_file.write ('\nGuava')
# my_file.close()
fruits = ['\nBanana', '\nAvocado', '\nFigs', '\nMango']
# appends a list of data into a ‘[Link]’ file.
my_file.writelines(fruits)
text=["\nJack Fruit","\nPineapple","\nBlueberry"]
my_file=open('[Link]', mode='a+')
my_file.writelines(text)
print("where the file cursor is:",my_file.tell())
my_file.seek(0)
for line in my_file:
print(line)
Lab 10 : Write a Python program to illustrate scope of variables

Department of Computer Science, SSBN Degree College, ATP 5


Python Lab Programs

x=300 #Global scope


def test():
y=100 #Local scope
print("Outter function")
print("X:",x)
print("y:",y)
def process():
z=500 #Nested Local scope
print("Inner function")
print("X:",x)
print("y:",y)
print("z:",z)
process() #calling process
#end of function
test() #calling test
print("Outside test function")
print("X:",x)
print("Y:",y) # y cannot be accessed
print("Z:",z) # z cannot be accessed

Department of Computer Science, SSBN Degree College, ATP 6

You might also like