You are on page 1of 18

BANSAL INSTITUTE OF RESEARCH TECHNOLOGY &

SCIENCE BHOPAL
NAME – CHANCHAL MALVIYA ROLL NO – 0506CS171005
BRANCH – COMPUTER SCIENCE SEMESTER – 5th
SUBJECT –PYTHON

S. NAME OF EXPERIMENT SIGN


NO
1. To write a Python program to find GCD of two numbers.
2. To write a Python Program to find the square root of a number
by Newton’s Method.
3. 3. To write a Python program to find the exponentiation of a
number.
4. To write a Python Program to find the maximum from a list
of numbers.
5. To write a Python Program to perform Linear Search.
6. To write a Python Program to perform binary search.
7. To write a Python Program to perform selection sort.
8. To write a Python Program to perform insertion sort.
9. To write a Python Program to perform Merge sort.

10. To write a Python program to find first n prime numbers.

11. To write a Python program to multiply matrices.

12. To write a Python program for command line arguments.

13. 13. To write a Python program to find the most frequent


words in a text read from a file.

14. To write a Python program to simulate elliptical orbits in


Pygame.

15. To write a Python program to bouncing ball in Pygame.


1. To write a Python program to find GCD of two numbers.

The Greatest Common Divisor (GCD) of two or more integers is the largest positive integer that
divides a given integer values without remainder. For example, the GCD value of integer 8 and
12 is 4 because, both 8 and 12 are divisible by 1, 2, and 4 (remainder is 0) and the largest
positive integer among them is 4.

ef 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)
Runtime Test Cases
Case 1:
Enter first number:5
Enter second number:15
GCD is:
5
 
Case 2:
Enter first number:30
Enter second number:12
GCD is:
6
2.To write a Python Program to find the square root of a number by Newton’s Method.

Square root expression is rephrased as a parabola that can be optimized via Newtonian
optimization. The same can be applied to higher order roots. Optimal point for this
function is the square root for “a”.

def
newton_method(number,
number_iters = 500):
a = float(number) # number to get
square root of
for i in range(number_iters): # iteration
number
number = 0.5 * (number + a /
number) # update
# x_(n+1) = 0.5 * (x_n +a / x_n)
return number
print newton_method(9)
# Output: 3
print newton_method(2)
# Output: 1.41421356237
3. To write a Python program to find the exponentiation of a number.

Given two numbers a and b, we have to find a to the power b using exponential operator (**)

a = 10
b=3

# calculating power using exponential oprator (**)


result = a**b

print (a, " to the power of ", b, " is = ", result)


4.To write a Python Program to find the maximum from a list of numbers.

Problem Description

The program takes a list and prints the largest number in the list.
Problem Solution
1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Sort the list in ascending order.
4. Print the last element of the list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to find the largest number in a list. The program
output is also shown below.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
Runtime Test Cases
 
Case 1:
Enter number of elements:3
Enter element:23
Enter element:567
Enter element:3
Largest element is: 567
 
Case 2:
Enter number of elements:4
Enter element:34
Enter element:56
Enter element:24
Enter element:54
Largest element is: 56

5.To write a Python Program to perform Linear Search.

A simple approach is to do linear search, i.e


 Start from the leftmost element of arr[] and one by one compare x with each element of
arr[]
 If x matches with an element, return the index.
 If x doesn’t match with any of elements, return -1
 def linear_search(alist, key):
 """Return index of key in alist. Return -1 if key not present."""
 for i in range(len(alist)):
 if alist[i] == key:
 return i
 return -1
  
  
 alist = input('Enter the list of numbers: ')
 alist = alist.split()
 alist = [int(x) for x in alist]
 key = int(input('The number to search for: '))
  
 index = linear_search(alist, key)
 if index < 0:
 print('{} was not found.'.format(key))
 else:
 print('{} was found at index {}.'.format(key, index))

 Runtime Test Cases


 Case 1:
 Enter the list of numbers: 5 4 3 2 1 10 11 2
 The number to search for: 1
 1 was found at index 4.
  
 Case 2:
 Enter the list of numbers: 5 2 1 5 -3
 The number to search for: 2
 2 was found at index 1.
  
 Case 3:
 Enter the list of numbers: 3 5 6
 The number to search for: 2
 2 was not found.

6. To write a Python Program to perform binary search.

7. def binary_search(alist, key):


8. """Search key in alist[start... end - 1]."""
9. start = 0
10. end = len(alist)
11. while start < end:
12. mid = (start + end)//2
13. if alist[mid] > key:
14. end = mid
15. elif alist[mid] < key:
16. start = mid + 1
17. else:
18. return mid
19. return -1
20.  
21.  
22. alist = input('Enter the sorted list of numbers: ')
23. alist = alist.split()
24. alist = [int(x) for x in alist]
25. key = int(input('The number to search for: '))
26.  
27. index = binary_search(alist, key)
28. if index < 0:
29. print('{} was not found.'.format(key))
30. else:
31. print('{} was found at index {}.'.format(key, index))
32.
Runtime Test Cases
33. Case 1:
34. Enter the sorted list of numbers: 3 5 10 12 15 20
35. The number to search for: 12
36. 12 was found at index 3.
37.  
38. Case 2:
39. Enter the sorted list of numbers: -3 0 1 5 6 7 8
40. The number to search for: 2
41. 2 was not found.
42.  
43. Case 3:
44. Enter the sorted list of numbers: 5
45. The number to search for: 5
46. 5 was found at index 0.

7.To write a Python Program to perform selection sort.

def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
 
 
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)
Runtime Test Cases
Case 1:
Enter the list of numbers: 3 1 4 5 2 6
Sorted list: [1, 2, 3, 4, 5, 6]
 
Case 2:
Enter the list of numbers: 2 10 5 38 1 7
Sorted list: [1, 2, 5, 7, 10, 38]
 
Case 3:
Enter the list of numbers: 5 3 2 1 0
Sorted list: [0, 1, 2, 3, 5]
8. To write a Python Program to perform insertion sort.

def insertion_sort(alist):
for i in range(1, len(alist)):
temp = alist[i]
j=i-1
while (j >= 0 and temp < alist[j]):
alist[j + 1] = alist[j]
j=j-1
alist[j + 1] = temp
 
 
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
insertion_sort(alist)
print('Sorted list: ', end='')
print(alist)
Runtime Test Cases
Case 1:
Enter the list of numbers: 2 4 1 5 8 0
Sorted list: [0, 1, 2, 4, 5, 8]
 
Case 2:
Enter the list of numbers: 5 4 3 2 0 -1
Sorted list: [-1, 0, 2, 3, 4, 5]
 
Case 3:
Enter the list of numbers: 3 4 1 4 5 0 7
Sorted list: [0, 1, 3, 4, 4, 5, 7]
9.To write a Python Program to perform Merge sort.

def merge_sort(alist, start, end):


'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
mid = (start + end)//2
merge_sort(alist, start, mid)
merge_sort(alist, mid, end)
merge_list(alist, start, mid, end)
 
def merge_list(alist, start, mid, end):
left = alist[start:mid]
right = alist[mid:end]
k = start
i=0
j=0
while (start + i < mid and mid + j < end):
if (left[i] <= right[j]):
alist[k] = left[i]
i=i+1
else:
alist[k] = right[j]
j=j+1
k=k+1
if start + i < mid:
while k < end:
alist[k] = left[i]
i=i+1
k=k+1
else:
while k < end:
alist[k] = right[j]
j=j+1
k=k+1
 
 
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
merge_sort(alist, 0, len(alist))
print('Sorted list: ', end='')
print(alist)
Runtime Test Cases
Case 1:
Enter the list of numbers: 3 1 5 8 2 5 1 3
Sorted list: [1, 1, 2, 3, 3, 5, 5, 8]
 
Case 2:
Enter the list of numbers: 5 3 2 1 0
Sorted list: [0, 1, 2, 3, 5]
 
Case 3:
Enter the list of numbers: 1
Sorted list: [1]

10. To write a Python program to find first n prime numbers.

r=int(input("Enter upper limit: "))


for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a)
Runtime Test Cases
 
Case 1:
Enter upper limit: 15
2
3
5
7
11
13
 
Case 2:
Enter upper limit: 40
2
3
5
7
11
13
17
19
23
29
31
32
11. To write a Python program to multiply matrices.

Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
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)
Output

[114, 160, 60, 27]


[74, 97, 73, 14]
[119, 157, 112, 23]

12. To write a Python program for command line arguments.


Python supports the creation of programs that can be run on the command line, completely with
command-line arguments. It provides a getopt module, with which command line options and
arguments can be parsed.

Accessing Command Line Arguments

The Python sys module provides access to any of the command-line arguments via sys.argv. It
solves two purposes:

 sys.argv is the list of command line arguments


 len(sys.argv) is the number of command line arguments that you have in your command
line
 sys.argv[0] is the program, i.e. script name
 import sys

 print ‘Number of arguments:’, len (sys.argv),


‘arguments.’

 print ‘Argument List:’, str(sys.argv)

 It will produce the following output:

 Number of arguments: 4 arguments.

 Argument List: [‘sample.py’, ‘inp1’, ‘inp2’, ‘inp3’]

13. To write a Python program to find the most frequent words in a text read from a file.

Given the data set, we can find k number of most frequent words.
The solution of this problem already present as Find the k most frequent words from a file. But
we can solve this problem very efficiently in Python with the help of some high performance
modules.
In order to do this, we’ll use a high performance data type module, which is collections. This
module got some specialized container datatypes and we will use counter class from this
module.
Approach :
1. Import Counter class from collections module.
2. Split the string into list using split(), it will
3. return the lists of words.
4. Now pass the list to the instance of Counter class
5. The function 'most-common()' inside Counter will return
6. the list of most frequent words from list and its count.

# Python program to find the k most frequent words


# from data set
from collections import Counter
  
data_set = "Welcome to the world of Geeks " \
"This portal has been created to provide well written well" \
"thought and well explained solutions for selected questions " \
"If you like Geeks for Geeks and would like to contribute " \
"here is your chance You can write article and mail your article " \
" to contribute at geeksforgeeks org See your article appearing on " \
"the Geeks for Geeks main page and help thousands of other Geeks. " \
  
# split() returns list of all the words in the string
split_it = data_set.split()
  
# Pass the split_it list to instance of Counter class.
Counter = Counter(split_it)
  
# most_common() produces k frequently encountered
# input values and their respective counts.
most_occur = Counter.most_common(4)
  
print(most_occur)

Output :
[('Geeks', 5), ('to', 4), ('and', 4), ('article', 3)]

14. To write a Python program to simulate elliptical orbits in Pygame.

Simulate Elliptical Orbit in Pygame


#Elliptical orbits

import pygame
import math
import sys

pygame.init()
screen = pygame.display.set_mode((600, 300))
pygame.display.set_caption("Elliptical orbit")

clock = pygame.time.Clock()

while(True):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    
    xRadius = 250
    yRadius = 100 
    
    for degree in range(0,360,10):
        x1 = int(math.cos(degree * 2 * math.pi / 360) * xRadius) + 300
        y1 = int(math.sin(degree * 2 * math.pi / 360) * yRadius) + 150
                screen.fill((0, 0, 0))
        pygame.draw.circle(screen, (255, 0, 0), [300, 150], 35)
        pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)
        pygame.draw.circle(screen, (0, 0, 255), [x1, y1], 15)
        
        pygame.display.flip()
        clock.tick(5)

Output:
15. To write a Python program to bouncing ball in Pygame.

# Bouncing ball

import sys, pygame


pygame.init()

size = width, height = 700, 300


speed = [1, 1]
background = 255, 255, 255

screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")

ball = pygame.image.load("ball.jpg")
ballrect = ball.get_rect()

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    ballrect = ballrect.move(speed)


    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]

    screen.fill(background)
    screen.blit(ball, ballrect)
    pygame.display.flip()
    
ball.jpg 
    

Output:

You might also like