0% found this document useful (0 votes)
3 views

python program lab manual Updated

The document outlines the Problem Solving and Python Programming laboratory at Raajdhani Engineering College, detailing its vision, mission, program outcomes, educational objectives, and specific outcomes for students. It includes a list of experiments, evaluation schemes, and rules for lab conduct, emphasizing the importance of ethical practices and safety. The laboratory aims to equip students with practical skills in programming and problem-solving using Python.

Uploaded by

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

python program lab manual Updated

The document outlines the Problem Solving and Python Programming laboratory at Raajdhani Engineering College, detailing its vision, mission, program outcomes, educational objectives, and specific outcomes for students. It includes a list of experiments, evaluation schemes, and rules for lab conduct, emphasizing the importance of ethical practices and safety. The laboratory aims to equip students with practical skills in programming and problem-solving using Python.

Uploaded by

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

RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR

PROBLEM SOLVING AND PYTHON PROGRAMMIMG

RAAJDHANI ENGINEERING COLLEGE


LABORATORY RECORD
SUBJECT CODE-RPL2B001
Problem solving and python programming

DEPARTMENT OF COMPUTER SCIENEC & ENGINEERING


PROBLEM SOLVING AND PYTHON PROGRAMMIMG LABORATORY
1|Page
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMIMG

VISION & MISSION OF RAAJDHANI ENGINEERING COLLEGE VISION


VISION
 To become an Institution of Academic Excellence in technical education, innovative
research, and entrepreneurship.

MISSION

 To educate students through academic courses and provide knowledge of social and
industrial needs.
 To collaborate with leading academic and scientific institutions across the globe to further
enhance education and research.
 To motivate young students on a sense of social responsibility through entrepreneurship
and startup.

PROBLEM SOLVING AND PYTHON PROGRAMMIMG LABORATORY


2|Page
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMIMG

VISION & MISSION OF DEPARTMENTOFCOMPUTER SCIENCE ENGINEERING


VISION

 To be one of the best in the country by developing globally competent engineers motivated
entrepreneurs, prospective researchers, and aspiring academicians.

 To bring up the Institution as an Institution of Academic excellence of National Standard.

 To strive to set global standards, making our students technologically superior and ethically
strong, who in turn shall contribute to the advancement of society and human kind .

MISSION
 To create globally competent students having ability to design, develop and test world class
software, keeping pace with the latest technological developments.

 To promote continuous learning, all-inclusive research in core and emerging areas.

 To inculcate the professionalism, team work, innovation and entrepreneurship among the
students.

 To exchange expertise with industry, academic and research organizations.

 To imbibe ethical and social values among students.

PROBLEM SOLVING AND PYTHON PROGRAMMIMG LABORATORY


3|Page
HANI ENGINE RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

Program Outcomes (POs)


Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering problems reaching
substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design system components
or processes that meet the specified needs with appropriate consideration for the public health and safety, and the
cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods including design
of experiments, analysis and interpretation of data, and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineeringandITtoolsincludingpredictionandmodelingtocomplexengineeringactivitieswith an understanding of the
limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health, safety,
legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in societal and
environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the engineering
practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams, and in
multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering community and
with society at large, such as, being able to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and management
principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent and life-
long learning in the broadest context of technological change.
.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


III|Page
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

Program Educational Objectives (PEOs)


1. To provide core theoretical and practical knowledge in the domain of Computer Science &
Engineering for leading successful career in industries, pursuing higher studies or entrepreneurial
endeavors.
2. To develop the ability to critically think, analyze and make decisions for offering techno-
commercially feasible and socially acceptable solutions to real life problems in the areas of
computing.
3. To imbibe lifelong learning, professional and ethical attitude for embracing global challenges and
make positive impact on environment and society.

Program Specific Outcomes (PSOs)

Students will able to :

PSO 1: Able to identify suitable data structures and algorithms to design, develop and evaluate effective
solutions for real-life and research problems.

PSO 2: Able to excel in various programming/project competitions and technological challenges laid by
professional societies.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


VI|Page
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

Course Outcomes (COs)

CO1: Students will be able to understand the concept of the Greatest Common Divisor
(GCD) of two numbers and the concept of finding the square root of a number using
Newton's method.

CO2: Students will be able to identify and understand the concept of exponentiation,
which involves raising a base number to a given power.

CO3: Students will be able to apply linear search and binary search techniques to search
for specific elements in arrays, lists, or other data structures.

CO4: Students will be able to understand the concept of prime numbers, which are natural
numbers greater than 1 that have no divisors other than 1 and themselves and compare
different prime number generation algorithms in terms of their efficiency and complexity.

CO5: Students will be able to analyze the concept of command line arguments and their
significance in program execution.

CO6: Students will be able to develop critical thinking skills by analyzing and improving
the accuracy, performance, and visual representation of the simulated elliptical orbits.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


VI|Page
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


VI|Page
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

RULES AND REGULATIONS

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


VI|Page
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

1.Access Control: Only authorized individuals, such as faculty, students, and


lab staff, are allowed entry into the laboratory.
2.Lab Etiquette: Maintain a professional and respectful environment in the lab.
Keep noise levels to a minimum to avoid disrupting others who are working. Do
not engage in any activities that may damage the lab equipment or infrastructure.
3.Lab Hours: The lab will have designated operating hours. Ensure that you
adhere to these hours and do not enter the lab outside the specified timings
without proper permission.
4.Personal Belongings: Keep personal belongings, such as bags, jackets, and
food, in designated areas or lockers to avoid clutter and prevent damage to
equipment. Do not bring any unauthorized items into the lab. Keep footwear
outside the laboratory. Arrange the chairs/desks in order before leaving the
laboratory.
5.Software Usage: Use licensed software and ensure compliance with relevant
software licenses and copyright laws. Do not install or use any unauthorized
software on lab computers.
6.Data and Privacy: Respect the privacy and confidentiality of other users' data.
Do not access, modify, or share other users' files or data without proper
authorization. Keep your own data stored securely and ensure you log out of your
accounts when finished.
7.Internet Usage: Use the internet responsibly and for academic purposes only.
Do not access or download any unauthorized or inappropriate material. Be
mindful of the bandwidth and do not engage in activities that may disrupt the
network for others.
8.Safety Precautions: Adhere to safety guidelines and protocols while working
in the lab. This includes properly handling electrical equipment, using appropriate
protective gear (such as goggles), and reporting any accidents or hazardous
situations to the lab staff.
9. Cleanliness and Maintenance: Maintain cleanliness and order in the lab.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


VI|Page
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

Clean up after yourself and keep your workspace tidy. Report any maintenance
issues or concerns to the lab staff promptly.

SAFETY PRECAUTIONS
All staff, students and others who work in laboratory must understand and agree to the information in this
document. All procedures which need to be conducted alone or after-hours need to be reviewed for hazards
and must be

 Turn off the machine once you are done using it.

 Do not plug in external devices without scanning them for computer viruses.

 Ensure that the temperature in the room stays cool, since there are a lot of machines inside a lab
as these can overheat easily. This is one of the many ways of ensuring computer safety.

 Try not to touch any of the circuit boards and power sockets when a device is connected to them
and switched on.

 Always maintain an extra copy of all your important data files.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


VI|Page
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

