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

Python Lab Programs

Python lab programs

Uploaded by

kovayini
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Python Lab Programs

Python lab programs

Uploaded by

kovayini
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 21

1.

GCD OF TWO NUMBERS

n1 = int(input("Enter a number:"))
n2 = int(input("Enter another number:"))
rem = n1 % n2
while rem != 0 :
n1 = n2
n2 = rem
rem=n1 % n2
print ("GCD of given numbers is :", n2)

Output:

Enter a number:4
Enter another number:8
gcd of given numbers is : 4
2. FIND SQUARE ROOT OF A NUMBER(NEWTON’S METHOD)

n = int(input("Enter a number"))
c = int(input("Enter count"))
approx = 0.5 * n
for i in range(c):
final = 0.5 *(approx + n/approx)
approx = final
print("The square root of a number is:", final)
print("If answer is not exact Increase the count value")

Output:

Enter a number 64
Enter count 7
The square root of a number is: 8.0
If answer is not exact Increase the count value
3.POWER OF NUMBER

Program 1:

n = int(input ("Enter a number : "))


e = int(input ("Enter an power : "))
r=n
for i in range (1,e):
r=n*r
print(r)

Program 2:

n = int(input ("Enter a number : "))


e = int(input ("Enter an power : "))
r=n**e
print(r)

Output:
Enter a number : 5
Enter an power : 3
125
4. FIND THE MAXIMUM OF A LIST OF NUMBERS

Program 1:

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

Output:
Enter number of elements:5
Enter element:34
Enter element:12
Enter element:55
Enter element:34
Enter element:10
Largest element is: 55

Program 2:

L=[2,26,7,9,12]
max=L[0]
for i in L:
if (i>max):
max=i
print(Largest element is:”,max)

Output:

Largest element is:26


5. LINEAR SEARCH
l = [4,1,2,5,3] #Set up array
flag=0
s = int(input("Enter search number")) # Ask for a number
for i in range(0,len(l)): # Repeat for each item in list
if s==l[i]: #if item at position i is search time
print("found at position " ,i) #Report found
flag=1
if(flag!=1):
print("Number not found")

Output:
Enter search number5
found at position 3

Enter search number10


Number not found
6. TO CHECK GIVEN NUMBER IS PRIME OR NOT

num=int(input("enter no"))
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")

Output:

enter no 5
5 is a prime number

enter no 6
6 is not a prime number
7.FIRST N PRIME NUMBERS

n=int(input("enter the upper limit"))


for num in range(1,n+1):
for i in range(2,num):
if (num % i)==0:
break
else:
print(num)

Output
enter the upper limit10
2
3
5
7
8.EXPONENTIATION OF NUMBER

import math
n = int(input("Enter number :"))
e=math.exp(n)
print(“Exponentiation is “,e)

output
Enter number :3
Exponentiation is 8.154
9.Binary Search

def binarysearch(list,no):
first = 0
last = len(list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if list[mid] == no :
found = True
pos=mid+1
else:
if no < list[mid]:
last = mid - 1
else:
first = mid + 1
if(return==True):
print(“Found in Position”,pos)
else:
print(“Number not found”)
list=[10,20,40,50,60]
no=int(input(”Enter search No”))
binarysearch(list,no)

output:

Enter search No

20

Found in Position 2
10. Bubble Sort

def bubble_sort(lst):
n=len(lst)
for i in range(n):
for j in range(i+1,n):
if lst[j] < lst[i]:
lst[j], lst[i] = lst[i], lst[j]
return lst
lst = [50,40,30,20,10,67,34,90]
list=bubble_sort(lst)
print(list)
output

[10, 20, 30, 34, 40, 50, 67, 90]


11.Matrix Multiplication

m1=[[1, 2, 3],[4, 5, 6],[7, 8, 9]]

m2=[[10, 11, 12],[14, 15, 16],[19, 20, 21]]

m3=[[0, 0, 0],[0, 0, 0],[0, 0, 0]]

for i in range(len(m1)):

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

for k in range(len(m2)):

m3[i][j]+=m1[i][k]*m2[k][j]

for k in m3:

print(k)

output:

[95, 101, 107]

[224, 239, 254]

[353, 377, 401]


12.Insertion sort

def insertionsort(List):

n=len(List)

for i in range(1,n):

tmp = List[i]

j=i-1

while j >=0 and tmp<List[j]:

List[j+1]=List[j]

j-= 1

List[j+1]=tmp

List = [100,40,30,20,10,67,34,90]

insertionsort(List)

print(List)

out put:

[10, 20, 30, 34, 40, 67, 90, 100]


13.Merge Sort

def mergesort(seq):

if len(seq)<=1:

return seq

m=len(seq)//2

return merge(mergesort(seq[:m]),mergesort(seq[m:]))

def merge(left, right):

result = []

i=j=0

while i <len(left) and j < len(right):

if left[i] < right[j]:

result.append(left[i])

i += 1

else:

result.append(right[j])

j += 1

result += left[i:]

result += right[j:]

return result

r= mergesort([50,40,30,20,10])

print(r)

output:

10,20,30,40,50
14.Selection Sort

list = [64, 25, 12, 22, 11]

n=len(list)

for i in range(n):

midx = i

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

if list[midx] > list[j]:

midx = j

list[i], list[midx] = list[midx], list[i]

print(list)

output:

11,12,22,25,64
15.To Print Python Version, Count Number of Arguments(usingCommand Line Argument)

import sys

print('version is', sys.version)

print("This is the name of the script: ", sys.argv[0])

print("Number of arguments: ", len(sys.argv))

print("The arguments are: " , str(sys.argv))

output:

version is 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)]

This is the name of the script:


C:/Users/PGLAB2/AppData/Local/Programs/Python/Python36-32/j1.py

Number of arguments: 1

The arguments are: ['C:/Users/PGLAB-02/AppData/Local/Programs/Python/Python36-


32/j1.py']
16.Programs for word count in a File

file = open('D:/b.txt', 'r')

num_words=0

for line in file:

words=line.split()

num_words+=len(words)

print("Number of Words:")

print(num_words)

output:

Number of Words:

b.txt

cat bat

rat apple

run pan

man
17.Program to find frequency of words in a file

f=open("D:/b.txt","r+")

wc={}

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

if word not in wc:

wc[word]=1

else:

wc[word]+=1

for k,v in wc.items():

print(k,v)

f.close()

output:

cat 1

bat 3

rat 2

apple 2

run 2

pan 2

man 3

b.txt

cat bat

rat apple

run pan

bat bat

rat apple

run pan
man man man

18.Simulate elliptical orbits in Pygame

Program:
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)+360
y1=int(math.sin(degree*2*math.pi/360)*yRadius)+360
screen.fill([0,0,255])
pygame.draw.circle(screen,[255,0,0],[300,150],50,0)
pygame.draw.ellipse(screen,[255,255,255],[50,50,500,200],1)
pygame.draw.circle(screen,[0,255,255],[x1,y1],15)
pygame.display.flip()
clock.tick(5)

18.Simulate elliptical orbits in Pygame


19. Simulate bouncing ball using Pygame
import pygame, sys, time, random
from pygame.locals import *
from time import *
pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption("Bounce")
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
info = pygame.display.Info()
sw = info.current_w
sh = info.current_h
y= 0
yy= sh
while True:
windowSurface.fill(BLACK)
pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)
sleep(.006)
y+= 1
if y>sh:
pygame.draw.circle(windowSurface, GREEN , (250,yy), 13, 0)
sleep(.0001)
yy +=-1
if yy<-.00001:
y=0
y+= 1
pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()

19. Simulate bouncing ball using Pygame

You might also like