Sei sulla pagina 1di 88

p

DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY


Approved by AICTE, New Delhi &Affiliated to Anna University, Chennai.
Accredited by NAAC
Salem Airport (Opp.), Salem 636 309
Ph. (04290) 233333, www.dgct.ac.in

BONAFIDE CERTIFICATE

Name :

Degree :

Branch :

Semester : Year: Section:

Reg. No. :

Certified that this is the bonafide record of the work done by the above student in
Laboratory during
the academic year

LAB-IN-CHARGE HEAD OF THE DEPARTMENT

Submitted for University Practical Examination held on

INTERNAL EXAMINER EXTERNAL EXAMINER


LAB MANNERS

Students must be present in proper dress code and wear the ID card.
Students should enter the log-in and log-out time in the log register without fail.
Students are not allowed to download pictures, music, videos or files without
the permission of respective lab in-charge.
Students should wear their own lab coats and bring observation note books to
the laboratory classes regularly.
Record of experiments done in a particular class should be submitted in the
next lab class.
Students who do not submit the record note book in time will not be allowed
to do the next experiment and will not be given attendance for that laboratory
class.
Students will not be allowed to leave the laboratory until they complete the
experiment.
Students are advised to switch-off the Monitors and CPU when they leave the
lab.
Students are advised to arrange the chairs properly when they leave the lab.
College
Vision
To improve the quality of human life through multi-disciplinary programs in
Engineering, architecture and management that are internationally recognized and would
facilitate research work to incorporate social economical and environmental development.
Mission
To create a vibrant atmosphere that creates competent engineers, innovators, scientists,
entrepreneurs, academicians and thinkers of tomorrow.
To establish centers of excellence that provides sustainable solutions to industry and
society.
To enhance capability through various values added programs so as to meet the
challenges of dynamically changing global needs.
Department
Vision
To cultivate creative, globally competent, employable and disciplined computing
professionals with the spirit of benchmarking educational system that promotes academic
excellence, scientific pursuits, entrepreneurship and professionalism.
Mission
To develop the creators of tomorrows technology to meet the social needs of our nation.

To promote and encourage the strength of research in Engineering, Science and Technology.

To channel the gap between Academia, Industry and Society.

Program Educational Objectives(PEOs)


PEO1 The Graduates of the program would constantly learn and update the knowledge in the
emerging fields of technology.
The Graduates will be able to analyze, design, implement, test and administer computer-
PEO2
based solutions to the real world problems aligned with the Industry expectations.

The Graduates inculcate soft skills such as communication, team work, leadership
PEO3 qualities, professional and ethical values and an ability to apply the acquired skills to
address the societal issues.
The Graduates will be able to work with an environment conducive for life-long learning
PEO4 needed for a successful professional career.
Program Outcomes(POs)

To apply knowledge of mathematics, science, engineering fundamentals and


computer science theory to solve the complex problems in Computer Science and
PO1
Engineering.
To analyze problems, identify and define the solutions using basic principles of
PO2
mathematics, science, technology and computer engineering.
To design, implement, and evaluate computer based systems, processes,
PO3 components, or software to meet the realistic constraints for the public health and
safety, and the cultural, societal and environmental considerations.
To design and conduct experiments, perform analysis & interpretation and provide
PO4
valid conclusions with the use of research-based knowledge and research
methodologies related to Computer Science and Engineering.
To propose innovative original ideas and solutions, culminating into modern
PO5
engineering products for a large section of the society with longevity.
To apply the understanding of legal, health, security, cultural & social issues, and
PO6 thereby ones responsibility in their application in Professional Engineering
practices.
To understand the impact of the professional engineering solutions in societal and
PO7
environmental issues, and the need for sustainable development.
To demonstrate integrity, ethical behavior and commitment to code of conduct of
PO8 professional practices and standards to adapt to the technological developments of
revolutionary world.
To function effectively as an individual, and as a member or leader in diverse teams,
PO9
and in multifaceted environments.
To communicate effectively to end users, with effective presentations and write
PO10 comprehends technical reports and publications representing efficient engineering
solutions.
To understand the engineering and management principles and their applications
PO11
to manage projects to suite the current needs of multidisciplinary industries.
To learn and invent new technologies, and use them effectively towards continuous
PO12
professional development throughout the human life.
Program Specific Outcomes(PSOs)

Design, develop, test and maintain strategies in software project development to


PSO1
deliver a quality product for business success.

Design, develop, test and maintain software in area of algorithms, system software,
web design, multimedia, big data analytics and networking for efficient design for
PSO2
computer based system.
Course Outcomes(COs)

C01 Write, test, and debug simple Python programs.

C02 Implement Python programs with conditionals and loops.

C03 Develop Python programs step-wise by defining functions and calling them.

C04 Use Python lists, tuples, dictionaries for representing compound data.

C05 Read and write data to/from files in Python.

Mapping
Course
Outcome PO PO PO PO PO PO PO PO PO PO1 PO1
PO12 PSO1 PSO2
s 1 2 3 4 5 6 7 8 9 0 1
(COs)

C01 3 3 2 2 1 1 2 3 3

C02 3 3 1 1 1 2 2

C03 3 3 1 2 2 1 3 2

C04 3 3 1 1 1 1 2

C05 2 2 1 1 1 2 1

Mapping Grade: 1-Slightly, 2-Moderately, 3-Substantially


CONTENTS

Ex. Page Date of Marks Staff


Date Name of the Experiment Remarks
No. No. completion Awarded Signature

Compute the GCD of two


1
numbers.
1
Find the square root of a number
2
(Newtons method)
6
Exponentiation (power of a
3 12
number)
Find the maximum of a list of
4 18
numbers

5a Linear search 24

5b Binary search 29

6a Selection sort 35

6b Insertion sort 37

7 Merge sort 42

8 First n prime numbers 48

9 Multiply matrices 54
Programs that take command
10 59
line arguments (word count)
Find the most frequent words in
11
a text read from a file
64
Simulate elliptical orbits in
12
Pygame
70
Simulate bouncing ball using
13
Pygame
77

RECORD COMPLETION DATE: AVERAGE MARKS SCORED:

LAB-IN-CHARGE:
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:1 Date
of Completion Additional Credits

GCD OF TWO NUMBERS


OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a basic Python coding.

PRE-REQUISITE

Basics of Python Language.

AIM:

To compute the Greatest Common Divisor of two numbers using python programming.

ALGORITHM:

Step 1: Start the program.


Step 2: Read the data into variable a, b.
Step 3: Assign the highest value to a and smallest to b.
Step 4: If b is equal to zero then a value is the GCD.otherwise divide a until b equal to zero
Step 5: Print the resulted value as GCD.
Step 6: Stop the program.

PROGRAM:
def gcd(a,b) :
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input(Enter first number:))
b=int(input(Enter second number:))
GCD=gcd(a,b)
Print(GCD is: )
Print(GCD)

1
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

OUTPUT:

Enter first number: 3


Enter Second number: 1
GCD is:
1

CONCLUSION:

Thus the python program to compute the Greatest Common Divisor of two numbers was
executed and the output is obtained.

2
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES:

1. Write a python program to find HCF without using GCD function.


2. Write a python program to find factors of number.
3. Write a python program to find the largest of three numbers.
4. Write a python program to find the given year is leap year or not.
5. Write a python program to find Least Common Multiple of two positive integers.
6. Write a python program to display the current date and time.

OBJECTIVE QUESTIONS:

1. Python is an example of
a) High level language b) Middle level language c) Low level language d) None
2. Python and Rexx is a type of
a) Logic based programming language b) Functional programming language
c) Interpreted programming language d) Object Oriented programming language
3. Which among the following is compiled programming language?
a) Q b) Python c) Clean d) Java
4. Python was developed by
a) Guido Van Rossum b) JohanDahl c) John George Kemeny d)Niklaus Wirth
5. Python is
a) Interactive b) Interpreted c) Only A d) Both A and B

VIVA QUESTIONS:

1. Define computer programming


2. Define Algorithm and Flowchat
3. Mention the characteristics of algorithm
4. What is the need for flowchart?
5. Compare Interpreted and Compiled Programming Language?
6. Why do people use python?
7. Difference between Interpreter and Compiler
8. Mention some built in functions available in python programming language
9. Define top tested loop
10. Define bottom tested loop

3
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

4
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

5
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:2 Date
of Completion Additional Credits

SQUARE ROOT OF A NUMBER (NEWTONS METHOD)

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a basic python coding.

PRE-REQUISITE

Basics of Python Language.

AIM:

To find the square root of a number (Newtons method) using python programming

ALGORITHM:

Step 1: Start the program.


Step 2: Get input from user.
Step 3: Caluculate square root of number
Num_sqrt**0.5.
Step 4: Disply Number.
Step 5: Stop the program

PROGRAM:

#Note: Change this value for a different result


Num=8
#uncomment to the input from the user
#num=float (input (Enter a number :))
Num_sqrt=Num**0.5
Print (the square root of %0.3f is %0.3f %( Num, Num_sqrt))

6
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

OUTPUT:

The square root of 8.000 is 2.828

CONCLUSION:

Thus the pyhton program to find square root of a number using newtons method is
executed and the output is obtained.

7
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES

1. Write a python program to compute cube root of a number.


2. Write a python program that will accept the base and height of a triangle and compute
the area.
3. Write a python program which accepts the radius the circle from the user and compute
the area.
4. Write a python program to swap two variables
5. Write a python program to convert kilometers to miles
6. Write a python program to check prime numbers
7. Write a python program tocheck Armstrong number
8. Write a python program to check whether a string is palindrome or not.
9. Write a python program to sort three integers without using conditional statements and
loops.
10. Write a python program to display the multiplication table.

OBJECTIVE QUESTIONS:

1. Python coding is saved with the extension of


a) .p b) .py c) .python d) .pyc
2. IDE stands for
a).Integrated Development Enviroinment b)Interactive Development Enviroinment.
c) Interepted Development Enviroinment d) None of the above
3. Python programs get structured through
a) Class b) Blocks c) Functions d) Intendation
4. What is the output of print str if str = 'Hello World!'?
a) Hello World! b) Str c) Error d) None
5. Which of the following function returns a random float r, such that 0 is less than or equal to r
and r is less than 1?
a)choice(seq) b) randrange ([start,] stop [,step]) c) random() d) seed([x])

8
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VIVA QUESTIONS:

1. List some types of python compilers


2. What are the three distinct numeric types of python?
3. Mention some mathematical functions available in python
4. Define operator and operand
5. Define string
6. Mention some string special operators available in python
7. What are the supported data types in python?
8. How will you convert string to float in python?
9. How will you convert string to all uppercase?
10. Compare decision making and Looping.

9
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

10
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

11
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:3 Date
of Completion Additional Credits

EXPONENTIATION (POWER OF A NUMBER)

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a basic python coding.

PRE-REQUISITE

Basics of Python Language.

AIM:

To find the exponent of a given number using python programming

ALGORITHM:

Step 1: Start the program.


Step 2: Enter the n value and m value
Step 3: Assign the value in add, multiply and exponent
Step 4:.Find the exponent value of given n and m value
Step 5: Stop the program.

PROGRAM:

n = int(input("n value: "))


m = int(input("m value: "))
def add(a, b):
num = a
for i in range(b):
num += 1
return num

12
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

def multiply(a, b):


num = 0
for i in range(b):
num = add(num, a)
return num

def exponent(a, b):


num = 1
for i in range(b):
num = multiply(num, a)
return num

print(exponent(n, m))

OUTPUT:
n value: 2
m value: 5
32

CONCLUSION:

Thus the python program to find Exponent of a given number using is executed and the
output is obtained.

13
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES

1. Write a python program to find Logarithm of given number.


2. Write a python program to find factorial of given number.
3. Write a python program to find cosine value of given X.
4. Write a python program to convert Celsius into Fahrenheit
5. Write a python program to generate the Fibonacci series
6. Write a python program to find the roots of the Quadratic equation

OBJECTIVE QUESTIONS:

1. Which is the correct operator for power(x^y)?

a) x^y b) x**y c) x^^y d) None

2. Which one of these is floor division?

a) / b) // c) % d) None

3. What is answer of this expression, 22 % 3 is

a) 7 b) 1 c) 0 d) 5

4. Mathematical operations can be performed on a string. State whether true or false

a) True b) False c) Error d) None

5. Operators with the same precedence are evaluated in which manner?

a) Left to Right b) Right to Left c) cant say d) None

14
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VIVA QUESTIONS:

1. List some of python Operators


2. Explain Conditional Operators
3. Mention some mathematical functions available in python
4. Define Operator Precedence
5. Explain the uses of solving mathematical functions in programming
6. Mention some of the advantages of using Operators
7. Mention the size of different data types?
8. Define Comparison Operators

15
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

16
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

17
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:4 Date
of Completion Additional Credits

MAXIMUM LIST OF NUMBERS

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a basic Python coding.

PRE-REQUISITE

Basics of Python Language.

AIM:

To compute the Maximum number in the List using python programming.

ALGORITHM:

Step 1: Start the program.


Step 2: Read the data into variable num in corresponding List
Step 3: Assign the values in the List
Step 4: Use append method and max () function in the list for the given values
Step 5: Print the Maximum element in the List
Step 6: Stop the program.

18
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PROGRAM:

Lst=[]
num=int(input(How many numbers:))
For n in range(num):
Numbers=int(input(Enter number ))
Lst.append(Numbers)
Print(Maximum element in the list is:, max(Lst))

OUTPUT:

How many numbers: 5


Enter number: 10
Enter number: 25
Enter number: 3
Enter number: 7
Enter number: 15

Maximum element in the list is : 25

CONCLUSION:

Thus the python program to compute the Maximum numbers in the List was executed
and the output is obtained.

19
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES:

1. Write a python program using Loop in the List


2. Write a python program to find duplicate element in the List
3. Write a python program to find intersection of two list elements
4. Write a python program for sorting the list
5. Write a python program to find selecting particular element in the List.
6. Write a python program to find difference between the two lists.

OBJECTIVE QUESTIONS:

1. What is the Output of the following code : print(type([1,2]))?

a) <class tuple> b) <class int> c) <class set> d) <class list>

2. What is the Output of the following code :

a=[1,2,3,None,(),[],]
print(len(a))

a) Syntax error b) 4 c) 5 d) 6

3. Which is the Output of following code:

Names=[ Amir , Barry , Chales ,Dao]


print(Names[-1][-1])
a) A b) r c) Amir d) o

4. Which of the following data structures can be used with the "in" operator to check if an item is
in the data structure?

a) List b) Set c) Dictionary d)All the above

5. Which method is used in the List to find number of times a given item is present in it.

a) count b) append c)extend d) None

20
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VIVA QUESTIONS:

1. Define List
2. Define Sort
3. Mention the use of Slip method in the List
4. What is the need for count method?
5. Compare List, tuple and Dictionary and mention its uses?
6. Why do we use Loop in the List?
7. Difference between Append and Extend
8. Mention some built in functions available in the List
9. Define the method for finding Maximum and Minimum element in the List
10. Define Indexing,Slicing and Matrices in the List

21
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

22
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

23
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:5(a) Date
of Completion Additional Credits

LINEAR SEARCH

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a Python coding to implement the linear search.

PRE-REQUISITE

Basics of Python Language.

AIM:

To implement the linear search program using python.

ALGORITHM:

Step 1: Start the program.


Step 2: Intilize elements.
Step 3: Get the elements.
Step 4: Enter the elements to be searched from the list.
Step 5: Compare each elements of the list with the element to be searched.
Step 6: Display the position of the element if comparison succeeds. Otherwise move to
the next element until condition succeeds.
Step 7: Stop the program.

PROGRAM:

items = [5, 7, 10, 12, 15]


print("list of items is", items)
x = int(input("enter item to search:"))
i = flag = 0
while i < len(items):

24
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

if items[i] == x:
flag = 1
break
i=i+1
if flag == 1:
print("item found at position:", i + 1)
else:
print("item not found")

OUTPUT:

list of items is, [5, 7, 10, 12, 15]


enter item to search
5
item found at position 1

CONCLUSION:

Thus the python program for the implementation of linear search was executed and
the output was obtained.

25
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES:

1. Write a python program to search the element 12 using linear search


76 45 98 32 12 65 27
2. Write a python program to Read an Array and Search for an Element using linear search.
3. Write a python program using Recursion to Search an Element in Array using linear
search.
4. Develop a python program for implementing linear search on a sorted array of N
numbers.

OBJECTIVE QUESTIONS:

1. A technique for direct search is


a) Binary search b) Linear search c) Tree search d) Hashing
2. A characteristic of the data that linear search ignores is
a) Order of the elements of the list b) Length of the list
c) Maximum value in list d) Type of elements of the list
3. In linear search, average number of comparison required for searching an element in a list
if n numbers is
a) Log2n b) n / 2 c) n d) n-1
4. The Worst case occur in linear search algorithm when
a) Item is somewhere in the middle of the array b) Item is not in the array at all
c) Item is the last element in the array
d) Item is the last element in the array or is not there at all
5. The Average case occur in linear search algorithm
a) Item is somewhere in the middle of the array b) Item is not in the array at all
c) Item is the last element in the array
d) Item is the last element in the array or is not there at all

VIVA QUESTIONS:

1. Define searching and mention its types.


2. What is linear searching?
3. Write the routine for linear search.
4. Search the given element using linear search
76 45 98 32 12 65 27
The key element is 12
5. Write the advantage and disadvantage of linear search.
6. What are the operations of linear search?
7. How to search an element in linear search?
8. In what order linear searching is performed?

26
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

27
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

28
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:5(b) Date
of Completion Additional Credits

BINARY SEARCH

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a Python coding to implement the binary search.

PRE-REQUISITE

Basics of Python Language.

AIM:

To implement the binary search program using python.

ALGORITHM:

Step 1: Start the program.


Step 2: Declare an array and variables as first, last and middle.
Step 3: Get the elements for the array.
Step 4: Enter the element to be searched from the array.
Step 5: Find the middle element in an array.
Step 6: Compare the element to be searched with the middle element.
Step 7: If the element is greater than the middle element ,perform the search in
right half group, else perform search in left half group.
Step 8: Display the position of the element if comparison succeeds.
Step 9: If condition fails move to the next element until it succeeds.
Step 10: Stop the program.

PROGRAM:

def binary_sort(sortedlist,n,x):
start = 0
end = n - 1
while(start <= end):
mid = (start + end)/2

29
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

if (x == sortedlist[mid]):
return mid
elif(x < sortedlist[mid]):
end = mid - 1
else:
start = mid + 1
return -1

n = input("Enter the size of the list: ")

sortedlist = []

for i in range(n):
sortedlist.append(input("Enter %dth element: "%i))

x = input("Enter the number to search: ")


position = binary_sort(sortedlist, n, x)

if(position != -1):
print("Entered number %d is present at position: %d"%(x,position))
else:
print("Entered number %d is not present in the list"%x)

OUTPUT:

Enter the size of the list: 3


Enter 0th element: 1
Enter 1th element: 2
Enter 2th element: 3
Enter the number to search: 3

Entered number 3 is present at position: 2

CONCLUSION:

Thus the pyhton program for the implementation of binary search was executed and
output was obtained.

30
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES

1. Write a python program to Read an Array and Search for an Element using binary search.
2. Write a python program using Recursion to Search an Element in Array using binary
search.
3. Develop a python program for implementing binary search on a sorted array of N
numbers.
4. Write a pyhton program to search the element 32 using binary search
76 45 98 32 12 65 27

OBJECTIVE QUESTIONS:

1. A technique for direct search is


a) Binary search b) Linear search c) Tree search d) Hashing
2. In order to get the contents of a Binary search tree in ascending order, one has to traverse it in
a) pre order b) post order c) in order d) not possible
3. A characteristic of the data that binary search uses is
a) Order of the elements of the list. b) Length of the list.
c) Maximum value in list. d) Type of elements of the list.
4. In binary search, average number of comparison required for searching an element in a list if
n numbers is
a) log2 n b) n / 2 c) n d) n-1
5. Binary search algorithm cannot be applied to
a) sorted linked list b) sorted binary trees
c) sorted linear array d) pointer array
6. Which of the following is not a limitation of binary search algorithm?
a) Must use a sorted array
b) Requirement of sorted array is expensive when a lot of insertion and deletions are
needed
c) There must be a mechanism to access middle element directly
d) Binary search algorithm is not efficient when the data elements are more than 1000.

31
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VIVA QUESTIONS:

1. What is binary?
2. What is binary search?
3. What are the techniques to implement binary search?
4. What are the operations in binary search?
5. What is binary searching?
6. Write the routine for binary search.
7. Search the given element using binary search
14 34 56 78 90 123
The key element is 90
8. Difference between linear search and binary search.
9. Write the advantage and disadvantage of binary search.
10. In what order binary search is performed.

32
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

33
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

34
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:6(a) Date
of Completion Additional Credits

SELECTION SORT

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a Python coding to implement selection sorting.

PRE-REQUISITE

Basics of Python Language.

AIM:

To sort the list of elements using selection sort.

ALGORITHM:

Step 1: Start the program.


Step 2: Read upper limit n.
Step 3: Read n elements to the list.
Step 4: Call Function Ssort(list).
Step 5: Print Sorted List.
Step 6: Stop the program.

PROGRAM:

def ssort(aList):
for I in range( len( len(aList)):
least = i
for k in range(i+1,len(aList)):
if aList[k]<aList[least]:
least=k
swap(alilst,least ,i)
def swap(A,x,y):

35
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

tmp=A[x]
A[x]=A[y]
A[y]=tmp
a=[]
n=int(input(Enter Upper Limit:))
for I in range(n):
a.append(int(input()))
ssort(a)
print(After Sorting:.a)

OUTPUT:

Enter Upper Limit: 5


7 4 9 1 6
After Sorting: [1, 4, 6, 7, 9]

CONCLUSION:

Thus the python program for the implementation of selection sort was executed and
the output was obtained.

36
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:6(b) Date
of Completion Additional Credits

INSERTION SORT

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a Python coding to implement insertion sorting.

PRE-REQUISITE

Basics of Python Language.

AIM:

To sortlist of elements using Insertion sort.

ALGORITHM:

Step 1: Start the program.


Step 2: Read upper limit n.
Step 3: Read n elements to the list.
Step 4: Call Function iSort(list).
Step 5: Print Sorted List.
Step 6: Stop the program.

Step 1: Funtion start


Step 2: FOR i=1 to len(a)
Step 2.1: currentvalue=a[i]
Step 2.2: pos=i
Step 2.3: WHILE pos>0 and a[pos-1]>currentvalue
Step 2.3.1: a[pos]=a[pos-1]

37
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Step 2.3.2: pos=pos-1


Step 2.3.3: a[pos]=currentvalue
Step 3: Return
PROGRAM:

def isort(a):
for index in range(1,len(a)):
currentvalue=a[index]
position=index
while position>0 and a[position-1]>currentvalue:
a[position]=a[position-1]
position=position-1
a[position]=currentvalue
a=[]
n=int(input(Enter Upper Limit:))
for i in range(n):
a.append(int(input()))
isort(a)
print(List afterinsert:,a)

OUTPUT:

EnterUpperLimit: 5
3
List after insert: [3]
2
List after insert: [2, 3]
5
List after insert: [2, 3, 5]
1
List after insert: [1, 2, 3, 5]
4
List after insert: [1, 2, 3, 4, 5]

CONCLUSION:

Thus the pyhton program for the implementation of insertion sort was executed and
output was obtained.

38
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES

1. Write a python program to sorting an array of strings using insertion sort.


2. Write a python program to print the sorting numbers without getting input from the user
using insertion sort.
3. Develop a python program to implementing selection sort in array of N numbers.

OBJECTIVE QUESTIONS:

1. If the number of records to be sortedin small,then _________________ sorting can be efficient.


a) Merge b) Heap c) Selection d) Insertion
2. The complexityof the sorting algorithm measures the __________________ as a function of the
number n of items to be sorter.
a) Average time b) Running time c) Average Case complexity d) Case complexity
3. Sorting algorithm can be characterized as ________________
a) Simple algorithm which requires the order of n2 comparision to sort n items
b) Sophesticated algorithms which require the o(nlog2n) comparision to sort n items
c) Both of the above d) None of the above
4. __________________ is putting an element in the appropriate place in a sorted list yields a large
sorted order list.
a) Insertion b) Selection c) Extracion d) Distribution
5. _________________ sorting algorithm is frequently used when n in small where n is total number
of elements.
a) Heap b) Insertion c) Bubble d) Selection
6. Which of the following sorting algorithm is of priority queue sorting type?
a) Merge b) Insertion c) Bubble d) Selection

VIVA QUESTIONS:

1. What is Selection sort?


2. What is Insertion sort?
3. What are the advantages of insertion sort?
4. List out the applications of selection sort ?
5. What are the methods available in sorting sequential files?
6. Why we need sorting?
7. List out thetypes of sorting.
8. Difference between selecton and insertion sort.

39
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

40
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

41
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:7 Date
of Completion Additional Credits

MERGE SORT

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a Python coding to implement merge sorting.

PRE-REQUISITE

Basics of Python Language.

AIM:

To sort the list of elements using merge sort.

ALGORITHM:

Step 1: Start the program.


Step 2: Divide Step: If a given array A has 0 or 1 element, simply return; it is already sorted.
Otherwise split A[p r] into two sub arrays A[p q] and A[q+1 r], each containing
about half of the elements of A[p q]. that is, q is the halfway point of A[p r].
Step 3: Conquer Step: Conquer by recursively sorting the two sub arrays A[p q] and A[q+1
r].
Step 4: Combine Step: Combine the elements back in A[p r] bymerging two sorted sub arrays
A[p q] and A[q+1 r] into a sorted sequence. To accomplish this step, we will define a
procedure MERGE(A,r,q,r).
Note that the recursion bottoms out when the sub array has justone element, so that it is
trivially sorted.
Step 5: Stop the program.

42
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PROGRAM:

def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]

mergeSort(lefthalf)
mergeSort(righthalf)

i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1

while i < len(lefthalf):


alist[k]=lefthalf[i]
i=i+1
k=k+1

while j < len(righthalf):


alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)

alist = [13,2,17,76,82,12,7]
mergeSort(alist)
print(alist)

43
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

OUTPUT:

Splitting [13, 2, 17, 76, 82, 12, 7]


Splitting [13, 2, 17]
Splitting [13]
Merging [13]
Splitting [2, 17]
Splitting [2]
Merging [2]
Splitting [17]
Merging [17]
Merging [2, 17]
Merging [2, 13, 17]
Splitting [76, 82, 12, 7]
Splitting [76, 82]
Splitting [76]
Merging [76]
Splitting [82]
Merging [82]
Merging [76, 82]
Splitting [12, 7]
Splitting [12]
Merging [12]
Splitting [7]
Merging [7]
Merging [7, 12]
Merging [7, 12, 76, 82]
Merging [2, 7, 12, 13, 17, 76, 82]
[2, 7, 12, 13, 17, 76, 82]

CONCLUSION:

Thus the python program for the implementation of merge sort was executed and
the output was obtained.

44
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES

1. Write a python program to implement dividing and conquer method.


2. Write a python program to print the sorting numbers without getting input from the user
using merge sort.
3. Develop a python program to implementing merge sort in array of N numbers.

OBJECTIVE QUESTIONS:

1. Which of the following sorting algorithm is divideand conquer type?


a) Merge b) Heap c) Selection d) Insertion
2. Partition and exchange sort is
a) Quick sort b) Tree Sort c) Merge Sort d) Bubble Sort
3. Total number ofpasses in merge sort of n numbers is ________________
a) n b)n-1 c)log(n) d)nlogn
4. What is the best case complexity of the merge sort algorithm?
a)O(n) b)O(n*n) c)O(nlogn) d)O(logn)
5. Which of the following sorting algorithms has the lowest worst case complexity?
a) Merge b) Insertion c) Bubble d) Selection

