INTRODUCTION
WHAT IS PYTHON?
Python is a powerful modern computer programming language. It allows
some similarities to Fortran, one of the earliest programming languages, but it is
much more powerful than Fortran.
Python allows you to use variables without declaring them and it relies on
indentation as a control structure. You are not forced to define classes in
Python(unlike Java) but you are free to do so when convenient.
WHY PYTHON?
1. Simple syntax
2. Free, Open source
3. Interpreted Language
4. Good support
5. Short programs
6. Multi-platform support
TWO MODES OF PYTHON:
Interactive Mode
Script Mode
1.PROGRAM TO FIND THE 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 the given number is :",n2)
OUTPUT:
COMPUTE GCD OF TWO NUMBERS
Enter a number:54
Enter the another number:24
GCD of given number is:6
Enter a number:54
Enter the another number:45
GCD of given number is:9
2. FIND THE SQUARE ROOT OF THE NUMBER
(NEWTON’S METHOD):
def newtonSqrt(n):
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
return approx
n=int(input('Enter upper limit:'))
for i in range (1,n):
print('square root of ',i,'is:',newtonSqrt(i))
OUTPUT:
Enter upper limit: 5
square root of 1 is 1.0
square root of 2 is 1.414213562373095
square root of 3 is 1.7320508075688772
square root of 4 is 2.0
3.TO COMPUTE EXPONENTATION
(POWER OF A NUMBER):
n=int(input(“enter a number:”))
e=int(input(“enter exponent:”))
r=n
for i in range (1,e):
r=n*r
print(‘exponentiation is :’,r)
OUTPUT:
Enter number:25
Enter exponent:2
Exponent is :625
4.TO FIND THE MAXIMUM AND MINIMUM OF A LIST OF
NUMBERS:
list=[]
n=int(input("enter the upper limit"))
for i in range(0,n):
a=int(input("enter the numbers"))
list.append(a)
maxno =list[0]
minno =list[0]
for i in range(len(list)):
if list[i]>maxno:
maxno=list[i]
if list[i]<minno:
minno=list[i]
print("maximum number of the list:",maxno)
print("minimum number of the list:",minno)
OUTPUT:
enter the upper limit:
enter the numbers:
maximum number of the list: 9
minimum number of the list: 1
5a.TO IMPLEMENT LINEAR SEARCH:
list = [14, 20, 58, 90, 3, 17]
x = int(input("Enter number to search: "))
found = False
for i in range(len(list)):
if(list[i] == x):
found = True
print("%d found at %dth position"%(x,i))
break
else:
print("%d is not in list"%x)
OUTPUT:
Enter number to search: 90
90 found at 4th position
5b. IMPLEMENT BINARY SEARCH:
def Binary_search(arr,start,last,element):
mid =(int)(start+last)/2
if(start>last):
print "Element not found"
elif (element>arr[mid]):
start = mid+1
Binary_search(arr,start,last,element)
elif (element<arr[mid]):
last = mid-1
Binary_search(arr,start,last,element)
else:
print "Element is present at index " + str(mid)
arr = [2,14,19,21,99,100,102,103,104,181]
element = 100
start = 0
last = len(arr)-1
Binary_search(arr,start,last,element)
OUTPUT:
Element is present at index 5
6a.TO IMPLEMENT SELECTION SORT:
def ssort (alist):
for i in range (len (alist)):
least=i
for k in range (i+1,len (alist)):
if alist [k]<alist [least]:
least=k
swap (alist ,least,i)
def swap(a,x,y):
tmp =a[x]
a[x]=a[y]
a[y]=tmp
return (a,x,y)
a=[]
n= int(input ("enter the upper limit:"))
for i in range (n):
a.append(int(input ()))
ssort(a)
print ("after sorting ",a)
OUTPUT:
enter the upper limit:9
after sorting [1, 2, 3, 3, 4, 5, 5, 7, 8]
6b.TO IMPLEMENT INSERTION SORT:
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 the upper limit:'))
for index in range(n):
a.append(int(input()))
isort(a)
print ("List after insertion:",a)
OUTPUT:
Enter the upper limit:5
List after insertion: [2, 3, 5, 6, 8]
7.TO IMPLEMENT MERGE SORT:
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
k=k+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)
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, 76, 82, 12]
merging [2, 13, 17, 7, 76, 82, 12]
[2, 13, 17, 7, 76, 82, 12]
8. FIRST n PRIME NUMBERS
n=int(input('enter the upper limit:'))
for num in range(1,n):
for i in range(2,num):
if num%i == 0:
j=num/i
print('%d equals %d * %d'%(num,i,j))
break
else:
print(num, 'is a prime number')
OUTPUT:
Enter the upper limit:6
1 is a prime number
2 is a prime number
3 is a prime number
4 equals 2*2
5 is a prime number
6 equals 2*3
9. MULTIPLY MATRICES:
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]
10.COMMAND LINE ARGUMENTS (WORD COUNT)
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--words','-w', action='store_true')
parser.add_argument('--lines','-l', action='store_true')
parser.add_argument('filename')
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
11.TO FIND THE MOST FREQUENT WORDS IN A TEXT
READ FROM A FILE:
def main():
filename =input ("enter a filename: ").strip()
infile=open(filename, "r")
wordcounts={}
for line in infile :
processLine(line.lower(),wordcounts)
pairs=list(wordcounts.items())
items =[[x,y] for(y,x) in pairs]
items.sort()
for i in range (len(items)-1,len(items)-11,-1):
print(items[i][1]+ "\t" + str(items[i][0]))
def processLine (line,wordcounts):
line=replacepunctuations (line)
words =line.split()
for word in words:
if word in wordcounts:
wordcounts[word] += 1
else:
wordcounts[word]=1
def replacepunctuations(line):
for ch in line:
if ch in "-@#$%^&*()_+=_<>?/,.;:!{}[]'\"":
line=line.replace(ch,"")
return line
main()
OUTPUT:
enter a filename: cse.txt
hi 1
how 1
are 1
you 1
12. SIMULATE ELLIPTICAL ORBITS IN PYGAME
import math
import random
import pygame
class Particle ():
def __init__ (self, x, y, colour=0x000000):
self.x = x
self.y = y s
elf.vx = 0
self.vy = 0
self.colour = colour
def apply_gravity (self, target):
dsqd = (self.x - target.x) ** 2 + (self.y - target.y) ** 2
#g = G*m/dsqd * normalized (self - target)
if dsqd == 0:
return
self.vx += -1 / dsqd * (self.x - target.x) / dsqd ** 0.5
self.vy += -1 / dsqd * (self.y - target.y) / dsqd ** 0.5
def update (self):
self.x += self.vx
self.y += self.vy
pygame.init()
window = pygame.display.set_mode ((600, 400))
main_surface = pygame.Surface ((600, 400))
colours = [0x000000, 0x111111, 0x222222, 0x333333, 0x444444, 0x555555,
0x666666,
0x777777, 0x888888, 0x999999, 0xaaaaaa, 0xbbbbbb] + [0xFF0000,
0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0x888888,
0xFFFFFF, 0x808000, 0x008080, 0x800080,
0x800000]
#colours = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF,
0x00FFFF, 0x888888
0xFFFFFF, 0x808000, 0x008080, 0x800080, 0x800000]
particles = [Particle (200, 100, colours [i]) for i in range (20)]
earth = Particle (200, 200)
for i, p in enumerate (particles):
p.vx = i / 100
while (True):
# main_surface.fill(0x000000)
pygame.draw.circle (main_surface, 0x00FF00, (earth.x, earth.y), 5, 2)
for p in particles:
p.apply_gravity (earth)
p.update ()
pygame.draw.circle (main_surface, p.colour, (int (p.x), int (p.y)), 5, 2)
window.blit(main_surface, (0, 0)) pygame.
display.flip()
OUTPUT:
13. SIMULATE BOUNCING BALL
import sys
import pygame
pygame.init()
size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load('C:\\Users\\admin\\Desktop//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(black) screen.blit(ball, ballrect)
pygame.display.flip()
OUTPUT: