You are on page 1of 52

FRANCIS XAVIER ENGINEERING COLLEGE TIRUNELVELI

DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS


SYSTEMS

21CS2501- Introduction to computing using python

I Year B.Tech CSBS / I Semester


2021 – 2022 / EVEN SEMESTER

Register Number : ________________________________________________

Name : ________________________________________________
FRANCIS XAVIER ENGINEERING COLLEGE,
TIRUNELVELI – 627003

ROLL NO ……………………….

BONAFIDE CERTIFICATE

Certified that this is a bonafide record of work done by


Selvan/Selvi…………………………………………………… with
Reg.No…………………………………………………….. of I semester in
B.Tech – Computer Science and Business Systems branch of this institution
in the 21CS2501 Introduction to computing using python during the
academic year 2021 – 2022.

Staff-in charge H.O.D

Submitted for the University Practical Examination held on…………………

Internal Examiner External Examiner


S.NO LIST OF EXPERIMENT PAGE MARKS SIGNATURE
NO. AWARDED
1. BASIC PYTHON PROGRAMMING

a) Write a program that takes 2 numbers as command line


arguments and prints its sum.
b) Implement python script to show the usage of various
operators available in python language.
c) Write a program for checking the given number is even
or odd.

d) Write a program for finding biggest number among 3


Numbers.
e) Implement python script to read person’s age form user
and display whether he is eligible for voting or not.

f) Implement python script to check the given year is leap


year or not.
2. Python Programs Using Looping Statements

a) Implement python script to generate first N natural


number
b) Implement python script to check given number is
palindrome or not

c) Implement python script to print factorial of a number.

d) Implement python script to check given number is


Armstrong or not

3. Python Program Using Functions

a) Define a function max_of_three () that takes three


numbers as arguments and returns the largest of them.

b) Write a program which makes use of function to


display all such numbers which are divisible by 7 but
are not a multiple of 5, between 1000 and 2000.
4. Python Programs Using List

a) Write a program which accepts a sequence of comma –


separated numbers numbers from console and generate
a list and a tuple which contain every number. Suppose
the following input is supplied to the program: 34, 67,
55,33,12,98. Then the output should be:
[ ‘34’ ,’67’ ,’55’, ’33’,‘12’,’98’]
(‘34’,’67’,’55’,’33’,’12’,’98’).

5. Python Programs Using String, Tuplues, Numpy Array.


a) Accepts a string and calculate the number of uppercase
letters and lowercase letters.
b) Write a python program to check whether the given
string is palindrome or not.
c) Create all possible strings by using ‘a’,’e’,’i’,’o’,’u’.
Use the character exactly once.
d) Multiply all the numbers in list.

6. Python Programs Using Dictionary

a) Create a dictionary and apply the following methods 1)


print the dictionary 2) access item 3) use get () 4)
change values 5) use len ().
7 Python Programs Using Files

a) Write python script to display file contents.

b) Write python script to copy file content s from one file


to another.
8. Python Program using Exceptions.

9. Calculation of the area: Don’t measure.

10. Monte Hall: 3 doors and a twist.

11. Sorting: Arrange the books.

12. Searching: Find in seconds.

13. Anagram.
14. Lottery simulation -Profit or Loss.

Simulate a password generator.


15.
16. Simulate a grade book for a teacher.

17 Rock Paper and Scissor.

18. Converting an image to Black and White /Grayscale.

19. Blurring an image, Edge Detection and Reducing the


Image Size.

1. BASIC PYTHON PROGRAMMING


a) Write a python program that takes two numbers as a command line argumentand prints its sum.

AIM:
To write a python program that takes two numbers as a command line argument and prints its sum.

ALGORITHM:
Step 1:Start.
Step2:Get a, b input values.
Step 3:Then add a and b using ‘+’ operator.
Step 4: Display the output.
Step 5:Stop.
PROGRAM:
a= int (input(“enter the first number:”))
b= int (input(“enter the second number:”))
c=a + b
print(“the addition of “, a,” and “b, “is”,c)

OUTPUT
Enter a number. 3
Enter a number. 5
Enter a number. 4
Sum = 12

RESULT:
Thus, the python program that takes two numbers as a command line argument and prints its sum was
executed successfully.
b) Implement python script to show the usage of various operators available in python language.

AIM:
To implement python script to show the usage of various operators available in python language.

ALGORITHM:
Step 1:Start.
Get two values a & b as input.
Do some operation using operators available in python like ‘+’, ‘-’, ‘*’. ‘/’.
Display the output.
Stop.
PROGRAM:
a= int (input(“enter the first number:”))
b= int (input(“enter the second number:”))
print (“a + b =,” a + b)
print (“a - b =,” a-b)
print (“a * b =,” a*b)
print (“a / b =,” a/b)

OUTPUT:
Enter a number:3
Enter a number:2
Arithmetic Operator
Sum= 5
Difference= 1
Product= 6
Quotient= 1.5
Remainder= 1
Floor Division= 1
Exponential= 9
Relational Operator
Greater= True
Lesser= False
Equal= False
Not Equal= True
Greater than or Equal= True
Lesser than or Equal to= False
Logical Operator
And= False
Or= True
Not= False
Enter a number:2
Enter a number:4
Enter a number:1
Enter a number:2
Assignment Operator
Addition Assignment= 6
Subtraction Assignment: -2
Multiplication Assignment: 2
Division Assignment: 0.3333333333333333
Bitwise Operator
AND= 2
OR= 3
XOR= 1
Left Shift= 12
Identity Operator
f is equal to x= True
Membership Operator

RESULT:
Thus, the script to show the usage of various operators available in python language was executed
successfully.
c) Write a program for checking the given number is even or odd.

AIM:
To Write a program for checking the given number is even or odd.

ALGORITHM:
Step 1:Start.
Step 1:Get input as n.
Step 1: Check whether the number satisfy the condition.
n%2==0.
If it satisfies print “even” or print “odd”.
Step4: Stop.
PROGRAM:
n=int (input (“enter a number:”))
if(n%2==0):
print (“the given number is even”)
else:
print (“the given number is odd”)

OUTPUT:
Enter a number.4
4 is even

RESULT
Thus, the program for checking the given number is even or odd was executed successfully.
d) Write a program for finding biggest number among 3numbers
AIM:
To Write a program for finding biggest number among 3numbers

ALGORITHM:
Step 1: Start.
Get a,b,c as input value
Checkthe following condition
Display the output
Stop.

PROGRAM:
a= int (input(“enter the first number:”))
b= int (input(“enter the second number:”))
c= int (input(“enter the third number:”))
if(a>b) and (a>c):
print (a,” is the largest number”)
elif (b>a) and (b>c):
print (b,” is the largest number”)
else:
print (c,” is the largest number”)

OUTPUT:
Enter a number.6
Enter a number. 8
Enter a number. 3
8 is greatest

RESULT
Thus, the program for finding biggest number among 3 numbers was executed successfully.
e)Implement python script to read person’s age from keyboard and display whether he is eligible for
voting or not.
AIM:
To implement python script to read person’s age from keyboard and display whether he is eligible
for voting or not

ALGORITHM:
Step 1:Start.
Step 2: Get input value as age
Step 3: Check whether the age is above 18
If it prints “eligible to vote”
OR
Print “not eligible to vote”
Step 4: Display the output
Step 5:Stop.

PROGRAM:
age= int (input(“enter your age:”))
if(age>=18)
print (” you areeligibleto vote”)
else:
print (” you are not eligible to vote”)

OUTPUT:
Enter the age:58
Eligible to vote

RESULT
Thus, the python script to read person’s age from keyboard and display whether he is eligible for
voting or not was executed successfully.
f)Implement python script to check the given year is leap year or not.
AIM:
To implement python script to check the given year is leap year or not.

ALGORITHM:
Step 1:Start.
Step 2: Get input value as year.
Step 3: Check whether the year is divisible by 4.
If it prints “leap”
OR
Print “not a leap”
Step 4: Display the output.
Step 5: Stop.

PROGRAM:
year= int (input(“enter a year:”))
if(year%4==0)
print (” The given year is leap year”)
else:
print (” The given year is not leap year”)

OUTPUT:
Enter a year.2024
2024 is leap year
RESULT:
Thus, the python script to check the given year is leap year or not was executed successfully.
2. Python Programs using looping statements
a) Implement python script to generate first N natural number
AIM:
To implement python script to generate first N natural number

ALGORITHM:
Step 1:Start.
Step 2: Get input value as num.
Step 3: Using for loop condition.
Step 4: Print the output.
Step 5: Stop.

PROGRAM:
numb=int (input ("Please enter maximum number: "))
print ("Natural numbers 1 to “, numb)
for I in range (1, num+1):
print (I)

OUTPUT:
Enter a number:5
1
2
3
4
5

RESULT:
Thus, the python script to generate first N natural number was executed successfully.
b) Implement python script to check given number is palindrome or not
AIM:
To implement python script to check given number is palindrome or not

ALGORITHM:
Step 1:Start.
Step 2: Get input value.
Step 3: transfer the value into another temporary variable.
Step 4: using a while loop condition.
Step 5: check if the reverse of the number is equal to the one in ‘n’.
Step 6: print the final output.
Step 7: Stop.

PROGRAM:
n=int (input ("Enter the number"))
rev=0
temp=n
while(temp>0):
rev=(10*rev) +(temp%10)
temp=temp//10
if(rev==n):
print ("Number is Palindrome")
else:
print ("Number is not Palindrome ")

OUTPUT:
Enter number:567
567 is not a palindrome number

RESULT:
Thus, the python script to check given number is palindrome or not was executed successfully.
c) Implement python script to print factorial of a number.
AIM:
To implement python script to print factorial of a number.

ALGORITHM:
Step 1:Start.
Step 2: Take the number from the user.
Step 3: Initialize a factorial variable to 1.
Step 4: Use if, elif and else condition.
Step 5: In else condition use the for loop.
Step 6: Print the final output.
Step 7: Stop.

PROGRAM:
num=int (input ("Enter the number"))
fact=1
if(num<0):
print ("The factorial of negative number doesn’t exist")
elif(num==0):
print ("The factorial is 1")
else:
for I in range (1, num+1):
fact=fact*I
print ("Factorial of number", num, “is",fact)

OUTPUT:
Enter a number:5
The factorial of 5 is 120

RESULT
Thus, the python script to print factorial of a number was executed successfully.
d) Implement python script to check given number is Armstrong or not.
AIM:
To implement python script to check given number is Armstrong or not.

ALGORITHM:
Step 1:Start.
Step 2: Take the number from the user.
Step 3: Initialize a sum variable to 0.
Step 4: Use while loop, get each digit of the number.
Step 5: check if the sum is equal to the ‘n’.
Step 6: Print the final output.
Step 7: Stop.

PROGRAM:
n=int (input ("Enter the number:"))
sum=0
temp=n
while(temp>0):
digit=temp%10
sum=sum+(digit**3)
temp=temp//10
if(sum==n):
print (n,"is an Armstrong number")
else:
print (n,"is not an Armstrong number")

OUTPUT:
Enter a number:153
153 is Armstrong

RESULT:
Thus, the python script to check given number is Armstrong or not was executed successfully.
3.Python Programs using Functions.
a) Define a function max_of_three () that takes three numbers as arguments and returns the largest of them.
AIM:
To a function max_of_three () that takes three numbers as arguments and returns the largest of them.
ALGORITHM:
Step 1:Start.
Step 2: Define max function.
Step 3: In max function read a, b, c.
Step 4: Check the condition a>b and a>c.
condition is true return ‘a’.
Step 5: Check the condition b>c.
condition is true return ‘b’.
Step 6: Otherwise print ‘c’.
Step 7: Print the final result.
Step 8: Stop.
PROGRAM:
def max_of_three (a, b, c):
if(a>b) and (a>c):
print(a)
elif(b>c):
print(b)
else:
print(c)
a=10
b=25
c=15
max_of_three (a, b, c)
OUTPUT:
Enter a number:78
Enter a number:34
Enter a number:15
Largest number= 78
RESULT: Thus, a function max_of_three () that takes three numbers as arguments and returns the
largest of them was executed successfully.
b) Write a program which makes use of function to display all such numbers which are divisible by 7 but are
not a multiple of 5, between 1000 and 2000.
AIM:
To Write a program which makes use of function to display all such numbers which are divisible by 7
but are not a multiple of 5, between 1000 and 2000
ALGORITHM:
Step 1:Start.
Step 2: Define display function.
Step 3: def display (n1, n2).
Step 4: In for loop, check the condition
i%7==0 and i%5! = 0.
Step 5: if the condition is a true
Print value.
Step 6: Otherwise go to the next iteration.
Step 7: Print the final result.
Step 8: Stop.

PROGRAM:
def display (n1, n2):
for i in range (1000, 2000+1):
if (i%7==0) and (i%5! =0):
print(i)
n1 = 1000
n2 = 2000
print (display (n1, n2))
OUTPUT:
[1001, 1008, 1022, 1029, 1036, 1043, 1057, 1064, 1071, 1078, 1092, 1099, 1106, 1113, 1127, 1134, 1141,
1148, 1162, 1169, 1176, 1183, 1197, 1204, 1211, 1218, 1232, 1239, 1246, 1253, 1267, 1274, 1281, 1288,
1302, 1309, 1316, 1323, 1337, 1344, 1351, 1358, 1372, 1379, 1386, 1393, 1407, 1414, 1421, 1428, 1442,
1449, 1456, 1463, 1477, 1484, 1491, 1498, 1512, 1519, 1526, 1533, 1547, 1554, 1561, 1568, 1582, 1589,
1596, 1603, 1617, 1624, 1631, 1638, 1652, 1659, 1666, 1673, 1687, 1694, 1701, 1708, 1722, 1729, 1736,
1743, 1757, 1764, 1771, 1778, 1792, 1799, 1806, 1813, 1827, 1834, 1841, 1848, 1862, 1869, 1876, 1883,
1897, 1904, 1911, 1918, 1932, 1939, 1946, 1953, 1967, 1974, 1981, 1988]

RESULT: Thus, a program which makes use of function to display all such numbers which are divisible by
7 but are not a multiple of 5, between 1000 and 2000 was executed successfully.
4.Python Programs using List
a) Write a program which accepts a sequence of comma separated numbers from console and generate a
list and a tuple which contains every number. Suppose the following input is supplied to the program: 34,
67, 55, 33, 12, 98. Then, the output should be: [‘34’,’67’,’55’,’12’,’98’,] (‘34’,’67’,’55’,’12’,’98’).
AIM:
To Write a program which accepts a sequence of comma separated numbers from console and generate
a list and a tuple which contains every number. Suppose the following input is supplied to the program: 34,
67, 55, 33, 12, 98. Then, the output should be: [‘34’,’67’,’55’,’12’,’98’,] (‘34’,’67’,’55’,’12’,’98’).
ALGORITHM:
Step 1:Start.
Step 2: Define display function.
Step 4: Split the input values into a list and assign them to a variable 1.
Step 5: Make the list as a tuple and assign it to variable 2.
Step 6: Print list.
Step 7: Print tuple
Step 8: Stop.

PROGRAM:
values = input ("Input some comma separated numbers: ")
list = values. Split (",")
tuple = tuple(list)
print ('List:‘, list)
print ('Tuple:‘, tuple)

OUTPUT:
Enter some numbers : 34, 67, 55, 33, 12, 98.
List: ['34', ' 67', ' 55', ' 33', ' 12', ' 98.']
Tuple: ('34', ' 67', ' 55', ' 33', ' 12', ' 98.')

RESULT: Thus, a program which accepts a sequence of comma separated numbers from console and
generate a list and a tuple which contains every number. Suppose the following input is supplied to the
program: 34, 67, 55, 33, 12, 98. Then, the output should be: [‘34’,’67’,’55’,’12’,’98’,]
(‘34’,’67’,’55’,’12’,’98’). was executed successfully.
5.Python Programs using String, Tuples, NumPy array.
a) Accepts a string and calculate the number of upper-case letters and lower-case letters.
AIM:
To Accepts a string and calculate the number of upper-case letters and lower-case letters.
ALGORITHM:
Step 1:Start.
Step 2: Take a string from the user.
Step 4: Initialize the two-count variable to 0.
Step 5: Use a for loop to travers char in the string and.
Step 6: Increment the first count each time a lowercase.
Step 7: Increment the second count variable each time a uppercase
Step 8: Char in encounter.
Step 8: Print the output.
PROGRAM:
string=input ("Enter string:")
count1=0
count2=0
for i in string:
if (i. islower ()):
count1=count1+1
elif (i. isupper ()):
count2=count2+1
print ("The number of lowercase characters is:")
print(count1)
print ("The number of uppercase characters is:")
print(count2)
OUTPUT:
Enter a string: Watermelon
The number of lowercase characters is: 6
The number of uppercase characters is: 4

RESULT: Thus accepts a string and calculate the number of upper-case letters and lower-case letters. was
executed successfully.
b) Write a python program to check whether the given string is palindrome or not.
AIM:
To Write a python program to check whether the given string is palindrome or not.
ALGORITHM:
Step 1:Start.
Step 2: Get input from the user.
Step 4: Using slice operation check the string is reversed or not.
Step 5: if yes, print palindrome.
Step 6: else, print not palindrome.
Step 7: Stop.
PROGRAM:
string=input ("Enter string:")
if (string==string [::-1]):
print ("The string is a palindrome")
else:
print ("The string is not a palindrome”)

OUTPUT:
Enter a string:malayalam
malayalam is a palindrome word

RESULT: Thus python program to check whether the given string is palindrome or not. was executed
successfully
d) Multiply all the numbers in a list.
AIM:
To multiply all numbers in a list.
ALGORITHM:
Step 1:Start.
Step 2: Declare a variable mul and set it to 1
Step 3: Run a loop for all elements in the list.
Step 4: Multiply all element to the mul.
Step 5: Return mul.
Step 6: Print value return by the function.
Step 7: Stop.

PROGRAM:
List= [3,5,2,1,4]
mul=1
for i in List:
mul=mul*i
print ("Multiplication of all numbers is:", mul)

OUTPUT:
6

RESULT: Thus multiplication of all numbers in a list was executed successfully


6.Python Programs using Dictionary
a) Create a dictionary and apply the following methods 1) Print the dictionary items 2) access items 3) use
get () 4) change values 5) use len ().
AIM:
To Create a dictionary and apply the following methods 1) Print the dictionary items 2) access
items 3) use get () 4) change values 5) use len ().
ALGORITHM:
Step 1: Start.
Step 2: get dic values
Step 3: get file address
Step 4: read file
Step 5: print the output
Step 6: Stop.

PROGRAM:
dic = { 'Name' : 'Nandini', 'Age' : 19 }
print ("The constituents of dictionary as string are : ",str(dic))
print ("The constituents of dictionary as list are : ",dic.items())
print ("The size of dicis : ",len(dic))
print ("Value : %s" % dic.get('Age'))

OUTPUT:
The constituents of dictionary as string are : {'Name': 'Nandini', 'Age': 19}
The constituents of dictionary as list are : dict_items([('Name', 'Nandini'), ('Age', 19)])
The size of dicis: 2
Value : 19

RESULT: Thus a dictionary and apply the following methods 1) Print the dictionary items 2) access items
3) use get () 4) change values 5) use len (). was executed successfully
7.Python Programs using files
a) Write python script to display file contents.
AIM:
To Write python script to display file contents.
ALGORITHM:
Step 1:Start.
Step 2: getting a file name
Step 3: getting a file address
Step 4: read the file
Step 5: print the file
Step 6: Stop.

PROGRAM:
file1 = open("d:/mytext.txt", "r")
s = file1.read()
print(s)
file1.close()

OUTPUT:
My test.txt

RESULT: Thus a python script to display file contents was executed successfully
b) Write python script to copy file contents from one file to another.
AIM:
To Write python script to copy file contents from one file to another.

ALGORITHM:
Step 1:Start.
Step 2: Open one file called test.txt in read mode.
Step3: Open another file out.txt in write mode.
Step 4: Read each line from the input file and write it into the output file.
Step 5: Stop.

PROGRAM:
with open('first.txt','r') as firstfile, open('second.txt','w') as secondfile:
for line in firstfile:
secondfile.write(line)

OUTPUT:

Case 1:
Contents of file(first.txt):
Hello world

Output(second.text):
Hello world

Case 2:
Contents of file(first.txt):
Sanfoundry

Output(out.text):
Sanfoundry

RESULT: Thus python script to copy file contents from one file to another was executed successfully
8. Python Programs using Exceptions.
AIM:
To Python Programs using Exceptions.

ALGORITHM:
Step 1:Start.
Step 2: create a list
Step 3:assign a index to the element
Step 4: call the index of the element
Step 5: Stop.

PROGRAM:

a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
print ("Fourth element = %d" %(a[3]))

except:
print ("An error occurred”)

RESULT:
Second element = 2
An error occurred

RESULT: Thus Python Programs using Exceptions was executed successfully


9. Calculation of the Area: Don’t measure.
AIM:
To Calculation of the Area: Don’t measure.

ALGORITHM:
Step 1:Start.
Step 2: assign a numpy array
Step 3: assign a list to array
Step 4: compute the area using trapezoidal rule
Step 5: compute the area using the composite simpson’s rule.
Step 6: print the area
Step 7: Stop.

PROGRAM:
import numpy as np
from scipy.integrate import simps
from numpy import trapz

# The y values. A numpy array is used here,


# but a python list could also be used.
y = np.array([5, 20, 4, 18, 19, 18, 7, 4])

# Compute the area using the composite trapezoidal rule.


area = trapz(y, dx=5)
print("area =", area)

# Compute the area using the composite Simpson's rule.


area = simps(y, dx=5)
print("area =", area)

OUTPUT:
area = 452.5
area = 460.0

RESULT: Thus Python Programs using Calculation of the Area: Don’t measure was executed successfully
10. Monte Hall : 3 doors and a twist.
AIM:
To write a python programme for Monte Hall : 3 doors and a twist.

ALGORITHM:
Step 1: start.
Step 2: scenario #1 for always switching:
you choose door #1.the host opens door #3 , because the prize is behind door #2, and asks if you want to
switch. You decide to switch to door #2you win!
Step 3: scenario #2 for always switching
you choose door #2.the host opens door #3 or door #1 , because the prize is behind door # 2, and asks if you
want to switch. You decide to switch to door #1 or door #3you lose.
Step 4: scenario #3 for always switching
you choose door #3. The host opens door #1 , because the prize is behind door #2, and asks if you want to
switch. You decide to switch to door #2you win!
Step 7: Stop.

PROGRAM:
import random
def play_monty_hall(choice):
prizes = ['goat', 'car', 'goat']
random.shuffle(prizes)
while True:
opening_door = random.randrange(len(prizes))
if prizes[opening_door] != 'car' and choice-1 != opening_door:
break
opening_door = opening_door + 1
print('We are opening the door number-%d' % (opening_door))
options = [1,2,3]
options.remove(choice)
options.remove(opening_door)
switching_door = options[0]
print('Now, do you want to switch to door number-%d? (yes/no)' %(switching_door))
answer = input()
if answer == 'yes':
result = switching_door - 1
else:
result = choice - 1
print('And your prize is ....', prizes[result].upper())
choice = int(input('Which door do you want to choose? (1,2,3): '))
play_monte_hall(choice)

OUTPUT:

RESULT: Thus python programme for Monte Hall : 3 doors and a twist was executed successfully
11. Sorting: Arrange the books
AIM:
To write a python programme for Sorting: Arrange the books.

ALGORITHM:
Step 1:Start.

Step 2: AddBookToFront(newBook) : This method will create a new Node with the
new Book object as its data value and then add the newly created node to the front of the linked list.

Step 3: SortByAuthorName(): This method will sort the linked list by the book author’s name in
ascending order.

Step 4: RemoveBookAtPosition(n): This method will remove the node at position n in the linked
list. Assume that the first node of the linked list has a position number of 0 and the second node has a
position number of 1 and so on.

Step 5: Display Book(): This method will traverse the linked list from its first node to its last node
and print the data value (i.e., the id, book Name and author Name of the Book object) of each node.

Step 6: AddBookAtPosition(new Book, n) : This method will create a new Node with the new
Book object as its data value and then add the newly created node at position n of the linked list. Assume
that the first node of the linked list has a position number of 0 and the second node has a position number of
1 and so on.

Step 7: Stop.

PROGRAM:
class Book:
def __init__(self,id,bookName,authorName,nextNode=None):
self.id = id
self.bookName = bookName
self.authorName = authorName
self.nextNode = nextNode

def getId(self):
return self.id

def getBookName(self):
return self.bookName

def getAuthorName(self):
return self.authorName

def getNextNode(self):
return self.nextNode

def setNextNode(self,val):
self.nextNode = val
class LinkedList:
def __init__(self,head = None):
self.head = head
self.size = 0

def getSize(self):
return self.size

def AddBookToFront(self,newBook):
newBook.setNextNode(self.head)
self.head = newBook
self.size+=1

def DisplayBook(self):
curr = self.head
while curr:
print(curr.getId(),curr.getBookName(),curr.getAuthorName())
curr = curr.getNextNode()

def RemoveBookAtPosition(self,n):
prev = None
curr = self.head
curPos = 0
while curr:
if curPos == n:
if prev:
prev.setNextNode(curr.getNextNode())
else:
self.head = curr.getNextNode()
self.size = self.size - 1
return True
prev = curr
curr = curr.getNextNode()
curPos = curPos + 1
return False

def AddBookAtPosition(self,newBook,n):
curPos = 1
if n == 0:
newBook.setNextNode(self.head)
self.head = newBook
self.size+=1
return
else:
currentNode = self.head
while currentNode.getNextNode() is not None:
if curPos == n:
newBook.setNextNode(currentNode.getNextNode())
currentNode.setNextNode(newBook)
self.size+=1
return
currentNode = currentNode.getNextNode()
curPos = curPos + 1
if curPos == n:
newBook.setNextNode(None)
currentNode.setNextNode(newBook)
self.size+=1
else:
print("cannot add",newBook.getId(),newBook.getBookName(),"at that position")

def SortByAuthorName(self):
for i in range(1,self.size):
node1 = self.head
node2 = node1.getNextNode()
while node2 is not None:
if node1.authorName > node2.authorName:
temp = node1.id
temp2 = node1.bookName
temp3 = node1.authorName

node1.id = node2.id
node1.bookName = node2.bookName
node1.authorName = node2.authorName

node2.id = temp
node2.bookName = temp2
node2.authorName = temp3
node1 = node1.getNextNode()
node2 = node2.getNextNode()

myLinkedList = LinkedList()
nodeA = Book("#1","cool","Isaac")
nodeB = Book("#2","amazing","Alfred")
nodeC = Book("#3","hello","John")
nodeD = Book("#4","why","Chase")
nodeE = Book("#5","good","Mary")
nodeF = Book("#6","hahaha","Radin")
myLinkedList.AddBookToFront(nodeA)
myLinkedList.AddBookToFront(nodeB)
myLinkedList.AddBookToFront(nodeC)
myLinkedList.AddBookAtPosition(nodeD,1)
myLinkedList.AddBookAtPosition(nodeE,1)
myLinkedList.AddBookAtPosition(nodeF,1)
myLinkedList.RemoveBookAtPosition(2)
myLinkedList.RemoveBookAtPosition(2)
myLinkedList.DisplayBook()
myLinkedList.SortByAuthorName()
print(myLinkedList.getSize())
myLinkedList.DisplayBook()
OUTPUT:
Book("#1","cool","Isaac")
Book("#2","amazing","Alfred")
Book("#3","hello","John")
Book("#4","why","Chase")
Book("#5","good","Mary")
Book("#6","hahaha","Radin")

RESULT: Thus a python programme for Sorting: Arrange the books was executed successfully
12.Searching: Find in seconds.
AIM:
To write a python programme for Searching: Find in seconds.

ALGORITHM:
Step 1:Start.
Step 2: importing the module
Step 3: generate 10 timestamp
Step 4: converting pandas series into data frame
Step 5: extracting seconds from time stamp
Step 6: display data frame
Step 7: Stop.

PROGRAM:
# importing the module
import pandas as pd
# generating 10 timestamp starting from '2016-10-10 09:21:12'
date1 = pd.Series(pd.date_range('2016-10-10 09:21:12',
periods = 10, freq = 's'))
# converting pandas series into data frame
df = pd.DataFrame(dict(GENERATEDTIMESTAMP = date1))
# extracting seconds from time stamp
df['extracted_seconds_timestamp'] = df['GENERATEDTIMESTAMP'].dt.second
# displaying DataFrame
display(df)

OUTPUT:
The time of execution of above program is : 0.001995563507080078

RESULT: Thus a python programme for Searching: Find in seconds was executed successfully
13. Anagram.
AIM:
To write a python programme for Anagram.

ALGORITHM:
Step 1:Start.

Step 2: Get the string inputs from the user and store them in separate variables.

Step 3:Use the sort() method to sort both the strings into lists.
Step 4: Check both lists if they are forming anagram or not
Step 5:Print the result
Step 6: Stop.

PROGRAM:
from collections import Counter
def check(s1, s2):
if(Counter(s1) == Counter(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
s1 = "listen"
s2 = "silent"
check(s1, s2)

OUTPUT:
Input : s1 = "listen"
s2 = "silent"
Output : The strings are anagrams

RESULT: Thus a python programme for Anagram was executed successfully


14. Lottery Simulation - Profit or Loss.
AIM:
To write a python programme for Lottery Simulation - Profit or Loss.

ALGORITHM:
Step 1:Start.
Step 2: define a random number
Step 3: assign random integer number
Step 4: assign lotto integer number
Step 5: Iterate the function for different values
Step 6: Print the random number.
Step 7: Stop.

PROGRAM:
import random

def randomNum():
for iteration, num in enumerate(range(4)):
first = random.randint(1,10)
second = random.randint(1,10)
third = random.randint(1,10)
fourth = random.randint(1,10)
print('Lotto number 1', first)
print('Lotto number 2', second)
print('Lotto number 3', third)
print('Lotto number 4', fourth)
print('the number of tries', iteration)
print(randomNum())
OUTPUT:

RESULT: Thus a python programme for Lottery Simulation - Profit or Loss was executed successfully
15. Simulate a password generator.
AIM:
To Simulate a password generator.
ALGORITHM:
Step 1:Start.
Step 2: Ask the user to enter the length of the password.
Step 3: Shuffle the characters using the random.shuffle method.
Step 4:Initialize an empty list to store the password.
Step 5:Write a loop that iterates length times.
Step 6:Pick a random character from all the characters using the random.choice method.

Step 7:Append the random character to the password.

Step 8:Shuffle the resultant password list to make it more random.

Step 9:Convert the password list to string using the join method.

Step 10:Print the password.

Step 11: Stop.

PROGRAM:
import string
import random
## characters to generate password from
characters = list(string.ascii_letters + string.digits + "!@#$%^&*()")
def generate_random_password():
## length of password from the user
length = int(input("Enter password length: "))
## shuffling the characters
random.shuffle(characters)
## picking random characters from the list
password = []
for i in range(length):
password.append(random.choice(characters))

## shuffling the resultant password


random.shuffle(password)
## converting the list to string
## printing the list
print("".join(password))
## invoking the function
generate_random_password()

OUTPUT:
Enter password length: 10
Enter alphabets count in password: 3
Enter digits count in password: 2
Enter special characters count in password: 3
V2(&#XlQq1

RESULT: Thus a python programme for password generator was executed successfully
16. Simulate a grade book for a teacher.
AIM:
To Simulate a grade book for a teacher.

ALGORITHM:
Step 1:Start.
Step 2: Calculate Grade of Student based on Marks obtained in 5 Subjects.Based on Marks obtained
in n number of Subjects
Step 3: If mark contains decimal values like 98.6, 86.9 etc., then replace int with float.
Step 4: Now enter marks obtained in 5 subjects say 89, 99, 98, 92, 77 and then press ENTER key to see the
grade obtained according to marks entered
Step 5: This program uses for loop to receive marks obtained in 5 subjects. It also uses for loop to find the
total mark
Step 6: Stop.

PROGRAM:
print("Enter Marks Obtained in 5 Subjects: ")
markOne = int(input())
markTwo = int(input())
markThree = int(input())
markFour = int(input())
markFive = int(input())

tot = markOne+markTwo+markThree+markFour+markFive
avg = tot/5

if avg>=91 and avg<=100:


print("Your Grade is A1")
elif avg>=81 and avg<91:
print("Your Grade is A2")
elif avg>=71 and avg<81:
print("Your Grade is B1")
elif avg>=61 and avg<71:
print("Your Grade is B2")
elif avg>=51 and avg<61:
print("Your Grade is C1")
elif avg>=41 and avg<51:
print("Your Grade is C2")
elif avg>=33 and avg<41:
print("Your Grade is D")
elif avg>=21 and avg<33:
print("Your Grade is E1")
elif avg>=0 and avg<21:
print("Your Grade is E2")
else:
print("Invalid Input!")
markOne = int(input())
markTwo = int(input())
markThree = int(input())
markFour = int(input())
markFive = int(input())
markOne = float(input())
markTwo = float(input())
markThree = float(input())
markFour = float(input())
markFive = float(input())

mark = []
tot = 0
print("Enter Marks Obtained in 5 Subjects: ")
for i in range(5):
mark.insert(i, input())

for i in range(5):
tot = tot + int(mark[i])
avg = tot/5

if avg>=91 and avg<=100:


print("Your Grade is A1")
elif avg>=81 and avg<91:
print("Your Grade is A2")
elif avg>=71 and avg<81:
print("Your Grade is B1")
elif avg>=61 and avg<71:
print("Your Grade is B2")
elif avg>=51 and avg<61:
print("Your Grade is C1")
elif avg>=41 and avg<51:
print("Your Grade is C2")
elif avg>=33 and avg<41:
print("Your Grade is D")
elif avg>=21 and avg<33:
print("Your Grade is E1")
elif avg>=0 and avg<21:
print("Your Grade is E2")
else:
print("Invalid Input!")

OUTPUT:
RESULT: Thus a python programme for a grade book for a teacher was executed successfully.
17. Rock Paper and Scissor.
AIM:
To write a python programme for Rock Paper and Scissor.

ALGORITHM:
Step 1:Start
Step 2: import random module( )
Step 3: Print multiline instruction
Step 4: take the input from user
Step 5: Printing either user or computer wins
Step 6: Winning Rules as follows :
Rock vs paper-> paper wins
Rock vs scissor-> Rock wins
paper vs scissor-> scissor wins.
Step 7: stop

PROGRAM:
# import random module
import random
# Print multiline instruction
# performstring concatenation of string
print("Winning Rules of the Rock paper scissor game as follows: \n"
+"Rock vs paper->paper wins \n"
+ "Rock vs scissor->Rock wins \n"
+"paper vs scissor->scissor wins \n")
while True:
print("Enter choice \n 1 for Rock, \n 2 for paper, and \n 3 for scissor \n")

# take the input from user


choice = int(input("User turn: "))

# OR is the short-circuit operator


# if any one of the condition is true
# then it return True value

# looping until user enter invalid input


while choice > 3 or choice < 1:
choice = int(input("enter valid input: "))

# initialize value of choice_name variable


# corresponding to the choice value
if choice == 1:
choice_name = 'Rock'
elif choice == 2:
choice_name = 'paper'
else:
choice_name = 'scissor'

# print user choice


print("user choice is: " + choice_name)
print("\nNow its computer turn.......")

# Computer chooses randomly any number


# among 1 , 2 and 3. Using randint method
# of random module
comp_choice = random.randint(1, 3)

# looping until comp_choice value


# is equal to the choice value
while comp_choice == choice:
comp_choice = random.randint(1, 3)

# initialize value of comp_choice_name


# variable corresponding to the choice value
if comp_choice == 1:
comp_choice_name = 'Rock'
elif comp_choice == 2:
comp_choice_name = 'paper'
else:
comp_choice_name = 'scissor'

print("Computer choice is: " + comp_choice_name)

print(choice_name + " V/s " + comp_choice_name)

# condition for winning


if((choice == 1 and comp_choice == 2) or
(choice == 2 and comp_choice ==1 )):
print("paper wins => ", end = "")
result = "paper"

elif((choice == 1 and comp_choice == 3) or


(choice == 3 and comp_choice == 1)):
print("Rock wins =>", end = "")
result = "Rock"
else:
print("scissor wins =>", end = "")
result = "scissor"

# Printing either user or computer wins


if result == choice_name:
print("<== User wins ==>")
else:
print("<== Computer wins ==>")

print("Do you want to play again? (Y/N)")


ans = input()

# if user input n or N then condition is True


if ans == 'n' or ans == 'N':
break

# after coming out of the while loop


# we print thanks for playing
print("\nThanks for playing")

OUTPUT:
Winning Rules of the Rock paper and scissor game as follows:
rock vs paper->paper wins
rock vs scissors->rock wins
paper vs scissors->scissors wins
Enter choice
1. Rock
2. paper
3. scissor
User turn: 1
User choice is: Rock
Now its computer turns.......
computer choice is: paper
Rock V/s paper
paper wins =>computer wins
do you want to play again?
N
RESULT: Thus a python programme for Rock Paper and Scissor was executed successfully.
18. Converting an Image to Black and White/Grayscale.
AIM:
To write a python programme for Converting an Image to Black and White/Grayscale.

ALGORITHM:
Step 1: Start.
Step 2: convert method: Converting between digital image color modes

Step 3: Converting image mode to 1, L or LA

Step 4: ImageEnhance.Color () method to get Grayscale images

Step 5: Manually converting each color pixel to grayscale pixels

Step 6: Stop.
PROGRAM:
from PIL import Image, ImageEnhance

file = "C://Users/ABC/20.jpg"
img = Image.open(file)
img.show()
from PIL import Image

file = "C://Users/ABC/20.jpg"
img = Image.open(file)

img.convert("1")
img.show()
from PIL import Image

file = "C://Users/ABC/20.jpg"
img = Image.open(file)

img = img.convert("L")
img.show()
from PIL import Image

file = "C://Users/ABC/20jpg"
img = Image.open(file)

filter = ImageEnhance.Color(img)
filter.enhance(0)
img.show()

from PIL import Image, ImageEnhance


img = Image.open("Desktop/11.jpg")
img_data = img.getdata()

lst=[]
for i in img_data:

# lst.append(i[0]*0.299+i[1]*0.587+i[2]*0.114) ### Rec. 609-7 weights


lst.append(i[0]*0.2125+i[1]*0.7174+i[2]*0.0721) ### Rec. 709-6 weights

new_img = Image.new("L", img.size)


new_img.putdata(lst)

new_img.show()

OUTPUT:

Gray scale conversion:

RESULT: Thus a python programme for Converting an Image to Black and White/Grayscale.
was executed successfully.
19. Blurring an Image, Edge Detection and Reducing the Image Size.
AIM:
To write a python programme for Blurring an Image, Edge Detection and Reducing the Image Size.

ALGORITHM:
Step 1:Start.
Step 2: import modules
Step 3: making filter of 3 by 3 filled with 1 divide
Step 4: divide by 9 for normalization
Step 5: divide by 25 for normalization
Step 6: divide by 49 for normalization
Step 7: Stop.

PROGRAM:
import cv2
import numpy as np
image = cv2.imread('geek.jpg')
# making filter of 3 by 3 filled with 1 divide
# by 9 for normalization
blur_filter1 = np.ones((3, 3), np.float)/(9.0)
# making filter of 5 by 5 filled with 1 divide
# by 25 for normalization
blur_filter2 = np.ones((5, 5), np.float)/(25.0)
# making filter of 7 by 7 filled with 1 divide
# by 49 for normalization
blur_filter3 = np.ones((7, 7), np.float)/(49.0)
image_blur1 = cv2.filter2D(image, -1, blur_filter1)
image_blur2 = cv2.filter2D(image, -1, blur_filter2)
image_blur3 = cv2.filter2D(image, -1, blur_filter3)
cv2.imshow('geek', image)
cv2.imshow('geek_blur1', image_blur1)
cv2.imshow('geek_blur2', image_blur2)
cv2.imshow('geek_blur3', image_blur3)
cv2.waitKey(0)
cv2.destroyAllWindows()

OUTPUT:
RESULT: Thus a python programme for Blurring an Image, Edge Detection and Reducing the Image Size
was executed successfully.

You might also like