solamalai coleege of engineering(approved by aicte, new delhi , affiliated to anna university,...

46
SOLAMALAI COLEEGE OF ENGINEERING (Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 www.solamalaice.ac.in DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR OF ENGINEERING FIRST SEMESTER GE8161 PROBLEM SOLVING AND PYTHON PROGRAMMING LAB MANUAL (Regulation 2017)

Upload: others

Post on 25-Aug-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

SOLAMALAI COLEEGE OF ENGINEERING (Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai)

Veerapanjan, Madurai-625 020

www.solamalaice.ac.in

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

BACHELOR OF ENGINEERING

FIRST SEMESTER

GE8161 PROBLEM SOLVING AND PYTHON PROGRAMMING LAB

MANUAL

(Regulation 2017)

Page 2: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

GE8161 PROBLEM SOLVING AND PYTHON PROGRAMMING

LAB MANUAL

OBJECTIVES

• To write, test, and debug simple Python programs.

• To implement Python programs with conditionals and loops.

• Use functions for structuring Python programs.

• Represent compound data using Python lists, tuples, dictionaries.

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

LIST OF PROGRAMS

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

PLATFORM NEEDED

Python 3 interpreter for Windows/Linux

OUTCOMES

Upon completion of the course, students will be able to:

• Write, test, and debug simple Python programs.

• Implement Python programs with conditionals and loops.

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

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

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

TOTAL: 60 PERIODS

Page 3: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

CONTENTS

Sl.No Ex.No. Title of the Experiments

1 Introduction to python Interpreter – Working Environment

2 Simple Programs

3 1 Compute the GCD of two numbers.

4 2 Find the square root of a number (Newton’s method)

5 3 Exponentiation (power of a number)

6 4a Find the maximum of a list of numbers

4b Removing all the duplicate elements in a list

7 5a Linear search

5b Binary search

8 6a Selection sort

6b Insertion sort

9 7 Merge sort

10 8 First n prime numbers

11 9 Matrix Multiplication

12 10 Programs that take command line arguments (word count)

13 11 Find the most frequent words in a text read from a file

14 Pygame Installation - Steps

15 12 Simulate elliptical orbits in Pygame

16 13 Simulate bouncing ball using Pygame

17 Do Yourself

18 Viva Questions

Page 4: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

IDLE

Integrated DeveLopment Environment or Integrated Development

and Learning Environment, is an integrated development environment for Python, It

provides GUI Interface

Page 5: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR
Page 6: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

SIMPLE PROGRAMS

Program 1: Addition of two numbers

a=5

b=6

print (a+b)

Program 2: Multiplication of two numbers

a=int(input("enter a value"))

b=int(input("enter a value"))

c=a * b

print("Multiplication of ", a, "x", b,"is", c)

Program 3: Factorial of a given Number

N=int(input("enter value"))

fact=1

i=1

while i<=N :

fact=fact * i

i=i+1

print(" Factorial of ",N, " is ", fact)

Program 4: Finding odd or even

N=int(input("enter a value"))

c=N % 2

if c == 0 :

print (" Given " , N, ". is EVEN")

else :

print( " Given " ,"N", "is ODD")

Program 5: Sum of N integers using function

def sum() : -----------------”function definition”

Page 7: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

n=int(input("enter a value"))

sum=0

for i in range (0,n) :

x=int(input("enter value"))

sum=sum + x

print ("Sum is ", sum)

sum() -------------”function call statement”

Program 6: Print Odd numbers in List

def ODD () :

# function block starts ---------------- single comment line

list= [4, 2, 8, 9, 3, 7]

list1=[]

j=0

for i in list :

if i % 2 != 0 :

list1.append(i)

j=j+1

for i in list1 :

print( i)

ODD ()

Page 8: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex. No 1 COMPUTE THE GCD OF TWO NUMBERS.

Aim:

To compute the GCD of two numbers

Algorithm

1. Import the math package.

2. Read two input values using input function

3. convert these values into integers

4. Store these values into two variables

5. Use the in-built function to find the GCD of both the numbers.

6. Print the GCD.

7. Exit.

Pseudocode

import

A=input()

B=input()

x=int()

y=int()

C=gcd()

print()

Expected Output

C:\Python36-32\mypgm>ex1.py

enter first value12

enter second value20

The GCD of 12 , 20 is 4

Page 9: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex. No 2 FIND THE SQUARE ROOT OF A NUMBER (NEWTON’S METHOD)

Aim

To find the square root of a number (Newton’s method)

Algorithm

1. create a function using def

2.Read one input value using input function

3. convert it ifloat integers

4. find the square root of the given number

6. Print the result

7. call the function

8. Exit.

Pseudocode

print ("Newton's Method.")

def function_name :

A=input()

x=float()

C=

print()

function_name

Expected Output

C:\Python36-32\mypgm>a2.py

Newton's Method.

enter a value16

Square root of 16 is= 4.0

Page 10: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex. No 3 EXPONENTIATION (POWER OF A NUMBER)

Aim

To write a python program to find exponentiation (power of a Number)

Algorithm

1. Create a function using def

2. Check if exponent value

a. If exponent == 1

Return base value

b. else

Recursively call the function with (base, exponent-1)

Multiply the result returned by each recursive call with base value and

Return the final result

3. Read base & exponent values using input function

4. Call the function & Print the Result

Pseudocode

def power(base,exp):

if exp==1:

return(base)

if exp!=1:

return(base*power( ))

base=int(input("Enter base: "))

exp=int(input("Enter exponential value: "))

print("Result:",power( ))

Expected Output

Enter base: 10

Enter exponential value: 5

Result: 100000

Page 11: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex. No 4a FIND THE MAXIMUM OF A LIST OF NUMBERS

Aim

To write a python program to find Maximum of a List of Numbers

Algorithm

1. Initialize a List

2. Read the Number of Elements

3. Read the List values one by one

4. Set Max = first element of the list

5. Compare Max with List elements

6. If Max< List element

7. Set Max= List element

8. Continue the step 5 until reach the end of the List

9. Print the Max

Pseudocode :

def MaxList():

list1=[]

N=int(input( ))

for i in range (0,N):

x=int(input( ))

list1.append(x)

Max=list1[0]

print(Max)

j=1

for condition :

if condition :

statement

print(" The Maximum Element in the List is ",Max)

MaxList()

Page 12: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Expected Output

Enter the number of elements5

enter value11

enter value22

enter value55

enter value112

enter value66

[11, 22, 55, 112, 66]

The Maximum Element in the List is 112

Page 13: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex. No 4b REMOVING ALL THE DUPLICATE ELEMENTS IN A LIST

Aim

To write a python program to remove all the duplicate elements in a list.

Algorithm

1. Initialize a List

2. Read the Number of Elements

3. Read the List values one by one

4. Set Dup = first element of the list

5. Compare Dup with List elements

6. If Dup = List element

7. Delete the List element

8. Continue the step 5 until the end of the List is reached

9. Print the duplicate List Elements

Pseudocode :

def DupList():

list1=[]

Dup = Set()

for val in list1:

if val not seen

output.append(val)

seen.add(val)

return output

list1=[]

result=DupList(val)

print(result)

Expected Output:

[ 5 , 1 , 4 ]

Page 14: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex. No 5a LINEAR SEARCH

Aim

To write a python program to perform Linear Search

Algorithm

Linear Search

1. Define a function called LS()

2. Define a empty list

3. Set a flag to 0

4. Read number of elements, store it in a variable called N

5. Read the values one by one using for loop

a. Append each value into the List

6. Print the list

7. Read key values to be searched in the list

8. Check whether key present in the list one by one using loop statement

a. if found ,Set flag to 1

9. If flag==1 , then print “key is found at position pos_value“

10. Else , print “key not found”

11. Call the function LS() at end of code

Pseudocode:

def LS() :

listA=

flag=

N=

print("Enter values one by one")

for i in

a=

listA .

print(listA)

key=

for

if :

flag

Page 15: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

if

print()

else:

printf()

LS()

Expected Output

C:\Python36-32\mypgm>a1.py

enter no.of values4

Enter values one by one

enter value11

enter value22

enter value33

enter value44

[11, 22, 33, 44]

enter key value22

22 is present in the List at position 2

Page 16: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex. No 5b BINARY SEARCH

Aim

To write a python program to perform Binary Search

Algorithm

Binary Search

1. Define a function called BS(alist,key)

2. Set a first & last values to point the boundary of list to be searched

3. Find mid position of the given list called alist

4. Compare key with mid position element

a. If mid element == key

Set found=True, print key found

b. If mid element < key

Set last= midposition -1

c. If mid element > key

Set first= midposition +1

5. Continue the steps 3 & 4 until the element found or reach the end of the list

6. Initialize a list ( elements in sorted order)

7. Call BS() with name of list & key value : BS(alist,key)

8. Print the result

Pseudocode:

def binarySearch(alist, key) :

first = 0

last = len(alist)-1

found = False

while first<=last and not found:

midpoint = ( )//2

if condition :

statement

elif condition :

statement

else:

return found

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]

x=binarySearch(testlist, 3)

print(x)

y=binarySearch(testlist, 13)

print(y)

Page 17: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Expected Output

False

Element Found 13

True

Page 18: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex No : 6a SELECTION SORT

Aim

To write a python program to perform Selection Sort

Algorithm

1. Set MIN to location 0

2. Search the maximum element in the list

3. Swap the value at location maximum

4. Decrement maximum to point to the next element

5. Repeat until the list is sorted.

Pseudocode

def selectionSort(alist):

for i in range(len(alist) , , ,):

Initialize positionOfMax as zero

for location in range( ):

if alist[location]>alist[positionOfMax]:

Equate positionOf Max and location

Swap the values

temp = alist[i]

alist[i] = alist[positionOfMax]

alist[positionOfMax] = temp

alist = [ , , , ]

Call selectionSort( )

print( )

Expected Output:

alist = [17, 20, 26, 31, 44, 54, 55, 77, 93]

Page 19: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex No : 6b INSERTION SORT

Aim

To write a python program to perform Insertion Sort

Algorithm

1. If it is first element, it is already sorted. Return 1

2. Pick next element

3. Compare with all elements in the sorted sub-list.

4. Shift all the elements in the sublist that is greater than the value to be sorted.

5. Insert the value.

6. Repeat until the list is sorted.

Pseudocode

def insertionSort(alist):

for i in range():

Equate currentvalue with alist[i]

Equate position and index

while pos>0 and alist[pos-1]>currentvalue:

alist[pos]=alist[pos-1]

Decrement pos

alist[position]=currentvalue

alist = [ , , , ]

call insertionSort( )

print( )

Expected Output:

alist = [17, 20, 26, 31, 44, 54, 55, 77, 93]

Page 20: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex No : 7a MERGE SORT

Aim

To write a python program to perform Merge Sort

Algorithm

1. To sort the entire sequence A[1..n]

2. Make a call to the procedure mergesort(A,1,n)

3. Mergesort(A,p,r)

4. Check if p<r then q= floor(p+r)/2

5. Merge (A,p,q)

6. Merge (A,q+1,r)

7. Merge (A,p,q,r)

Pseudocode

def mergesort( var a as list ):

if ( n == 1 ) return a

var l1 as list = a[0] ... a[n/2]

var l2 as list = a[n/2+1] ... a[n]

Call mergesort recursively( )

return merge( l1, l2 )

def merge( var a as list, var b as list ):

var c as list

while a and b have elements

if ():

add b[0] to the end of c

remove b[0] from b

else:

add a[0] to the end of c

remove a[0] from a

while ( a has elements ):

add a[0] to the end of c

remove a[0] from a

while ( b has elements ):

add b[0] to the end of c

remove b[0] from b

return c

Page 21: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Expected Output:

Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]

Splitting [54, 26, 93, 17]

Splitting [54, 26]

Splitting [54]

Merging [54]

Splitting [26]

Merging [26]

Merging [26, 54]

Splitting [93, 17]

Splitting [93]

Merging [93]

Splitting [17]

Merging [17]

Merging [17, 93]

Merging [17, 26, 54, 93]

Splitting [77, 31, 44, 55, 20]

Splitting [77, 31]

Splitting [77]

Merging [77]

Splitting [31]

Merging [31]

Merging [31, 77]

Splitting [44, 55, 20]

Splitting [44]

Merging [44]

Splitting [55, 20]

Splitting [55]

Merging [55]

Splitting [20]

Merging [20]

Merging [20, 55]

Merging [20, 44, 55]

Merging [20, 31, 44, 55, 77]

Merging [17, 20, 26, 31, 44, 54, 55, 77, 93]

[17, 20, 26, 31, 44, 54, 55, 77, 93]

Page 22: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex. No 8 FIRST N PRIME NUMBERS

Aim

To write a python program to find first N prime Numbers

Algorithm

1. Read lower & Upper bound values for the Range

2. Foe each number in the Range

3. Divide the num by 2 to num-1

4. Check the remainder

If Remainder == 0 then,

Num is not a prime number.

Else

Print the Number as Prime

5. Repeat the Steps 2 to 4 until reach the Upper bound of the Range

Pseudocode:

lower = int(input("Enter lower range: "))

upper = int(input("Enter upper range: "))

print("Prime numbers between",lower,"and",upper,"are:")

for num in range(lower,upper + 1):

if num > 1:

for i in range(2,num):

if ( ) == 0:

break

else:

print(num)

Expected Output

Enter lower range: 2

Enter upper range: 10

Prime numbers between 1 and 25 are: 2 3 5 7

Page 23: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex No : 9 MATRIX MULTIPLICATION

Aim

To write a python program to perform Matrix Multiplication.

Algorithm

Matrix-Multiply(A, B)

1. Input two matrixes.

2. Output Output matrix C.

3. Complexity O(n^3)

4. if columns [A] ≠ rows [B]

then error "incompatible dimensions"

5. else

for i =1 to rows [A]

for j = 1 to columns [B]

C[i, j] =0

for k = 1 to columns [A]

C[i, j]=C[i, j]+A[i, k]*B[k, j]

6. return C

Pseudocode

Input: matrices A and B

Let C be a new matrix of the appropriate size

Pick a tile size T = Θ(M)

For I from 1 to n in steps of T:

For J from 1 to p in steps of T:

For K from 1 to m in steps of T:

Multiply AI:I+T, K:K+T and BK:K+T, J:J+T into CI:I+T, J:J+T, that is:

For i from I to min(I + T, n):

For j from J to min(J + T, p):

Let sum = 0

For k from K to min(K + T, m):

Set sum ← sum + Aik × Bkj

Set Cij ← Cij + sum

Return C

Expected Output:

[114, 160, 60, 27]

[74, 97, 73, 14]

[119, 157, 112, 23]

Page 24: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex No : 10 COMMAND LINE ARGUMENTS – WORD COUNT

Aim

To write a python program to perform count of the number of words using command

line arguments.

Algorithm

1. Start the program

2. Open the file by entering the name in read mode

3. Using For loop find the split point using a space.

4. Count the number of words in the file at split points.

5. Display the count of words

6. Terminate the loop and the program.

Pseudocode

# Command Line Arguments - find word count in a file

fname = input( filename)

initialize num_words=0

with open(fname , r) as file:

for loop:

words = line.split()

num_words += len(words)

print (num_words)

Expected Output: Enter file name: data1.txt

Number of words:

2

Enter file name: data2.txt

Number of words:

5

Page 25: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex No : 11 FIND FREQUENCY OF WORDS

Aim

To write a python program to find the frequency of words using python file

programming.

Algorithm

1.Algorithm to count the frequency of occurrence

2.import re and string packages

3.open the file in read mode

4.read the text string in the document

5. Match the words with the pattern of test string

6.Using for loop count the frequency of words

7. Increment the frequency count if pattern occurs for second time.

8. Display the frequency count

9.Terminate the loop and the program.

Pseudocode

# Count frequency of word in a file

import re and string

frequency = {}

document_text = open(filename, 'r')

text_string = document_text.read()

match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)

for loop match pattern:

count = frequency and get(word,0)

increment the count

frequency_list = frequency.keys()

for loop frequency_list:

print frequency of words

Expected Output:

before 2

battle 1

field 1

all 2

any 1

altogether 1

ago 1

advanced 1

add 1

above 1

Page 26: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

PYGAME INSTALLATION

To Install Pygame Module

Steps:

1. Install python 3.6.2 into C:\

2. Go to this link to install pygame www.pygame.org/download.shtml

3. Click and download msi file for Python 2.7

4. Double Click to install

5. Open IDLE and Type >>> import pygame

Open Command Prompt ( To install in Linux Environment )

1. Type the following command

C:\>py -m pip install pygame --user

Collecting pygame

Downloading pygame-1.9.3-cp36-cp36m-win32.whl (4.0MB)

100% |████████████████████████████████| 4.0MB

171kB/s

Installing collected packages: pygame

Successfully installed pygame-1.9.3

Page 27: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

2. Now, pygame installed successfully

3. To see if it works, run one of the included examples in pygame-1.9.3

• Open command prompt

• Type the following

C:\>cd Python36-32\Scripts\pygame-1.9.3

C:\Python36-32\Scripts\pygame-1.9.3>cd examples

C:\Python36-32\Scripts\pygame-1.9.3\examples>aliens.py

C:\Python36-32\Scripts\pygame-1.9.3\examples>

Page 28: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Do Yourself

1. Write Pygame code to develop the following

2. Sort & Print 10 students Names in Alphabetical order

3. Write Pygame code to develop the following

Page 29: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex No : 12 SIMULATE ELLIPTICAL ORBITS

Aim

To write a python program to simulate the Elliptical orbits using Pygame in python

programming.

Algorithm

1. Import the pygame module

2. Call pygame init function

3. Set the screen display mode

4.Using While loop set the pygame event

5. If Event = QUIT then quit the pygame.

6. Using the draw function draw the circle and elliptical orbits

7. Update the screen

8. Terminate the pygame

Pseudocode

import pygame

pygame.init()

screen = pygame.display.set_mode( )

done = False

while not done:

for event in pygame.event.get():

if event.type == pygame.QUIT:

done = True

pygame.draw.circle(screen, (color coordinates), [screen coordinates], size, radius)

pygame.draw.ellipse(screen, (color coordinates), [Screen Coordinates], orbits)

pygame.display.flip()

Expected Output:

Page 30: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex No : 13 SIMULATE BOUNCING BALL

Aim

To write a python program to simulate the bouncing Ball using Pygame in python

programming.

Algorithm

1. Import system,pygame

2. Initialize the pygame

3. Set the initial value of the variables.

4. Set the screen Display mode.

5. Load the ball image to the python program.

6. Set the gravity and horizontal acceleration

7. Set the vertical and Horizontal Speed.

8. Initialize the clock timer.

9. Using While loop Make the clock to tick.

10.Using While loop set the events.

11.If event type = QUIT then Quit Pygame.

12.Else set the keyboard controls UP , DOWN , LEFT , RIGHT for ball movement

13.Set the screen blit coordinates.

14.Update or refresh the screen.

15. Terminate the pygame.

Pseudocode

import sys,pygame

pygame.init()

… variables…

set the screen display mode with size

load the ball into the program

set the gravity acceleration

set the horizontal acceleration to zero

initialize the vertical speed to zero

initialize the horizontal speed to zero

clock = pygame.time.Clock()

While Loop:

Clock is ticking

Set the keyboard controls UP , DOWN , LEFT , RIGHT

screen.blit(ball, (x, y))

pygame.display.update()

Page 31: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Expected Output:

Page 32: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Viva Question

1. What is Interpreted Language?

2. What is Interactive & Script mode?

3. What is a python module?

4. What is a Linear Search?

5. What is Binary Search?

6. What is sorting?

7. What is file?

8. How will you open a file?

9. List out Condition statements

10. List out Control statements

11. What is slicing?

12. What is exception handling?

13. What is the use of Pygame module”

14. What is variable?

15. How will you get input from keyboard?

16. How will you display on screen?

17. What is list?

18. What is None type?

19. How will you add values into the list at runtime?

20. What is a prime number?

21. What is Function?

22. What is recursion?

23. How will you invoke a function?

24. What is nested functions?

25. What is the use of in range {} ?

Page 33: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Ex No : 1

# Python program to find the G.C.D of two input number

# define a function

def computeGCD(x, y):

# choose the smaller number

if x > y:

smaller = y

else:

smaller = x

for i in range(1, smaller+1):

if((x % i == 0) and (y % i == 0)):

gcd = i

return gcd

#num1 = 54

#num2 = 24

# take input from the user

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

print("The G.C.D. of", num1,"and", num2,"is", computeGCD(num1, num2))

Ex No : 2

#Python Program to calculate the square root

# Note: change this value for a different result

Page 34: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

num = 8

# uncomment to take 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))

Ex No : 3

# Compute exponentiation i.e. power of a number

def power(base,exp):

if(exp==1):

return(base)

if(exp!=1):

return(base*power(base,exp-1))

base=int(input("Enter base: "))

exp=int(input("Enter exponential value: "))

print("Result:",power(base,exp))

Ex No : 4a

# Maximum of a list of numbers

a=[]

n=int(input("Enter number of elements:"))

for i in range(1,n+1):

b=int(input("Enter element:"))

a.append(b)

Page 35: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

a.sort()

print("Largest element is:",a[n-1])

Ex No : 4b

# Program to remove all duplicates in the list

def remove_duplicates(values):

output = []

seen = set()

for value in values:

# If value has not been encountered yet,

# ... add it to both list and set.

if value not in seen:

output.append(value)

seen.add(value)

return output

# Remove duplicates from this list.

values = [5, 5, 1, 1, 2, 3, 4, 4, 5]

result = remove_duplicates(values)

print(result)

Ex No : 5A

#Linear search

Page 36: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

list_of_elements = [4, 2, 8, 9, 3, 7]

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

found = False

for i in range(len(list_of_elements)):

if(list_of_elements[i] == x):

found = True

print("%d found at %dth position"%(x,i))

break

if(found == False):

print("%d is not in list"%x)

Ex No : 5B

# binary search

# stepwise explanatino

#http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBinarySearc

h.html

def binarySearch(alist, item):

first = 0

last = len(alist)-1

found = False

while first<=last and not found:

Page 37: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

midpoint = (first + last)//2

if alist[midpoint] == item:

found = True

print("Element Found",item)

else:

if item < alist[midpoint]:

last = midpoint-1

else:

first = midpoint+1

return found

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]

print(binarySearch(testlist, 3))

print(binarySearch(testlist, 13))

Ex No : 6A

#Selection sort

# Stepwise explanation

#http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSo

rt.html

def selectionSort(alist):

for fillslot in range(len(alist)-1,0,-1):

Page 38: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

positionOfMax=0

for location in range(1,fillslot+1):

if alist[location]>alist[positionOfMax]:

positionOfMax = location

temp = alist[fillslot]

alist[fillslot] = alist[positionOfMax]

alist[positionOfMax] = temp

alist = [54,26,93,17,77,31,44,55,20]

selectionSort(alist)

print(alist)

Ex No : 6B

# Insertion Sort

# Step wise Explanation

#http://interactivepython.org/courselib/static/pythonds/SortSearch/TheInsertionSor

t.html

def insertionSort(alist):

for index in range(1,len(alist)):

currentvalue = alist[index]

position = index

while position>0 and alist[position-1]>currentvalue:

alist[position]=alist[position-1]

Page 39: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

position = position-1

alist[position]=currentvalue

alist = [54,26,93,17,77,31,44,55,20]

insertionSort(alist)

print(alist)

Ex No: 7a

# program for merge sort

# step wise explanation

#http://interactivepython.org/courselib/static/pythonds/SortSearch/TheMergeSort.h

tml

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):

Page 40: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

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 = [54,26,93,17,77,31,44,55,20]

mergeSort(alist)

print(alist)

Ex No : 8

# Python program to display all the prime numbers within an interval

# change the values of lower and upper for a different result

Page 41: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

lower = 900

upper = 1000

# uncomment the following lines to take input from the user

#lower = int(input("Enter lower range: "))

#upper = int(input("Enter upper range: "))

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)

Ex No:9

#Matrix Multiplication

# Program to multiply two matrices using nested loops

# 3x3 matrix

X = [[12,7,3],

[4 ,5,6],

[7 ,8,9]]

# 3x4 matrix

Page 42: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

Y = [[5,8,1,2],

[6,7,3,0],

[4,5,9,1]]

# result is 3x4

result = [[0,0,0,0],

[0,0,0,0],

[0,0,0,0]]

# iterate through rows of X

for i in range(len(X)):

# iterate through columns of Y

for j in range(len(Y[0])):

# iterate through rows of Y

for k in range(len(Y)):

result[i][j] += X[i][k] * Y[k][j]

for r in result:

print(r)

Ex No : 10

# Command Line Arguments - to find the word count in a file

# data1.txt

# data2.txt

Page 43: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

fname = input("Enter file name: ")

num_words = 0

with open(fname, 'r') as f:

for line in f:

words = line.split()

num_words += len(words)

print("Number of words:")

print(num_words)

Ex No:11

# Count frequency of word in a file

# test.txt

import re

import string

frequency = {}

document_text = open('test.txt', 'r')

text_string = document_text.read().lower()

match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)

for word in match_pattern:

count = frequency.get(word,0)

frequency[word] = count + 1

frequency_list = frequency.keys()

Page 44: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

for words in frequency_list:

print (words, frequency[words])

Ex No:12

# Simulate elliptical orbits in Pygame using python programming .

import pygame

pygame.init()

screen = pygame.display.set_mode((400, 300))

done = False

while not done:

for event in pygame.event.get():

if event.type == pygame.QUIT:

done = True

pygame.draw.circle(screen, (255,255,255), [150, 95], 5, 3)

pygame.display.update()

pygame.draw.circle(screen, (255,255,255), [135, 95], 5, 3)

pygame.draw.circle(screen, (255,255,255), [120, 95], 5, 3)

pygame.draw.circle(screen, (255,255,255), [105, 100], 5, 3)

pygame.draw.circle(screen, (255,255,255), [90, 110], 5, 3)

pygame.draw.circle(screen, (255,255,255), [85, 130], 5, 3)

pygame.draw.circle(screen, (255,255,255), [85, 150], 5, 3)

Page 45: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

pygame.draw.circle(screen, (255,255,255), [90, 170], 5, 3)

pygame.draw.circle(screen, (255,255,255), [110, 185], 5, 3)

pygame.draw.circle(screen, (255,255,255), [140, 195], 5, 3)

pygame.draw.circle(screen, (255,255,255), [170, 195], 5, 3)

pygame.draw.circle(screen, (255,255,255), [200, 190], 5, 3)

pygame.draw.circle(screen, (255,255,255), [230, 180], 5, 3)

pygame.draw.circle(screen, (255,255,255), [250, 160], 5, 3)

pygame.draw.ellipse(screen, (255,0,0), [100, 100, 100, 70], 10)

pygame.display.flip()

Ex No:13

#Simulate bouncing ball using Pygame using python programming.

import pygame

from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((400, 300))

done = False

while not done:

for event in pygame.event.get():

if event.type == pygame.QUIT:

done = True

Page 46: SOLAMALAI COLEEGE OF ENGINEERING(Approved by AICTE, New Delhi , Affiliated to Anna University, Chennai) Veerapanjan, Madurai-625 020 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING BACHELOR

pygame.draw.circle(screen, (255,255,255), [100, 80], 10, 0)

pygame.display.update()

pygame.draw.circle(screen, (0,0,0), [100, 80], 10, 0)

pygame.display.update()

pygame.draw.circle(screen, (255,255,255), [150, 95], 10, 0)

pygame.display.update()

pygame.draw.circle(screen, (0,0,0), [150, 95], 10, 0)

pygame.display.update()

pygame.draw.circle(screen, (255,255,255), [200, 130], 10, 0)

pygame.display.update()

pygame.draw.circle(screen, (0,0,0), [200, 130], 10, 0)

pygame.display.update()

pygame.draw.circle(screen, (255,255,255), [250, 150], 10, 0)

pygame.display.update()

pygame.display.update()

for event in pygame.event.get():

if event.type == QUIT:

pygame.quit()

sys.exit()