VIVA QUESTIONS:

1. What is mergw sort?


2. Why quick sort is better than merge sort?
3. What are the advantages of merge sort?
4. List out the applications of merge sort?
5. What is divide and conquer method?

45
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

46
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

47
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:8 Date
of Completion Additional Credits

FIRST N PRIME NUMBERS

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a Python coding to implement primenumbers.

PRE-REQUISITE

Basics of Python Language.

AIM:

To write a program to find and print the prime numbers upto n.

ALGORITHM:

Step 1: Start the program.


Step 2: Read n numbers.
Step 3: FOR num - 1 to n
Step 4: FOR I 2 to num
Step 4.1: IF num % i==0
Step 4.2: j num/i
Step 4.3: Print num is not a prime number
Step 4.4: Break
Step 5: ELSE Print num is a prime number
Step 6: END FOR.
Step 7: Stop the Program.

48
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PROGRAM:

n=int(input(Enter the Upper Limit:))


for num in range(1,n):
for i in range(2,num):
ff num%i == 0:
j=num/i
print(%d equals %d * %d%(num,I,j))
break
else:
print (num, is a prime number)

OUTPUT:

Enter Upper Limit: 5


1 is a prime number
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number

CONCLUSION:

Thus the python program for the implementation of prime number was executed and
the output was obtained.

49
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES

1. Write a python program to print whether a given number is prime or not.


2. Write a python program to find the sum of prime numbers.
3. Write a python program to print only prime numbers of given N numbers
4. Write a program to find the factorial of a given number.
5. Write a program to generate Fibonacci series.

OBJECTIVE QUESTIONS:

1. Out of the following which of these integers is not prime?


a) 21 b) 35 c) 71 d) 101
2. Which positive integer less than 21 are relatively prime to 21?
a) 18 b) 19 c) 21 d) 24
3. Numbers that have only two factors and are different from each other are called____________
a) odd numbers b)prime numbers c)composite numbers
d)even numbers
4. Prime factors of 70 are,
a) 2*3*5*7 b)2*2*5 c)2*3*5 d)2*5*7

VIVA QUESTIONS:

1. What is prime number?


2. List some of the built-in functions used in python?
3. What is logic behind prime numbers?
4. What is the use of range() function in the program?

50
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

51
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

52
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

53
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:9 Date
of Completion Additional Credits

MULTIPLY MATRICES

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a Python coding to multiply matrices.

PRE-REQUISITE

Basics of Python Language.

AIM:

To implement matrix multiplication using python.

ALGORITHM:

Step 1: Start the program.


Step 2: Read matrix A and matrix B.
Step 3: To multiply matrices sufficient and necessary condition is number of columns in matrix
A = number of rows in matrix B.
Step 4: Loop for each row in matrix A and loop for each columns in matrix B.Intialize output
matrix C to 0. This loop will run for each rows of matrix A.
Step 5: Loop for each columns in matrix A.
Step 6: Multiply A[i,k] to B[k,j] and add this value to C[I,j]
Step 7: Print matrix C.
Step 8: Stop the program

54
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PROGRAM

a=[[1,2],
[3,4]]
b=[[1,2],
[3,4]]
c=[[0,0],
[0,0]]
for i in range(len(a)):
for j in range(len(b[0])):
for k in range(len(b)):
c[i][j] += a[i][k] *b[k][j]
print("Resultant Matrix")
for r in c:
print(r)

OUTPUT:

Resultant Matrix

[7, 10]

[15, 22]

CONCLUSION:

Thus the python program for the implementation of matrix multiplication was executed
and the output was obtained.

55
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES:

1. Write a python program to add two matrices.


2. Wirte a python program to print the ascending and descending order of the given array.
3. Wirte a python program to find the largest and smallest of the given array.
4. Write a python program to transpose the given matrix.

OBJECTIVE QUESTIONS:

1. Which of the following loops will execute the body of loop even when condition controlling
the loop is initially false?
a) do-while b) while c) for d) None of the mentioned
2. Which of these statement is incorrect?
a) switch statement is more efficient than a set of nested ifs.
b) two case constants in the same switch can have identical values.
c) switch statement can only test for equality, whereas if statement can evaluate
any type of boolean expression.
d) it is possible to create a nested switch statements.
3. Applications of multidimensional array are?
a) Matrix-Multiplication
b) Minimum Spanning Tree
c) Finding connectivity between nodes
d) All of the mentioned

VIVA QUESTIONS:

1. What is the difference between 'for' and 'while' loops?


2. What are arrays?
3. Does compiler perform bound checking on arrays?
4. What happens if the size of array exceeds?
5. How are array elements can be passed to function?
6. How is individual element in an array can be accessed?
7. What is important is initilizating 2-d arrays?

56
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

57
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

58
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:10 Date
of Completion Additional Credits

PROGRAMS THAT TAKE COMMAND LINE ARGUMENTS (WORD COUNT)

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a Python coding to perform command line


arguments(word/line counts)

PRE-REQUISITE

Basics of Python Language.

AIM:

To perform command line arguments (word/line counts).

ALGORITHM:

Step 1: Start the program.


Step 2: Add arguments to find the words and lines.
Step 3: Add file name as arguments..
Step 4: Parse the arguments to get the values
Step 5: Format and print the words and lines.
Step 6: Stop the program.

PROGRAM:

parser= argparse.ArgumentParser()

parser.add_argument("- -words", "-w", action="store_true")

parser.add_argument("- -lines", "-w", action="store_true")

parser.add_argument("filename")

59
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

args= parser.parse_args()

if args.words:

print "Words in a file:{}" .format(print_words(args.filename))

elif args.lines:

print "Lines in a file:{}" .format(print_lines(args.filename))

else:

print "Words in a file:{}" .format(print_words(args.filename))

print "Lines in a file:{}" .format(print_lines(args.filename))

OUTPUT:

Python main.py I input.txt

Word in a file 23

Lines in a file 1

CONCLUSION:

Thus the pyhton program to perform command line arguments (word/line counts) was
executed and output was obtained.

60
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES

1. Write a program to find the most frequent words in a text read from a file.
2. Write a program to get a line with max word count from the given file.
3. Write a C Program to copy contents of a file to another file.
4. Write a program append text to a file and display the text
5. Write a python program to find the longest words.
6. Write a program to read a file line by line and store it into an array.
7. Write a Progam to illustrate the use of kwargs in python.

OBJECTIVE QUESTIONS:

1. Which of the following data types is not supported in python?


a) Tuple b) Dictionary c)Generics d) List
2. Which of the following is correct about tuples in python?
a) A tuple is another sequence data type that is similar to the list.
b) A tuple consists of a number of values separated by commas.
c) Unlike lists, however, tuples are enclosed within parentheses.
d) All of the above.
3. Which of the following function merges elements in a sequence?
a) isupper() b) join(seq) c) len(string) d) ljust(width[, fillchar])

VIVA QUESTIONS:

1. What is a Python module?


2. Name the File-related modules in Python?
3. What is the use of args(*) and kwargs(*)?
4. How the command line arguments in python can be processed?
5. State the purpose of python sys module?
6. Explain import statement.
7. Define python modules searching order.
8. What is pickling and unpickling?

61
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

62
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

63
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:11 Date
of Completion Additional Credits

FIND THE MOST FREQUENT WORDS IN A TEXT READ FROM A FILE

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a Python coding to implement file operations.

PRE-REQUISITE

Basics of Python Language.

AIM:

To find the most frequent words in a text read from a file.

ALGORITHM:

Step 1: Start the program.


Step 2: Read the file name.
Step 3: Open the file.
Step 4: Read each line from the file to count the lowers and words.
Step 5: Read each line from the file to replace the punctuations.
Step 6: Split each line into words and count them.
Step 7: Print the words and counts.
Step 8: Stop the program.

64
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PROGRAM:

file=open("C:\\Python27\\dgct.txt","r")

wordcount={}

for word in file.read().split():

if word not in wordcount:

wordcount[word] = 1

else:

wordcount[word] += 1

print (word,wordcount)

file.close()

OUTPUT:

Enter a Filename: dgct.txt


Dgct 1
Dhirajlal 2
Gandhi 2
College 1
Of 1
Technology 1
Salem 2

CONCLUSION:

Thus the python program for the implementation of words in a text read from a file was
executed and the output was obtained.

65
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES

1. Write a python program to find the file attributes.


2. Write a program to read a data from file
3. Write a program to append text to a fileand display the text.
4. Write a program to set file offsets in python.
5. Write a program to read a file line by line and store it into an array.

OBJECTIVE QUESTIONS:

1. Which of the following command is used to open a file in write mode only??
a) infile=open(c:\dgct.txt,r) b) infile=open(c:\\dgct.txt,r)
c) infile=open(file=c:\dgct.txt,r+) d) infile=open(file=c:\\dgct.txt,r)
2. . Which of the following command is used to read n number of charecters from a file using
file oblect<file>
a) file.read(n) b) n=file.read() c) file.readline(n) d) file.readlines()
3. . Which of the following command is used to read the entire contents of the file as a string
using file object<file>
a) tmpfile.read(n) b)tmpfile.read() c)tmpfile.readline()
d)tmpfile.readlines()
4. . Which of the following function do you use to write data in binary file.
a)write b)output c)dump d)send
5. The readlines() method returns
a) str b) a list of lines c) a list of single charecter
d) a list of integers
6. Which function is used to read all charecters?
a)Read() b)Readcharecteers() c)Readall() d)Readchar()

VIVA QUESTIONS:

1. What is file in python?


2. List out the python file modes?
3. What is the use of seek() function?
4. What are the python file methods?
5. What is flush()?
6. What is directory in python?

66
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

67
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

68
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

69
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:12 Date
of Completion Additional Credits

SIMULATE ELLIPTICAL ORBITS IN PYGAME

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a Python coding to implement the linear search.

PRE-REQUISITE

Basics of Python Language.

AIM:

To write a program for elliptical orbits in Pygame.

ALGORITHM:

Step 1 : Start the program.


Step 2 : Class represents the ball that moves in a circle.
Step 3 : Constructor that creates the balls image.
Step 4 : The center the sprite will orbit.
Step 5 : Correct angle in radians.
Step 6 : How far away from the center to orbit,in pixels..
Step 7 : How fast to orbit,in radians per frame.
Step 8 : Update the balls position and calculate a new x,y.
Step 9 : Increase the angle in prep for the next round.
Step 10 : Set the user to be where the mouse is.
Step 11 : Initialize Pygame and set the height and width of the screen.
Step 12 : All blocks and the player block as well.
Step 13 : Set a random center location for the block to orbit.

70
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Step 14 : Create a RED player block and used to manage how fast the screen updates.
Step 15 : See if the player block has collided with anything.
Step 16 : Stop.

PROGRAM:

import pygame
import random
import math
#colors
black = (0,0,0)
white = (255,255,255)
green = (0,255,0)
red = (255,0,0)
blue = (0,0,255)
class block(pygame.sprite.sprite):
def_init_(self,color,width,height):
super()._init_()
self.image = pygame.surface((width,height))
self.image.fill(color)
self.rect=self.image.get_rect()
self.center_x=0
self.center_y=0
self.angle=0
self.radius=0
self.speed=0.05
def update(self):
self.rect.x+self.radius * math.sin(self.angle)+ self.center_x
self.rect.y+self.radius * math.cos(self.angle)+ self.center_y
self.angle+=self.speed
class player(pygame.sprite.sprite):
class to represent the player.
def_init_(self,color,width,height):
create the player image.
super()._init_()
self.image=pygame.surface((width,height))
self.image.fill(color)
self.rect=self.image.get_rect()
def update(self);

