UNIT-1
[Link] a python program to find largest of three numbers.
SOURCECODE:
# Python program to find the largest number among the three input numbers
# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12
# uncomment following lines to take three numbers from user
#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)
[Link] a Python program to display all the prime numbers within an interval
lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
[Link] progrm to swap two numbers witout using a temporry variable
P = 5 # P = 0101
Q = 10 # Q = 1010
print ("Variables Value Before Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
# Method to swap 'P' and 'Q'
P ^= Q # P = 1111, Q = 1010
Q ^= P # Q = 0101, P = 1111
P ^= Q # P = 1010, Q = 0101
print ("Variables Value After Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
[Link] a programs on Operators with suitable examples
i)Arithmetic operators
a = 32 # Initialize the value of a
b = 6 # Initialize the value of b
print('Addition of two numbers:',a+b)
print('Subtraction of two numbers:',a-b)
print('Multiplication of two numbers:',a*b)
print('Division of two numbers:',a/b)
print('Reminder of two numbers:',a%b)
print('Exponent of two numbers:',a**b)
print('Floor division of two numbers:',a//b)
ii)Relational operators
a = 32 # Initialize the value of a
b = 6 # Initialize the value of b
print('Two numbers are equal or not:',a==b)
print('Two numbers are not equal or not:',a!=b)
print('a is less than or equal to b:',a<=b)
print('a is greater than or equal to b:',a>=b)
print('a is greater b:',a>b)
print('a is less than b:',a<b)
iii)Assignment Operators
a = 32 # Initialize the value of a
b = 6 # Initialize the value of b
print('a=b:', a==b)
print('a+=b:', a+b)
print('a-=b:', a-b)
print('a*=b:', a*b)
print('a%=b:', a%b)
print('a**=b:', a**b)
print('a//=b:', a//b)
iv)Logical Operators
a = 5 # initialize the value of a
print(Is this statement true?:',a > 3 and a < 5)
print('Any one statement is true?:',a > 3 or a < 5)
print('Each statement is true then return False and vice-versa:',(not(a > 3 and a <
5)))
v)Bitwise Operators
if a = 7
b = 6
then, binary (a) = 0111
binary (b) = 0110
hence, a & b = 0011
a | b = 0111
a ^ b = 0100
~ a = 1000
Let, Binary of x = 0101
Binary of y = 1000
Bitwise OR = 1101
8 4 2 1
1 1 0 1 = 8 + 4 + 1 = 13
Bitwise AND = 0000
0000 = 0
Bitwise XOR = 1101
8 4 2 1
1 1 0 1 = 8 + 4 + 1 = 13
Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6
~x = -6
a = 5 # initialize the value of a
b = 6 # initialize the value of b
print('a&b:', a&b)
print('a|b:', a|b)
print('a^b:', a^b)
print('~a:', ~a)
print('a<<b:', a<<b)
print('a>>b:', a>>b)
vi)Membership Operators
x = ["Rose", "Lotus"]
print(' Is value Present?', "Rose" in x)
print(' Is value not Present?', "Riya" not in x)
vii)Identity Operators
a = ["Rose", "Lotus"]
b = ["Rose", "Lotus"]
c = a
print(a is c)
print(a is not c)
print(a is b)
print(a is not b)
print(a == b)
print(a != b)
[Link] a program to add and multiply Comlex numbers
# Python program to add
# two complex numbers
# function that returns
# a complex number after
# adding
def addComplex( z1, z2):
return z1 + z2
# Driver's code
z1 = complex(2, 3)
z2 = complex(1, 2)
print( "Addition is : ", addComplex(z1, z2))
# Python program to demonstrate
# multiplication of complex numbers
def mulComplex( z1, z2):
return z1*z2
# driver code
z1 = complex(2, 3)
z2 = complex(4, 5)
print("Multiplication is :", mulComplex(z1,z2))
[Link] a program to print multiplication of a given number
# Multiplication table (from 1 to 10) in Python
num = 19
# To take input from the user
# num = int(input("Display multiplication table of? "))
# Iterate 10 times from i = 1 to 10
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
UNIT-II
1)Write a program to define a function with multiple return values
# A Python program to return multiple
# values from a method using class
class Test:
def __init__(self):
[Link] = "geeksforgeeks"
self.x = 20
# This function returns an object of Test
def fun():
return Test()
# Driver code to test above method
t = fun()
print([Link])
print(t.x)
2)Write a program to define a function using default arguments
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
3)write a program to find the length of the string without using any library
functions
#take user input
string = 'Hello'
count = 0
for i in string:
count+=1
print(count)
4)Write a program to check if the substring is present in a given string or not.
# input strings str1 and substr
string = "geeks for geeks" # or string=input() -> taking input from the user
substring = "geeks" # or substring=input()
# splitting words in a given string
s = [Link]()
# checking condition
# if substring is present in the given string then it gives output as yes
if substring in s:
print("yes")
else:
print("no")
5)Write a program to perform the given operations on a list:
i. additionii. [Link]. [Link]
#[Link]
primes = [2, 3, 5, 7]
# Append additional prime number, saving returned result
should_be_none = [Link](11)
# Show that the prime was added
assert primes == [2, 3, 5, 7, 11]
# Show that `None` was returned
assert should_be_none is None
primes = [2, 3, 5, 7]
# Append additional prime number, saving returned result
should_be_none = [Link](11)
# Show that the prime was added
assert primes == [2, 3, 5, 7, 11]
# Show that `None` was returned
assert should_be_none is None
#[Link]
# List of friends
friends = ['Mary', 'Jim', 'Jack']
# Insert additional friend `“Molly”` before index `2`
[Link](2, 'Molly')
# Show that “Molly” was added
assert friends == ['Mary', 'Jim', 'Molly', 'Jack']
#[Link]
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Show original list
print("Original List:\n", List)
print("\nSliced Lists: ")
# Display sliced list
print(List[3:9:2])
# Display sliced list
print(List[::2])
# Display sliced list
print(List[::])
6)perform any 5 builtin functions by taking aany list
i)append
# Adds List Element as value of List.
List = ['Mathematics', 'chemistry', 1997, 2000]
[Link](20544)
print(List)
ii)insert
List = ['Mathematics', 'chemistry', 1997, 2000]
# Insert at index 2 value 10087
[Link](2, 10087)
print(List)
iii)extend
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
# Add List2 to List1
[Link](List2)
print(List1)
# Add List1 to List2 now
[Link](List1)
print(List2)
iv)count
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print([Link](1))
v)length
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))
UNIT-III
1)write a program to create tuples(name,age ,address,college) for atleast two
members and concatinate
the tuples and print the concatinated tuples
tup1 = ("Sri",33,"Guntur","LITAM"),
tup2 = ("Hari",32,"Hyd","SCREC"),
print("The original tuple 1 : " + str(tup1))
print("The original tuple 2 : " + str(tup2))
tup1=list(tup1)
tup2=list(tup2)
[Link](tup2)
print("Tuples after Concatenating : " + str(tuple(tup1)))
[Link] a program to count the number of vowels in a string (No control flow
allowed).
def vowel_count(str):
# Creating a list of vowels
vowels = "aeiouAEIOU"
# Using list comprehension to count the number of vowels in the string
count = len([char for char in str if char in vowels])
# Printing the count of vowels in the string
print("No. of vowels :", count)
# Driver code
str = "GeeksforGeeks"
# Function Call
vowel_count(str)
3)Write a program to check if a given key exists in a dictionary or not.
def checkKey(dic, key):
if dic.has_key(key):
print("Present, value =", dic[key])
else:
print("Not present")
# Driver Function
dic = {'a': 100, 'b':200, 'c':300}
key = 'b'
checkKey(dic, key)
key = 'w'
checkKey(dic, key)
4)Write a program to add a new key-value pair to an existing dictionary.
# Python program to add a key:value pair to dictionary
dict = {'key1':'geeks', 'key2':'for'}
print("Current Dict is: ", dict)
# using the subscript notation
# Dictionary_Name[New_Key_Name] = New_Key_Value
dict['key3'] = 'Geeks'
dict['key4'] = 'is'
dict['key5'] = 'portal'
dict['key6'] = 'Computer'
print("Updated Dict is: ", dict)
5)Write a program to sum all the items in a given dictionary.
# Python3 Program to find sum of
# all items in a Dictionary
# Function to print sum
def returnSum(myDict):
list = []
for i in myDict:
[Link](myDict[i])
final = sum(list)
return final
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
UNIT-IV
1. Write a program to sort words in a file and put them in another file. The output
file
should have only lower-case words, so any upper-case words from source must be
lowered.
# Taking "gfg input [Link]" as input file
# in reading mode
with open("gfg input [Link]", "r") as input:
# Creating "gfg output [Link]" as output
# file in write mode
with open("gfg output [Link]", "w") as output:
# Writing each line from input file to
# output file using loop
for line in input:
[Link]([Link]())
gfg input [Link]: HI I am Srihari RAO
working as a ASSISTANT PROFESSOR in LOYOLA
INSTITUTE OF TECHNOLOGY AND MANAGEMENT
I have 6 YEARS OF TEACHING EXPERIENCE.
gfg output [Link]: hi i am srihari rao
working as a assistant professor in loyola
institute of technology and management
i have 6 years of teaching experience.
2. Python program to print each line of a file in reverse order.
# Open the file in write mode
f2 = open("[Link]", "w")
# Open the input file again and get
# the content as list to a variable data
with open("[Link]", "r") as myfile:
data = [Link]()
# We will just reverse the
# array using following code
data_2 = data[::-1]
# Now we will write the fully reverse
# list in the output2 file using
# following command
[Link](data_2)
[Link]()
Output:
[Link]:
hi i am srihari rao
working as a assistant professor in loyola
institute of technology and management
i have 6 years of teaching experience.
[Link]:
i have 6 years of teaching experience.
institute of technology and management
working as a assistant professor in loyola
hi i am srihari rao
3. Python program to compute the number of characters, words and lines in a file.
# Function to count number of characters, words, spaces and lines in a file
def counter(fname):
# variable to store total word count
num_words = 0
# variable to store total line count
num_lines = 0
# variable to store total character count
num_charc = 0
# variable to store total space count
num_spaces = 0
# opening file using with() method
# so that file gets closed
# after completion of work
with open(fname, 'r') as f:
# loop to iterate file
# line by line
for line in f:
# incrementing value of num_lines with each
# iteration of loop to store total line count
num_lines += 1
# declaring a variable word and assigning its value as Y
# because every file is supposed to start with a word or a character
word = 'Y'
# loop to iterate every
# line letter by letter
for letter in line:
# condition to check that the encountered character
# is not white space and a word
if (letter != ' ' and word == 'Y'):
# incrementing the word
# count by 1
num_words += 1
# assigning value N to variable word because until
# space will not encounter a word can not be completed
word = 'N'
# condition to check that the encountered character is a white
space
elif (letter == ' '):
# incrementing the space
# count by 1
num_spaces += 1
# assigning value Y to variable word because after
# white space a word is supposed to occur
word = 'Y'
# loop to iterate every character
for i in letter:
# condition to check white space
if(i !=" " and i !="\n"):
# incrementing character
# count by 1
num_charc += 1
# printing total word count
print("Number of words in text file: ",
num_words)
# printing total line count
print("Number of lines in text file: ",
num_lines)
# printing total character count
print('Number of characters in text file: ',
num_charc)
# printing total space count
print('Number of spaces in text file: ',
num_spaces)
# Driver Code:
if __name__ == '__main__':
fname = '[Link]'
try:
counter(fname)
except:
print('File not found')
[Link]:
hi i am srihari rao
working as a assistant professor in loyola
institute of technology and management
i have 6 years of teaching experience.
Output:
Number of words in text file:26
Number of lines in tet file:4
Number of characters in text file:117
Number of spaces in text file:22
4. Write a program to create, display, append, insert and reverse the order of the
items
in the array.
class check():
def __init__(self):
self.n=[]
def add(self,a):
return [Link](a)
def remove(self,b):
[Link](b)
def dis(self):
return (self.n)
obj=check()
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Delete")
print("3. Display")
choice=int(input("Enter choice: "))
if choice==1:
n=int(input("Enter number to append: "))
[Link](n)
print("List: ",[Link]())
elif choice==2:
n=int(input("Enter number to remove: "))
[Link](n)
print("List: ",[Link]())
elif choice==3:
print("List: ",[Link]())
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
5. Write a program to add, transpose and multiply two matrices.
# Function to add two matrices
def add_matrices(matrix1, matrix2):
rows = len(matrix1)
columns = len(matrix1[0])
# Create a result matrix filled with zeros
result = [[0 for _ in range(columns)] for _ in range(rows)]
# Iterate over the elements and perform addition
for i in range(rows):
for j in range(columns):
result[i][j] = matrix1[i][j] + matrix2[i][j]
return result
# Example matrices
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix2 = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
# Call the function to add the matrices
result_matrix = add_matrices(matrix1, matrix2)
# Print the result matrix
for row in result_matrix:
print(row)
ii) multilication
# Define the matrices
matrix1 = [[1, 2],
[3, 4]]
matrix2 = [[5, 6],
[7, 8]]
# Create an empty result matrix
result = [[0, 0],
[0, 0]]
# Perform matrix multiplication
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
result[i][j] += matrix1[i][k] * matrix2[k][j]
# Print the result matrix
print("Result Matrix:")
for row in result:
print(row)
iii)Transpose
def transpose_matrix(matrix):
# Get the number of rows and columns in the matrix
rows = len(matrix)
cols = len(matrix[0])
# Create a new matrix with swapped dimensions
transpose = [[0 for _ in range(rows)] for _ in range(cols)]
# Fill the transpose matrix with the elements from the original matrix
for i in range(rows):
for j in range(cols):
transpose[j][i] = matrix[i][j]
return transpose
# Example matrix
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Find the transpose of the matrix
transpose = transpose_matrix(matrix)
# Print the original matrix
print("Original Matrix:")
for row in matrix:
print(row)
# Print the transpose matrix
print("\nTranspose Matrix:")
for row in transpose:
print(row)
Output
Original Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Transpose Matrix:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
6. Write a Python program to create a class that represents a shape. Include
methods
to calculate its area and perimeter. Implement subclasses for different shapes like
circle,
triangle, and square.
# define a function for calculating
# the area of a shapes
def calculate_area(name):\
# converting all characters
# into lower cases
name = [Link]()
# check for the conditions
if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
# calculate area of rectangle
rect_area = l * b
print(f"The area of rectangle is
{rect_area}.")
elif name == "square":
s = int(input("Enter square's side length: "))
# calculate area of square
sqt_area = s * s
print(f"The area of square is
{sqt_area}.")
elif name == "triangle":
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
# calculate area of triangle
tri_area = 0.5 * b * h
print(f"The area of triangle is
{tri_area}.")
elif name == "circle":
r = int(input("Enter circle's radius length: "))
pi = 3.14
# calculate area of circle
circ_area = pi * r * r
print(f"The area of circle is
{circ_area}.")
elif name == 'parallelogram':
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
# calculate area of parallelogram
para_area = b * h
print(f"The area of parallelogram is
{para_area}.")
else:
print("Sorry! This shape is not available")
# driver code
if __name__ == "__main__" :
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to find: ")
# function calling
calculate_area(shape_name)
Output:
Calculate Shape Area
Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length: 10
Enter rectangle's breadth: 15
The area of rectangle is 150.
UNIT-V
1. Python program to check whether a JSON string contains complex object or not.
import json
def is_complex_num(objct):
if '__complex__' in objct:
return complex(objct['real'], objct['img'])
return objct
complex_object =[Link]('{"__complex__": true, "real": 4, "img": 5}',
object_hook = is_complex_num)
simple_object =[Link]('{"real": 4, "img": 3}', object_hook = is_complex_num)
print("Complex_object: ",complex_object)
print("Without complex object: ",simple_object)
Output:
Complex object: (4+5j)
without complex object: {'real':4, 'img':3}
[Link] Program to demonstrate NumPy arrays creation using array () function.
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
Output:
[1 2 3 4 5]
<class '[Link]'>
3. Python program to demonstrate use of ndim, shape, size, dtype.
import numpy as np
a = [Link]([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
print("Dimension of the given Ndarray=",[Link])
print("Shape of the given Ndarray=",[Link])
print("Size of the given Ndarray=",[Link])
print("Data Type of given Ndarray=",[Link])
print("Size of each element in Ndarray=",[Link])
Output:
Dimension of the given Ndarray= 3
Shape of the given Ndarray= (2, 2, 3)
Size of the given Ndarray= 12
Data Type of given Ndarray= int64
Size of each element in Ndarray= 8
4. Python program to demonstrate basic slicing, integer and Boolean indexing.
import numpy as np
arr = [Link](25)
s = slice(2, 21, 4)
print (arr[s])
arr=[Link]([[1,2],[3,4],[5,6]])
print(arr)
arr=[Link]([[1,2],[3,4],[5,6]])
print(arr)
OUTPUT::
[[1 2]
[3 4]
[5 6]]
5. Python program to find min, max, sum, cumulative sum of array
def cumSum(s):
sm=0
cum_list=[]
for i in s:
sm=sm+i
cum_list.append(sm)
return cum_list
a=[10,20,30,40,50]
print(min(a))
print(max(a))
print(sum(a))
print(cumSum(a))
Output:
10
50
150
[10, 30, 60, 100, 150]
6. Create a dictionary with at least five keys and each key represent value as a
list where this list contains at least ten values and convert this dictionary as a
pandas data frame and explore the data through the data frame as follows:
# import pandas module import pandas
# create student dictionary of dictionaries with
# 5 students with Age ,subject and address
data = {{'Age': 15, 'subject': 'java', 'Address': 'Hyderabad'},
{'Age': 9, 'subject': 'python', 'Address': 'Hyderabad'},
{'Age': 15, 'subject': 'c/c++', 'Address': 'Guntur'},
{'Age': 21, 'subject': 'html', 'Address': 'ponnur'},
{'Age': 15, 'subject': 'c/c++', 'Address': 'delhi'}
}
# create pandas dataframe from dictionary of
# dictionaries
data = [Link](data)
# display
data
OUTPUT:::
Age subject Address
0 15 java Hyderabad
1 9 python Hyderabad
2 15 c/c++ Guntur
3 21 html ponnur
4 15 c/c++ delhi
a) Apply head () function to the pandas data frame
# Import pandas
import pandas as pd
# Create a list of dictionaries
data = [
{'Age': 15, 'subject': 'java', 'Address': 'Hyderabad'},
{'Age': 9, 'subject': 'python', 'Address': 'Hyderabad'},
{'Age': 15, 'subject': 'c/c++', 'Address': 'Guntur'},
{'Age': 21, 'subject': 'html', 'Address': 'ponnur'},
{'Age': 15, 'subject': 'c/c++', 'Address': 'delhi'}
]
# Create DataFrame
df = [Link](data)
# Apply head() function
print([Link]())
OUTPUT::
Age subject Address
0 15 java Hyderabad
1 9 python Hyderabad
2 15 c/c++ Guntur
3 21 html ponnur
4 15 c/c++ delhi
b) Perform various data selection operations on Data Frame
import pandas as pd
data = [
{'Age': 15, 'subject': 'java', 'Address': 'Hyderabad'},
{'Age': 9, 'subject': 'python', 'Address': 'Hyderabad'},
{'Age': 15, 'subject': 'c/c++', 'Address': 'Guntur'},
{'Age': 21, 'subject': 'html', 'Address': 'ponnur'},
{'Age': 15, 'subject': 'c/c++', 'Address': 'delhi'}
]
df = [Link](data)
OUTPUTT::
0 15
1 9
2 15
3 21
4 15
Name: Age, dtype: int64