CONTENTS
SL
NAME OF THE EXPERIMENTS PAGENO.
NO
Compute the GCD of two numbers. 12-13
1
Find the square root of a number (Newton's method) 14-15
2
Find the Exponentiation (power of a number) 16-17
3
Find the maximum of a list of numbers 18-19
4
Linear search and Binary search. 20-22
5
Selection sort, Insertion sort 23-24
6
Merge sort. 25-26
7
First n prime numbers. 27-28
8
Multiply matrices. 29-30
9
Programs that take command line arguments (word count) 31-32
10
Find the most frequent words in a text read from a file 33-34
11
Simulate elliptical orbits in Pygame. 35-36
12
Simulate bouncing ball using Pygame. 37-38
13

PROBLEM SOLIVING AND PYTHON PROGRAMMING LABORATORY


8
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

INDEX SHEET/VALUATION SHEET

(DEPT.OF COMPUTER SCIENCE ENGG.)


SL EXPERIMENT Attendance Lab Lab Final Signature
NO. &performance Record Viva Experiment & With Date
(20) (20) (10) Viva (50)

1. Compute the GCD of two numbers.

2. Find the square root of a number


(Newton's method).

3. Exponentiation
(power of a number).

4. Find the maximum of a list of


numbers .
5. Linear search and Binary search.

6. Selection sort, Insertion sort .


7. Merge sort.

8. First n prime numbers.

9. Multiply matrices

10.Programs that take command line


arguments (word count)

11.Find the most frequent words in a


text read from a file .

12.Simulate elliptical orbits in Pygame.

13.Simulate bouncing ball using


Pygame.
PROBLEM SOLIVING AND PYTHON PROGRAMMING LABORATORY
9
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

PRACTICAL/SESSIONALEVALUTIONSCHEME

Pass mark willbe50%which means students have to score 50out of 100.

Evaluation Scheme
Attendance &Daily performance 20
Lab Record 20
Lab Viva 10
Final Experiment &Viva 50
Total 100

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


10
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

Experiment -1
AIM OF THE EXPERIMENT: Compute the GCD of two numbers

Requirement Specification:
Installation of Python in System
Pen and paper
Calculator (optional)
Two numbers to compute their GCD
THEORY:
The objective of this laboratory experiment is to compute the Greatest Common
Divisor (GCD) of two given numbers using the Euclidean algorithm.
PROCEDURE
 Write down the two numbers whose GCD is to be computed.
 Apply the Euclidean algorithm by performing the following steps:
a. Divide the larger number by the smaller number.
b. Write down the remainder obtained.
c. Replace the larger number with the smaller number and the smaller number
with the remainder obtained in step b.
d. Repeat steps a-c until the remainder obtained is zero.
 The GCD of the two numbers is the last non-zero remainder obtained in step 2.
Program development:
#Python Program to find GCD of Two Numbers a temp variable
num1=int (input())
num2= int (input() )
a=num1
b=num2
while(num2!=0):
#swap using temp variable

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


11
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
Temp=num2
Num2=num1%num2
Num1=temp
gcd=num1
print(gcd)

INPUT:
15
75
OUTPUT:
15

CONCLUSION:
The Euclidean algorithm is a simple and efficient method for computing the GCD of
two numbers. It is widely used in various applications such as cryptography, number
theory, and computer science. By following the above procedure, anyone can
compute the GCD of two numbers with ease.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


12
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

EXPERIMENT- 2

AIM OF THE EXPERIMENT: Find the square root of a number (Newton's


method).
Requirement Specification:
Installation of Python in System
Pen and paper
Calculator (optional)
THEORY:

The objective of this laboratory experiment is to find the square root of a


given number using Newton's method.
PROCEDURE
 Write down the number whose square root is to be computed.
 Choose an initial guess for the square root and write it down.
 Apply Newton's method by performing the following steps:
a. Divide the number whose square root is to be computed by the
initial guess to obtain a quotient.
b. Take the average of the initial guess and the quotient obtained in
step a.
c. Use the average obtained in step b as the new guess.
d. Repeat steps a-c until the difference between the new guess and the
previous guess is smaller than a desired tolerance level.
 The last guess obtained in step 3 is an approximation of the square
root of the given number.
Program development:
def squareRoot(n, 1):

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


13
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
#Assuming the sqrt of n as n only
x=n
#To count the number of iterations
count = 0
while (1) :
count += 1
# Calculate more closed x
root = 0.5 (x + (n / x))
# Check for closeness
if (abs(root x) < 1):
break
#update root
X=root
return root
#driver code
If--------------name-------=”------main----“ :
n=327
1=0.00001
Print(squareroot(n,1))
Output:
18.08
CONCLUSION:
Newton's method is a simple and efficient method for finding the square root of a

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


14
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
number. It can be used to obtain a good approximation of the square root with only a
few iterations. By following the above procedure, anyone can find the square root of
a number using Newton's method.

EXPERIMENT -3
AIM OF THE EXPERIMENT: Exponentiation (power of a number).
Requirement Specification:
Installation of Python in System
Scientific calculator
Pen and paper
Stopwatch or timer
THEORY:
Exponentiation, or the process of raising a number to a power, is a fundamental
mathematical operation that is used extensively in various fields of science and
engineering. In this experiment, we will investigate the relationship between
exponentiation and the power of a number. Specifically, we will explore how the
power of a number changes as the exponent is varied.
PROCEDURE
 Choose a base number. For the purposes of this experiment, we will use 2 as the
base number.

 Choose a range of exponents to investigate. For example, you might choose


exponents ranging from 1 to 10.

 Calculate the power of the base number for each exponent using the formula:
 Power = base number ^ exponent

 Record the results in a table or chart.

 Graph the data on a coordinate plane, with the exponent on the x-axis and the
power on the y-axis.

 Analyze the data and observe any patterns or trends.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


15
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
Calculate the rate of change of the power as the exponent increases. This can be
done by finding the difference in power between consecutive exponents and
dividing by the difference in exponents. For example, if the power for exponent 3 is
8 and the power for exponent 4 is 16, the rate of change would be (16-8)/(4-3) = 8.

 Compare the rate of change to the value of the base number. For a base
number of 2, the rate of change should be equal to 2.

 Repeat the experiment with different base numbers and observe any
differences in the results.
Program development:
num=int (input(“Enter number:”))
exp-int (input("Enter exponential value: "))
result=1
for i in range(1,exp+1):
result=result*num
print("Result is:",result)
Output:-
Enter number:2
Enter exponential value:10
Result is :1024

CONCLUSION:

This experiment demonstrates the relationship between exponentiation and the


power of a number. It shows that as the exponent is increased, the power of a
number increases exponentially. This relationship is useful in many fields of science
and engineering, such as computing and physics. By understanding this relationship,
we can better understand and apply the principles of exponentiation in our work.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


16
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

EXPERIMENT- 4
AIM OF THE EXPERIMENT: Programs on Loops.
Requirement Specification:
Computer with a programming language installed (e.g. Python,)
Stopwatch or timer
Pen and paper
THEORY:
Loops are a fundamental programming construct that allows a program to repeat a set of
instructions multiple times. In this experiment, we will investigate the efficiency of different types
of loops in terms of their execution time and memory usage.
PROCEDURE
 Choose a programming language and create three different programs that accomplish the
same task using a while loop, a for loop, and a do-while loop. For example, the task could be
to sum the first 1000 natural numbers.

 Implement a timer in each program that records the execution time.

 Run each program and record the execution time in a table.

 Repeat step 3 multiple times and calculate the average execution time for each program.

 Analyze the data and observe any patterns or trends.

 Calculate the memory usage of each program using a memory profiler. Record the memory
usage in the table.

 Analyze the data and observe any patterns or trends.

 Compare the efficiency of each program in terms of execution time and memory usage.
Program development:

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


17
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
n=int(input(“Enter a number of elements in list”))
mylist=[]
printf(“Enter elements of the list”)
for---in range (n):
a=int(input())
mylist.append(a)
maximum=mylist[0]
for i in mylist:
if maximum<i:
maximum=i
printf(“Maximum of the list is :”maximum)

Output:-
Enter number of element in list 5
Enter elements of the list
12
32
45
67
87
Maximum of the list is :
87

CONCLUSION:
This experiment demonstrates the trade-offs between different types of
loops in terms of their efficiency. While a do-while loop may be more
efficient in terms of execution time, it may use more memory than a while
loop. Similarly, a for loop may be less efficient in terms of execution time
than a while loop, but it may use less memory. By understanding these
PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
18
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
trade-offs, programmers can choose the most appropriate loop for a given
task to optimize the performance of their programs.

EXPERIMENT -5

AIM OF THE EXPERIMENT.(a) Linear search and Binary search


Requirement Specification:
Computer with a programming language installed (e.g. Python)
Stopwatch or timer
Pen and paper
THEORY:
Searching for a specific item in a list or an array is a common operation in
computer programming. Linear search and binary search are two algorithms
used for searching. In this experiment, we will compare the efficiency of
linear search and binary search algorithms in terms of their execution time
for different sizes of arrays.
PROCEDURE
 Choose a programming language and create two different programs
that perform linear search and binary search algorithms. For example,
the task could be to search for a specific number in an array of 1000
elements.

 Implement a timer in each program that records the execution time.

 Create arrays of different sizes (e.g. 100, 1000, 10000, 100000) and
populate them with random numbers.

 Run each program on each array and record the execution time in a

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


19
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
table.

 Repeat step 4 multiple times and calculate the average execution time
for each program.

 Analyze the data and observe any patterns or trends.

 Graph the data on a coordinate plane, with the size of the array on the
x-axis and the execution time on the y-axis.

 Analyze the graph and observe any patterns or trends.

 Compare the efficiency of each algorithm in terms of execution time.

Program development:
def Linear search (array,n,k):
for j in range (0,n);
if (array[j]==k):
return j
return -1
array=[1,3,5,7,9,]
k=7
n=len(array)
result=Linear search (array,n,k)
if(result== -1):
print(“Element found at index: “,result)

Output:-
Element found at index: 3

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


20
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

b) To write a python program to perform Binary search

def binarysearch (arr,k,low,high):


while low <=high:
mid=low+(high-low)\2
if arr[mid]==k:
return mid
elif arr[mid]<k:
low=mid+1
else:
high=mid-1
return-1
arr=[1,3,5,7,9]
k=5
result=binarysearch (arr,k,o,len(arr)-1)
if result !=-1:
print(“Element is present at index”+str(result))
else
print(“Not found”)
Output:-
Not found

CONCLUSION:

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


21
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

This experiment demonstrates the efficiency differences between linear


search and binary search algorithms. While linear search may be
sufficient for small arrays, binary search is more efficient for larger
arrays. By understanding the performance characteristics of different
search algorithms, programmers can choose the most appropriate
algorithm for a given task to optimize the performance of their programs.

EXPERIMENT- 6
AIM OF THE EXPERIMENT: Selection sort, Insertion sort
Requirement Specification:
Python installed on a computer
Stopwatch or timer
Pen and paper
THEORY:
Sorting is a fundamental operation in computer science, and there are
many algorithms for sorting data. In this experiment, we will compare the
efficiency of two commonly used sorting algorithms in Python: selection
sort and insertion sort.
PROCEDURE
 Create a Python program that implements selection sort and another
program that implements insertion sort. The programs should sort a
list of integers in ascending order.

 Implement a timer in each program that records the execution time.

 Generate a list of integers of different sizes (e.g. 10, 100, 1000,


10000).

 Run each program on each list and record the execution time in a
table.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


22
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
 Repeat step 4 multiple times and calculate the average execution time
for each program.

 Analyze the data and observe any patterns or trends.

 Graph the data on a coordinate plane, with the size of the list on the x-
axis and the execution time on the y-axis.

 Analyze the graph and observe any patterns or trends.

 Compare the efficiency of each algorithm in terms of execution time.

Program development:
def selection sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[i] <alist[smallest]:
smallest =j
alist[i], alist[smallest]=alist[smallest), alist[i]
alist=input("Enter the list of numbers: ').split()alist [int(x) for x in alist]
selection_sort(alist)
print("Sorted list: ', end=")
print(alist)
Output:-
Enter the list of numbers:142368975
Sorted list:[1,2,3,4,5,6,7,8,9]
6.b.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


23
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
def insertion_sort(alist):
for i in range(1, len(alist));
temp = alist[i]
j=i-1
while (>= 0 and temp <alist[j]):
alist[i+1]=alist[j]
j=j-1
alist[j+1] = temp
alist = input("Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
insertion_sort(alist)
print('Sorted list: ', end=")
print(alist)
output:
Enter the list of numbers :1 4 5 3 6 7 8
Sorted list:[1,3,4,5,6,7,8]

CONCLUSION:
This experiment demonstrates the efficiency differences between selection
sort and insertion sort algorithms in Python. While insertion sort may be
faster for small lists, selection sort is more efficient for larger lists. By
understanding the performance characteristics of different sorting
algorithms, programmers can choose the most appropriate algorithm for a
given task to optimize the performance of their programs.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


24
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

EXPERIMENT- 7
AIM OF THE EXPERIMENT: Merge sort

Requirement Specification:
Python installed on a computer
Stopwatch or timer
Pen and paper
THEORY:
Sorting is a fundamental operation in computer science, and there are many
algorithms for sorting data. In this experiment, we will compare the
efficiency of merge sort algorithm in python.
PROCEDURE
 Create a Python program that implements Merge sort algorithm. The
program should sort a list of integers in ascending order.

 Implement a timer in the program that records the execution time.

 Generate a list of integers of different sizes (e.g. 10, 100, 1000,


10000).

 Run the program on each list and record the execution time in a table.

 Repeat step 4 multiple times and calculate the average execution time
for each program.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


25
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

 Analyze the data and observe any patterns or trends.

 Graph the data on a coordinate plane, with the size of the list on the x-
axis and the execution time on the y-axis.

 Analyze the graph and observe any patterns or trends.

 Compare the efficiency of the Merge sort algorithm in terms of


execution time.
Program development:
def merge_sort(alist, start, end):
Sorts the list from indexes start to end - 1 inclusive,"
if end-start > 1:
mid = (start + end)//2
merge_sort(alist, start, mid)
merge_sort(alist, mid, end)
merge_list(alist, start, mid, end)
def merge_list(alist, start, mid, end).
left=alist[start:mid]
right=alist[mid:end]
k = start
i=0
j=0
while (start + i < mid and mid+j < end):
if (left[i] <= right[j]):
alist[k] = left[i]
else:
PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
26
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
alist[k] = right[j]
j=j+1
k=k+1
if start+i<mid:
while k <end:
alist[k]-right[j]
alist=input("Enter the list of numbers: )spilt()
alist= [int(x) for: x in alist]
merge-sort(alist,o,len(a list))
print(sorted list:,end=”)
print(alist)
Output:-
Enter the list of numbers :1 3 2 4 5 6 7 9 8
Sorted list:[1,2,3,4,5,6,7,8,9]

CONCLUSION:
This experiment demonstrates the efficiency of Merge sort algorithm in
Python. Merge sort is one of the most efficient sorting algorithms in terms
of execution time and is particularly useful for large lists. By
understanding the performance characteristics of different sorting
algorithms, programmers can choose the most appropriate algorithm for a
given task to optimize the performance of their programs.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


27
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

EXPERIMENT -8
AIM OF THE EXPERIMENT:. First n prime numbers
Requirement Specification:
Python installed on a computer
Pen and paper
THEORY:
Prime numbers are an important mathematical concept and are often used
in computer science. In this experiment, we will write a Python program to
generate the first n prime numbers.
PROCEDURE
 Define a function called is_prime(num) that takes an integer num as
input and returns True if num is a prime number and False otherwise.

 Define a function called first_n_primes(n) that takes an integer n as


input and returns a list of the first n prime numbers. Use the
is_prime(num) function to generate the list.

 Test the program with small values of n (e.g. 10, 20, 50) and verify
that it generates the correct list of prime numbers.

 Analyze the performance of the program for larger values of n (e.g.


100, 1000, 10000). Record the execution time for each value of n.

 Graph the data on a coordinate plane, with the value of n on the x-axis
and the execution time on the y-axis.
PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
28
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

 Analyze the graph and observe any patterns or trends.

Program development:
#change the values of lower and upper for a different result
Lower=int(input(“Enter number starting:”))
Upper=int(input(“Enter number ending:”))
Print(“prime numbers between”,lower,”and”,upper,”are:”)
For num in range (lower,upper,+1):
#prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i)=0:
break
else:
print(num)

Output:-
Enter number starting :1
Enter number ending:9
Prime numbers between 1 and 9 are:
2
3
5
7
CONCLUSION:

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


29
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
This experiment demonstrates the efficiency of generating the first n prime
numbers in Python. The program we created is able to efficiently generate
the first n prime numbers for small values of n, but becomes less efficient
for larger values of n. By understanding the performance characteristics of
different algorithms, programmers can choose the most appropriate
algorithm for a given task to optimize the performance of their programs.

EXPERIMENT -9
AIM OF THE EXPERIMENT: Multiply two matrices using nested
loops
Requirement Specification:
Python installed on a computer
Pen and paper
THEORY:
Matrix multiplication is an important mathematical operation in computer science.
In this experiment, we will write a Python program to multiply two matrices using
nested loops.
PROCEDURE
 Define two matrices A and B of size m x n and n x p, respectively. Initialize the
matrices with random values.

 Define a function called matrix_multiplication(A, B) that takes the matrices A


and B as inputs and returns the product matrix C of size m x p.

 Implement the matrix multiplication algorithm using nested loops. Record the
execution time for different matrix sizes.

 Analyze the performance of the program for different matrix sizes. Record the
execution time for each matrix size.

 Graph the data on a coordinate plane, with the size of the matrices on the x-axis

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


30
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
and the execution time on the y-axis.

 Analyze the graph and observe any patterns or trends.

Program development:
#take a 3x3 matrix
A=[[12,7,3],
[4,5,6],
[7,8,9]]
#take a 3x4 matrix
B=[[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
result=[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterating by row of A
for i in range(len(A)):
# iterating by column by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B));
result[i][j]+=A[i][k]*B[k][j]
for r in result:
print(r)
output:
[114,160,60,27]

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


31
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
[74,97,73,14]
[119,157,112,23]
CONCLUSION:
This experiment demonstrates the efficiency of multiplying two matrices
using nested loops in Python. The program we created is able to
efficiently multiply small matrices using nested loops, but becomes less
efficient for larger matrices. By understanding the performance
characteristics of different algorithms, programmers can choose the most
appropriate algorithm for a given task to optimize the performance of
their programs.

EXPERIMENT- 10

AIM OF THE EXPERIMENT: program that take command line


arguments(word count)
Requirement Specification:
Python installed on a computer
A text file containing words
THEORY:
Word count is a common operation in text processing and analysis. In this
experiment, we will write a Python program that takes a text file as a
command line argument and counts the number of words in the file.
PROCEDURE
 Define a function called word_count(filename) that takes a file
name as input and returns the number of words in the file.

 Use the sys module to accept command line arguments in the


program. The program should accept the name of the text file to be
processed as a command line argument.

 Implement the word count algorithm. The program should open the
file and count the number of words in it. The word count should be

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


32
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
printed to the console.

 Test the program with different text files and verify that it correctly
counts the number of words in each file.

 Analyze the performance of the program for large text files. Record
the execution time for each file size.

 Graph the data on a coordinate plane, with the size of the text file on
the x-axis and the execution time on the y-axis.

 Analyze the graph and observe any patterns or trends.

Program development:
import sys
print (“This is the name of the script”, sys.argv[0])
printf(“Number of arguments :”,len(sys.argv))
printf(“The arguments are :”,str(sys.argv))
#Example output
#This is the name of the script:sysargv.py
#Number of arguments in :3
#The arguments are:[‘sysargv.py’,’arg1’,’arg2’]

output:
This is the name of the script: sysargv.py
Number of arguments: 3
The arguments are: ['sysargv.py', 'arg1', 'arg2']

CONCLUSION:

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


33
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
This experiment demonstrates the efficiency of counting the number of
words in a text file using command line arguments in Python. The
program we created is able to efficiently count the number of words in a
text file using command line arguments. By understanding the
performance characteristics of different algorithms, programmers can
choose the most appropriate algorithm for a given task to optimize the
performance of their programs.

EXPERIMENT- 11

AIM OF THE EXPERIMENT: Find the most frequent words in a


text read from a file
Requirement Specification:
Python installed on a computer
A text file containing words
THEORY:
Text analysis is a common task in natural language processing. In this
experiment, we will write a Python program that reads a text file and finds
the most frequent words in the file.
PROCEDURE
 Define a function called word_count(filename) that takes a file name
as input and returns a dictionary containing the count of each word in
the file.

 Implement the word count algorithm. The program should open the
file, read the text, split the text into words, and count the frequency of
each word.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


34
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

 Define a function called most_frequent_words(counts, n) that takes a


dictionary of word counts and an integer n as input and returns a list of
the n most frequent words in the dictionary.

 Implement the most frequent words algorithm. The program should


sort the word counts in descending order and return a list of the n most
frequent words.

 Test the program with different text files and verify that it correctly
identifies the most frequent words in each file.

 Analyze the performance of the program for large text files. Record
the execution time for each file size.

 Graph the data on a coordinate plane, with the size of the text file on
the x-axis and the execution time on the y-axis.

 Analyze the graph and observe any patterns or trends.

Program development:
Import sys
Count={}
With open (sys.argv[1],’r’)as f:
For line in f :
For word in line .spilt():
if word not in count:
count[word]=1
else:
count[word]+=1
print(word,count[word])
PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
35
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
file.close()
output:
hello 1
world 1
this 1
is 1
a2
test 2
file 2
CONCLUSION:
This experiment demonstrates the efficiency of identifying the most
frequent words in a text file using Python. The program we created is able
to efficiently identify the most frequent words in a text file using Python.
By understanding the performance characteristics of different algorithms,
programmers can choose the most appropriate algorithm for a given task
to optimize the performance of their programs. This program can be used
in a wide range of applications such as language modeling, sentiment
analysis, and more.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


36
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

EXPERIMENT- 12
AIM OF THE EXPERIMENT: Simulate elliptical orbits in pygame
Requirement Specification:
Installation of Python in System
Pygame module installed on the computer
THEORY:
Pygame is a popular Python module used for game development. In this
experiment, we will use Pygame to simulate elliptical orbits of planets
around a star. We will use Kepler's laws of planetary motion to model the
orbits and Pygame to visualize the motion of the planets.
PROCEDURE
 Define the basic elements of the simulation, including the star, the
planets, and their initial positions and velocities.

 Define a function to calculate the positions and velocities of the


planets at each time step based on Kepler's laws of planetary motion.

 Define a function to draw the planets and star on the screen using
Pygame.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


37
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
 Define the main game loop to run the simulation. The loop should
update the positions and velocities of the planets and draw them on the
screen.

 Test the simulation with different initial conditions and verify that the
orbits of the planets are elliptical.

 Analyze the performance of the simulation for different numbers of


planets and time steps. Record the execution time for each number of
planets and time step.

 Graph the data on a coordinate plane, with the number of planets or


time steps on the x-axis and the execution time on the y-axis.

 Analyze the graph and observe any patterns or trends.


Program development:
Import pygame
Import math
Import sys
Pygame.init()
#setting screen size
Screen=pygame.display.set-mode(600,300))
#setting caption
Pygame.display.set-caption(‘’Elliptical orbit”)
#increasing clock variable
Clock=pygame.time.clock()
While(True):
For event in pygame.event.get():
if event .typein pygame.event.get();

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


38
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
if event.type==pygame.QUIT:
sys.exit()
#setting x and y radius of ellipse
xRadius=250
yRadius=100
for degree in range (0,360,10):
x1=int(math.cos(degree*2*math.pi\360)*xRadius)+300
y1=int(math.sin(degree*2*math.pi\360)*yRadius)+150
screen.fill((0,0,0))
pygame.draw.circle(screen,(255,69,0),[300,150],40)
pygame.draw.ellipse(screen,(255,255,255,),[50,50,500,200],10
pygame.draw.circle(screen,(0,255,0),[x1,y1],20)
pygame.display.flip()
clock.tick((5)#screen refresh rate
Output:
A Pygame window opens with a white ellipse representing the orbit of the
planet around the star, which is represented by a red circle. The planet is
represented by a green circle moving along the ellipse, simulating its
elliptical orbit. The program updates the position of the planet every 10
degrees and sets the refresh rate of the screen to 5 frames per second.

CONCLUSION:

This experiment demonstrates the potential of using Pygame to


simulate the motion of planets around a star. By understanding the laws
of planetary motion and using Pygame to visualize the motion,
programmers can create realistic simulations of planetary orbits. This
program can be used in a wide range of applications such as astronomy,

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


39
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
physics, and game development. By optimizing the performance of the
simulation, programmers can create more complex simulations with
larger numbers of planets and longer time steps.

EXPERIMENT- 13
AIM OF THE EXPERIMENT: Simulate bouncing ball using pygame
Requirement Specification:
Python 3.x
Pygame library
THEORY:
Simulate a bouncing ball using Pygame.
PROCEDURE
 Import the Pygame library and initialize it.
 Set the screen size and caption.
 Set the initial position, size, and velocity of the ball.
 Create a game loop that updates the position of the ball and redraws it
on the screen.
 Add collision detection to make the ball bounce off the walls.
 Add gravity to make the ball fall and bounce realistically.
 Run the game loop until the program is stopped.
Program development:
import pygame

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


40
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING

pygame.init()

class Ball(pygame.sprite.Sprite):
def __init__(self, screen, background):
pygame.sprite.Sprite.__init__(self)
self.screen = screen
self.background = background
self.image = pygame.Surface((30, 30))
self.image.fill((255, 255, 255))
pygame.draw.circle(self.image, (0, 0, 255), (15, 15), 15)
self.rect = self.image.get_rect()
self.rect.center = (320, 240)
self.dx = 5
self.dy = 5

def update(self):
old_center = self.rect.center
self.rect.centerx += self.dx
self.rect.centery += self.dy
pygame.draw.line(self.background, (0, 0, 0), old_center,
self.rect.center)
self.check_bounds()

def check_bounds(self):
"""Bounce on encountering any screen boundary"""
if self.rect.right >= self.screen.get_width() or self.rect.left <= 0:
self.dx *= -1
if self.rect.bottom >= self.screen.get_height() or self.rect.top <= 0:
self.dy *= -1

def main():
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Boundary-checking: bounce")
background = pygame.Surface(screen.get_size())

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


41
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
background.fill((255, 255, 255))
screen.blit(background, (0, 0))
ball = Ball(screen, background)
all_sprites = pygame.sprite.Group(ball)
clock = pygame.time.Clock()
keep_going = True
while keep_going:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
keep_going = False
all_sprites.clear(screen, background)
all_sprites.update()
all_sprites.draw(screen)
pygame.display.flip()

if __name__ == "__main__":
main()
output:
A Pygame window is opened with the title "Boundary-checking: bounce."
The window is 640 pixels wide by 480 pixels tall. A white background is
drawn on the window, and a blue ball is drawn in the center of the
window. The ball moves across the screen at a constant speed of 5 pixels
per frame, bouncing off the top, bottom, left, and right boundaries of the
window when it reaches them.
CONCLUSION:

This experiment demonstrates the potential of using Pygame to


simulate the motion of planets around a star. By understanding the laws
of planetary motion and using Pygame to visualize the motion,
programmers can create realistic simulations of planetary orbits. This
program can be used in a wide range of applications such as astronomy,
physics, and game development. By optimizing the performance of the

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


42
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
simulation, programmers can create more complex simulations with
larger numbers of planets and longer time steps.

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY


43

You might also like