71
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

pos=pygame.mouse.get_pos()
self.rect.x=pos(0)
self.rect.y=pos(1)
pygame.init()
screen_width=700
screen_height=400
screen=pygame.display.set_mode((screen_width,screen_height))
block_list=pygame.sprite.group()
all_sprites_list=pygame.sprite.group()
for i in range(50):
block=block(black,20,15)
block.center_x=random.radrange(screen_width)
block.center_y=random.radrange(screen_height)
block.radius=random.radrange(10,200)
block.angle=random.random()*2*math.pi
block.speed=0.008
block_list.add(block)
all_sprites_list.add(block)
player=player(red,20,15)
all_sprites_list.add(player)
done=false
clock=pygame.time.clock()
score=0
while not done:
for event in pygame.event.get():
if event.type==pygame.quit:
done=true
all_sprites_list.update()
screen.fill(white)
blocks_hit_list=pygame.sprite.spritecollide(player,block_list,true)
for block in blocks_hit_list:
score+=1
print(score)
all_sprites_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()

72
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

OUTPUT:

CONCLUSION:

Thus the python program for the implementation elliptical orbits using Pygame is
obtained.

73
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICE EXERCISES:

1. Simulation of solar system in Pygame.


2. Simulation of Planetary orbits.

OBJECTIVE QUESTIONS:

1. A file position in python is


a) tell b) offset c) write d) read

2. Mode which is used to open a file for both appending and reading
a) w+ b) a+ c) ab d) ab+

3. Directory which is used to display the current working location


a) mkdir b) chdir c) getcwd d) rmdir

4. Which of the following allows python to logically organize


a) Module b) object c) source d) list

VIVA QUESTIONS:

1. Define elliptical orbits.


2. What is simulation?
3. Define import statement.
4. What is closing and opening files?
5. Define a function in python.
6. What is python dictionary?
7. Explain tuples in python.

74
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

75
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

76
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment Score /10


EX.No:13 Date
of Completion Additional Credits

SIMULATE BOUNCING BALL USING PYGAME

OBJECTIVE

To acquire programming skills for application development in real-world problem solving.

OUTCOME

Students become expertise to write a Python coding to implement file operations.

PRE-REQUISITE

Basics of Python Language.

AIM

To write the code for bouncing ball in pygame.

ALGORITHM

Step 1: Start
Step 2: Number of frames per second
Step 3: Change this value to speed up or slow down your game
Step 4: Global values to be used through the program
Step 5 : Set up the colors
Step 6 : Draw the arena the game will be played in
Step 7 : Draw outline of arena and center line
Step 8 : Draw the paddle and stop the paddle moving too low
Step 9 : draw and move the ball and returns new position
Step 10 : Checks for collision with the wall, and bounces ball off it and returns new
direction
Step 11 : Initiate variable and set starting positions and any future changes made within
rectangles
Step 12: Create rectangles for ball and paddles
Step 13 : Draws the starting position of the arena and make cursor invisible.
Step 14 : Mouse movement commands are produced
Step 15 : Stop

77
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PROGRAM:

Shapes.py

def rectangle(turtle, x, y, width, height, color):


turtle.penup()
turtle.setx(x)
turtle.sety(y)
turtle.pendown()
turtle.color(color, color)
turtle.begin_fill()
for i in range(2):
turtle.forward(width)
turtle.left(90)
turtle.forward(height)
turtle.left(90)
turtle.end_fill()

main.py

from turtle import *


from shapes import *

screen = Screen()

board = Turtle()
board.speed(0)

rectangle(board, 0, 0, 200, 5, "black")


rectangle(board, 0, 0, 5, 200, "black")
rectangle(board, 0, 195, 200, 5, "black")
rectangle(board, 195, 0, 5, 200, "black")

board.ht()

ball = Turtle()
ball.speed(0)
screen.register_shape("ball", ((0, 0), (0, 5), (5, 5), (5, 0)))
ball.shape("ball")
ball.penup()
ball.setx(100)
ball.sety(100)

def collisionCheck(r1x, r1y, r1w, r1h, r2x, r2y, r2w, r2h):

78
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

return (r1x < r2x + r2w) and (r1x + r2w > r2x) and (r1y < r2y + r2h) and (r1h + r1y > r2y)

dx = 1
dy = 1.5

while True:
ball.setx(ball.xcor() + dx)
ball.sety(ball.ycor() + dy)

if collisionCheck(ball.xcor(), ball.ycor(), 5, 5, 0, 0, 200, 5):


dy = dy * -1

if collisionCheck(ball.xcor(), ball.ycor(), 5, 5, 0, 0, 5, 200):


dx = dx * -1

if collisionCheck(ball.xcor(), ball.ycor(), 5, 5, 0, 195, 200, 5):


dy = dy * -1

if collisionCheck(ball.xcor(), ball.ycor(), 5, 5, 195, 0, 5, 200):


dx = dx * -1

79
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

OUTPUT:

CONCLUSION:

Thus the python program for the implementation of Simulate bouncing ball using Pygame
was executed successfully.

VIVA QUESTIONS:

1. What is pygame?
2. Mention the applications of pygame.
3. List the library files that python uses for designing.
4. Can pygame applications run on android phones?
5. Mention some alternative for pygame library.

80

Potrebbero piacerti anche