Вы находитесь на странице: 1из 19

#WELCOME TO PYTHON PROGRAMMING

"""Hi Friends, Am E.S.Adithya here presenting you with the complete module of
Python Programs starting from the basic Programs for dummies to Advanced Programs
using Python fanatics... :)

So kindly go through my entire package to learn Python...No knowledge of Python is


required prior to reading the content provided here...It's totally made with the
thought that the person who's going to read this is a total newbie to Python
language...So have fun learning Python buddies :)

In case of any queries or doubts, Kindly don't hesistate to let me know about it
via my mail ID thesmartkid.2000@gmail.com ....It's only your reviews and feedbacks
that's going to encourage me to make more such material to help this world move
forward to a better future :)"""

#PROGRAM 1
#Arithmetic Operators
print("PYTHON PROGRAM 1")
x=15
y=4

print('x+y=',x+y) #add x and y


print('x-y=',x-y) #subtract y from x
print('x*y=',x*y) #multiply x and y
print('x/y=',x/y) #divide x and y
print('x%y=',x%y) #reminder of division
print('x**y=',x**y) #x to the power of y
print('x//y=',x//y) #division without decimal points
x=15; y=-4; print('x//y=',x//y)

#PROGRAM 2
#Comparison Operators
print("PYTHON PROGRAM 2")
x=54
y=18
print('x>y is',x>y)
print('x<y is',x<y)
print('x==y is',x==y)
print('x!=y is',x!=y)
print('x>=y is',x>=y)
print('x<=y is',x<=y)

#PROGRAM 3
#Logical Operators
print("PYTHON PROGRAM 3")

x=True
y=False
print('x and y is',x and y) #logical and
print('x or y is',x or y) #logical or
print('not x is',not x) #logical not

#PROGRAM 4
#Bitwise Operators
print("PYTHON PROGRAM 4")
x=60 # In bitwise 60 = 0011 1100
y=13 # In bitwise 13 = 0000 1101
z=2 # In bitwise 2 = 0000 0010
print('x&y is',x&y) #0011 1100 & 0000 1101 = 0000 1100 =12 [bitwise and]
print('x|y is',x|y) #0011 1100 | 0000 1101 = 0011 1101 = 61 [bitwise or]
print('~x is',~x) #~0011 1100 =-61 in 2's complement [bitwise
print('x^y is',x^y) #0011 1100 ^ 0000 1101 =0011 0001 = 49
print('x>>y is',x>>y) #0011 1100 shifted right 2 times
print('x<<y is',x<<y) #0011 1100 shifted left 2 times

#PROGRAM 5
#Membership Operators
print("PYTHON PROGRAM 5")
x='Python Program'
y={1:'John',2:'9090'}
print('y' in x)
print('p' in x) #case sensitive
print('hello' not in x)
print(1 in y)
print('a' in y)

#PROGRAM 6
#Identity Operators
print("PYTHON PROGRAM 6")
x1=5
y1=5
x2='Python'
y2='python'
x3=[1,2,3]
y3=[1,2,3]
print(x1 is y1) #x1 and y1 are integer comparison
print(x1 is not y1)
print(x2 is y2)#case sensitive, x2 and y2 are string comparison
print(x3 is y3) #lists cannot be compared

#PROGRAM 7
#Assignment Operators
print("PYTHON PROGRAM 7")
a=5
a+=5; print(a)
a-=2; print(a)
a*=3; print(a)
a/=12; print(a)
a**=4; print(a)

#PROGRAM 8
#Precedence of Operators
print("PYTHON PROGRAM 8")
a=20
b=10
c=15
d=5
e=0
e=a+b*c/d
print"Value of a+b*c/d is ",e
e=(a+b)*c/d
print"Value of (a+b)*c/d is",e
e=a+(b*c)/d
print"Value of a+(b*c)/d is",e
e=(a+(b*c))/d
print"Value of (a+(b*c))/d is",e
e=((a+b)*c)/d
print"Value of ((a+b)*c)/d is",e
e=a+b*(c/d)
print"Value of a+b*(c/d) is",e
e=(a+b)*(c/d)
print"Value of (a+b)*c(c/d) is ",e

#PROGRAM 9
print("PYTHON PROGRAM 9")
a=1078372488329084903294032940
print(a)
b=50.0832982394832942397492374893
print(b)
c=1+2j
print(c)
print(a) #print a again
del a
#print(a)
#Note this will give an error in the output screen stating "NameError : name 'a' is
not defined

#PROGRAM 10
print("PYTHON PROGRAM 10")
a=10
print(a, " is of type", type(a))
a=50.0
print(a, " is of type", type(a))
a=3+4j
print(a, " is complex number", type (a))
a=3+4j
print(a, " is complex number?", isinstance(3+4j, complex))

#PROGRAM 11
#String Slicing and Concatenation
print("PYTHON PROGRAM 11")
str="Python Program !"

print str #prints complete string


print str[0] #indexing - Prints first character of the string
print str[7:10] #slicing-Prints characters starting from 7th to 10th
print str[7:] #Prints string starting from 7th character
print str * 2 #Repitition - Prints string two times
print str + "Ver 3.4" #concatenating- Prints concatenated string

#PROGRAM 12
#Lists
print("PYTHON PROGRAM 12")
list1 = [ ] #Empty list
list2 = [ 67, 90, 12, 88] #List with integer elements
list3 = [' python', 6732, 45.23, 'jack' , 100.2] #List with mixed data types
print "List 1 =", list1 #Prints empty list
print "List 2 =", list2 #Prints complete list1
del list2[2] #Delete 2nd element in list2
print "Updated List 2 =", list2
print "First element of List 3=", list3[0]
#prints first element of the list3
print "Sliced List 3= ", list3[1:3]
#prints element starting from 2nd till 3rd
print "Sliced List 3= ", list3[2:]
#prints elements starting from 3rd element
print "Repeated list 3 =", list3 * 2
#prints list3 two times
print "Concatenated list 2 and list 3 =", list2+list3

#PROGRAM 13
#Tuples
print("PYTHON PROGRAM 13")
tuple2=(78, 90, 23, 787)
tuple3=('hello', 673, 34.90, 'world')
list3= ['hello', 673, 34.90, 'world'] #check list elements brackets []
print "Tuple 2= ", tuple2
print "First element of Tuple 2 =", tuple2[0]
print "Concatenated Tuple 2 and Tuple 3 =", tuple2+tuple3
print "Tuple 3=", tuple3
print "List 3=", list3
list3=[1000, 89, 'hi']
print "Changed List 3 =", list3
tuple3=(1000,89, 'hi')
print "Changed Tuple 3 =", tuple3
list3[2]=5555
print "Changed one element of List 3 =", list3
#tuple3[2]=5555
#print "Changed one element of Tuple 3=", tuple3
#note this will give an error in the output screen stating "TypeError : 'tuple'
object does not support item assignment

#PROGRAM 14
#Tuple Functions
print("PYTHON PROGRAM 14")
tup3= ('hello', 23, 34.90, 'world')
print "Length of the Tuple =", len(tup3)
print "Maximum value in the Tuple= ", max(tup3)
print "Minimum value in the Tuple= ", min(tup3)
#del Tuple3
#note this will give an error in the output screen stating "NameError : name
'tuple3' not defined

#PROGRAM 15
#Sets
print("PYTHON PROGRAM 15")
my_set={1,3}
print(my_set)
my_set.add(2) #add an element
print(my_set)
my_set.update([2,3,4]) #add multiple elements
print(my_set)
my_set.update([4,5],{1,6,8}) #add list and set
print(my_set)
#print my_set[0] #TypeError: 'set' object does not support indexing
my_set.discard(4) #discard an element in a set
print(my_set)
my_set.remove(6) #remove an element
print(my_set)
my_set.pop() #pop 1st element from a set
print(my_set)

#PROGRAM 16
#Dictionary
print("PYTHON PROGRAM 16")
dict={'Name': 'John', 'SSN' : 4568, 'Designation': 'Manager'}
print "dict['Name']: ", dict['Name']
print "dict['SSN']: ",dict['SSN']
print "dict['Designation']: ", dict['Designation']
dict['Designation'] = 'Senior Manager ' # update existing memory
dict['Location'] = 'New Delhi' #add new entry
print("After updating")
print "dict['Designation']: ", dict['Designation']
print "dict['Location']: ", dict['Location']
print "Length of the Dictionary =", len(dict)

# ---------------------------------------------------
# IF,IF-ELSE,IF-ELIF-ELSE,NESTED IF [Flow of Control]
# ---------------------------------------------------

#PROGRAM 17

age = input("What's your age = ")

if (age>=60):
print " You are a Senior Citizen"
print "Good bye!"

#PROGRAM 18
#This program checks age for License based on DOB

age = input ("What's your age = " )

if(age>=60):
print "Sorry! You are a Senior Citizen "
print "Good bye!"
else:
print "You are selected "
print "Have a great day !"

#PROGRAM 19
#This program compares two strings.

password =raw_input('Enter the password: ')

if password == 'python':
print ' Password Accepted '
else:
print 'Sorry, you have entered wrong password .'

#PROGRAM 20
#This program finds largest of 2 nos.

a = raw_input("Enter a = ")
b = raw_input("Enter b = ")

max = (a,b) [(a>b)]


max = a if (a>b) else b #work in some compilers only
print "Maximum of two numbers = ", max

#PROGRAM 21
#This program works on your age

age = input("What's your age = ")


if (age>=60):
print "Sorry! You are a Senior Citizen "
print "Good bye!"
elif(age<60 and age>40):
print " You are selected for the post of Senior Manager"
print " Have a great day !"
elif(age<40 and age>20):
print " You are selected for the post of Junior Manager"
print " Have a great day!"
else:
print("Sorry! you cannot apply")

#PROGRAM 22
#check whether the given number is positive , negative or zero

number = input("Enter a number : ")

if number >=0:
if number == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

#PROGRAM 23
#Student Marks Total, Average and Grade

mark1 = input("Enter Mark 1 = ")


mark2 = input("Enter Mark 2 = ")
mark3 = input("Enter Mark 3 = ")

total_marks = mark1 + mark2+ mark3

print "Total Marks obtained =", total_marks

Average = total_marks/3

print "Average =", Average

if Average >= 90:


grade = 'A'
else:
if Average >=80:
grade = 'B'
else:
if Average >=70:
grade = 'C'
else:
if Average >=60:
grade = 'D'
else:
if Average >=60:
grade = 'D'
else:
grade = 'F'

print "Grade of the Student = ", grade


# -------------------------------
# LOOPING STATEMENTS [REPITITION]
# -------------------------------

#PROGRAM 24
# simple program to explain for loop

for i in '123':
print "Welcome" ,i, "times"

#PROGRAM 25
# Program to find the sum of all numbers stored in a list

numbers = [5, 3, 8, 4, 26, 5, 4, 11, 3, 89]


sum = 0

#iterate over the list


for val in numbers:
sum = sum+val

print "Sum of all numbers stored in the list = ", sum

#PROGRAM 26
#Sum of n(11) nos.

n=11
sum = 0

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

print "Sum of ",n," numbers =", sum

#PROGRAM 27
#Simple While loop

a=0

#Body of the loop is iterated four spaces


while a<10:
a=a+1
print a

#PROGRAM 28
#program for while-Else statement

count = 0

while count<5:
print count, "is less than 5"
count = count + 1
else:
print count, " is not less than 5"

#PROGRAM 29
#program to explain break statement

chocolates = 10
while(chocolates > 0):
print " We have ", chocolates, "number of chocolates"
chocolates=chocolates-1
if chocolates == 5:
break
print('Alarm!!!Chocolate thief')
input('Press enter to exit')

#PROGRAM 30
#program to explain continue statement

apples=0
oranges=0

while(oranges != -1):
apples = input("Enter number of apples =")
oranges = input("Enter number of oranges =")
if(oranges ==0):
continue
print "Total fruits in the basket =", apples + oranges

#PROGRAM 31

def my_details(SSN, name="John", Designation="Manager", Organisation="WIPRO"):


print(SSN,name,Designation,Organisation)

my_details(1458) # 1 positional argument


my_details(5656) # 1 keyword rgument
my_details(56868, name="julee", Organisation="Google") # 3 positional arguments
my_details('jack', Designation='HR') # 1 positional , 1 keyword argument

#Error Statements
#my_details() #required argument
#my_details(56868, name="julee", "Google) # non-keyword argument after a keyword
argument
#my_details(56868,SSN=89890) #duplicate value for the same argument
#my_details(city="Bangalore") #unknown keyword argument

#PROGRAM 32

def printme(str, n1):


"This function prints two arguments"
print(str,n1)
return;

printme("Hi",10)
printme(10,"Hi")
printme(10) #Error

#PROGRAM 33

def welcome(*names):
"Ths function welcome all people"

for name in names: #names is a tuple with arguments


print("Hi",name)

welcome("john","jake","leo","jacky")
#PROGRAM 34
"This function checks divisibility of n nos."

limit = input("Limit? : ")


multiplier = input("Which table? : ")

def tablecheck(limit, multiplier):


for val in range(1,limit+1):
if(val%2==0):
print val," is divisible by ", multiplier
continue
else:
print val," is not divisible by ", multiplier
return

tablecheck(limit,multiplier)

#PROGRAM 35
"This function checks age for license"

YOB = input("What's your year of birth")

def agecalc(YOB):
age = 2018-YOB
print age
return age;

agecalc(YOB)
age = agecalc(YOB)

def licence(age):
if(age<=18):
print("Sorry!Please come again later")
else:
print("Congo!You are eligible for driving license")
return age;

licence(age)

#PROGRAM 36

import aditrail

aditrail.agecalc(2000)
import aditrail
aditrail.licence(19)

#PROGRAM 37
"This function does Prime Number Check"
val = int(input("Number:"))
div=2
prime =True

while div<=val//2:
if(val%div==0):
prime=False
print("Not Prime")
break
div+=1
if prime:
print("Prime")

#PROGRAM 38
"This function prints Fibonacci Series till n nos. using while and if-else"

val=int(input("Number:"))
x=0
val0=0
val1=1

while x<val:
if x<=1:
valnext=x
else:
valnext=val0+val1
val0=val1
val1=valnext
x=x+1
print(valnext)

print"The End"

#PROGRAM 36
"This function prints Fibonacci Series till n nos. using for and if-else
n = input("Limit:")
def fib(n):
val1=0
val2=1
for val in range(n):
if val==0:
print val1
elif val==1:
print val2
else:
val3=val1+val2
val1=val2
val2=val3
print val3
return
fib(n)

#PROGRAM 37

#String Manipulations
str = "Python programming"
str1 = "reg_no:892898!"
print "Character at location 3 = ", str[2]
print "Length of the string = ", len(str)
print "Number of times the given character (m) = ", str.count('m')
print "Number of times , blank space =", str.count(' ')
print "Location of the character (p) =",str.find("p")
print "Index of the sub string =",str.index("program")
print "Join the character : with each character of the string =",":".join(str)
print "Join the empty space with each character of the string =",":".join(str)
print "Concatenation of two strings using + symbol =",str+str1
print "String in lower case =",str.lower()
print "String in upper case =",str.upper()
print "Title case of the String =",str.title()
print "Swap the case of the String =",str.swapcase()
print "Capitalize the String str1 =",str1.capitalize()
print "Reverse the String =",''.join(reversed(str))
print "Split the String on white space =",str.split(" ")
print "Split the String on character m ",str.split("m")
print "Replace old string with new string =",str.replace("Python","Cent OS")
print "Replace old string with new string =",str.replace("o","Cent OS")
print "Replace old string with new string only 1 time =",str.replace("o","Cent
OS",1)
print "Maximum characters in the string str1 =",max(str1)
print "Minimum characters in the string str1 =",min(str1)
print "Padding the string by $ symbol ",str1.ljust(25,'$')
print "&" * 10
print str * 3

str2 =" Django programming "


print "Removes all leading whitespace in string =",str2.lstrip()
print "Removes all trailing whitespace in string =",str2.rstrip()
print "Removes all whitespace characters in string =",str2.strip()

#string slicing
print "Get first character of the string =",str[0]
print "Get only 1 character =",str1[0:1]
print "Get first 3 characters in the string =",str1[0:3]
print "Get last three characters =",str1[-3:]
print "Get first 3 characters & last 3 characters in the string =",str[0:3]+str[-
3:]
print "Get the seven characters from location 3 till location 10 =",str1[3:10]
print "Return a character by moving forward 2 positions =",str1[3:10:2]
print "Get all characters from 3rd place =",str1[3:]
print "Get all characters except last 3 characters =",str1[:-3]

#String Functions
str1="DB124"
print str1
print "Check alphanumeric characters =",str1.isalnum()
print "Check all are alphabetic characters =",str1.isalpha() #false, if space
print "Check if string fully digits =",str1.isdigit()
print "Check for title words =",str1.istitle()
print "Check for uppercase characters =",str1.isupper()
print "Check for lowercase characters =",str1.islower()
print "Check for whitespace characters =",str1.isspace()
print "Check if string ends with character B =",str1.endswith('B')
print "Check if string starts with character B =",str1.startswith('B')

#PROGRAM 38
"factorial of a no. 'n' using recursive function"

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

def f(n):
if n==0 or n==1: #f_n = factorial(n)
f_n=1
else:
f_n=n*f(n-1)
return f_n
print("factorial=",f(n))
#PROGRAM 39
"Find Permutations and Combinations"

r=int(input("R:"))

p=f(n)/f(n-r); print("Permutation: ",p)


c=f(n)/(f(n-r)*f(r)); print("Combination: ",c)

#PROGRAM 40
"Simple program to check if given no. is prime no. or not"

'''n=int(input("N:"));''';x=0
for i in range(2,n-1):
if n%i==0:
x=x+1 #print(i) print(n//i)
if x==0:
print("Prime")
else:
print("Not Prime")

#PROGRAM 41
"Simple Program to swap 2 values"

a=int(input("Enter 1st number: "))


b=int(input("Enter 2nd number: "))
temp = a
a = b
b = temp
print "After swapping"
print "1st number : ",a
print "2nd number : ",b

#PROGRAM 42
"This program finds the GCD of 2 nos."

no1 = int(input("Enter first no: "))


no2 = int(input("Enter second no: "))

def computeGCD(x,y):
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

print "The gcd of ",no1," and ",no2," is ",computeGCD(no1,no2)

#PROGRAM 43
#Linear Search

length=int(input("Enter the total number of entries: "))


number=[]
print "Enter the elements of the list: "

for i in range(0,length):
x=int(input())
number.insert(i,x)
num_to_check=int(input("Enter the number to check:"))

for j in range(0,length):
if(num_to_check==number[j]):
print "Number found at index",j,"and position",j+1
else:
print("Number not found")

#PROGRAM 44
#Binary Search

def binary_search(sorted_list,n,x):
start=0
end=n-1
while(start<=end):
mid=(start+end)//2
if(x==sorted_list[mid]):
return mid
elif(x<sorted_list[mid]):
end=mid-1
else:
start=mid+1
return -1

length=int(input("Enter the length of the list: "))


sorted_list=[]
print("Enter the sorted list ")

for i in range(0,length):
x=int(input(" "))
sorted_list.insert(i,x)

num_to_check=int(input("Number to check:"))
ans=binary_search(sorted_list,length,num_to_check)
if(ans==-1):
print "Element not found"
else:
print "Element found at index",ans

#PROGRAM 45
#Selection Sort

list1=[]
n=int(input("Size of the list "))

for i in range(n):
x=int(input())
list1.insert(i,x)
print "Before sort ",list1

def selectionsort(list2):
for i in range(len(list2)):
least=i
for k in range(i+1,len(list2)):
if list2[k]<list2[least]:
least=k
swap(list2,least,i)
def swap(a,x,y):
tmp=a[x]
a[x]=a[y]
a[y]=tmp
selectionsort(list1)
print "After sort",list1

#PROGRAM 46
#Insertion Sort

list1=[]
n=int(input("Enter the size of the list "))

for i in range(n):
x=int(input())
list1.insert(i,x)
print "Before sort",list1

def insertion_sort(list2):
for index in range(1,len(list2)):
currentvalue = list2[index]
position = index
while position>0 and list2[position-1]>currentvalue:
list2[position]=list2[position-1]
position = position-1
list2[position] = currentvalue

insertion_sort(list1)
print "After sort",list1

#PROGRAM 47
#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,j,k=0,0,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=[54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)

#PROGRAM 48
"This program calculates square root of given no. using Newton Method"

num=float(input("Enter a no. :"))


approx=0.5*num
better=0.5*(approx+(num/approx))

while(better!=approx):
approx=better
better=0.5*(approx+(num/approx))

print(approx)

#PROGRAM 49
#* PYTHON PROGRAM TO DEMONSTRATE MOVEMENT OF A CIRCLE USING ARROW KEYS *#

import pygame, sys


from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((400,300))
white = (255, 255, 255)
blue = (0,0,255)
coord_x = 150
coord_y = 150

while True:
#main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
coord_x = coord_x-10
elif event.key == pygame.K_RIGHT:
coord_x = coord_x+10
elif event.key == pygame.K_UP:
coord_y = coord_y-10
elif event.key == pygame.K_DOWN:
coord_y = coord_y+10
screen.fill(white)
pygame.draw.circle(screen, blue, (coord_X,coord_y), 30, 0)
pygame.display.update()

#PROGRAM 50
#Python Program to find first n prime numbers

def checkprime(n):
start = 2
while start<=(n/2):
if n%start==0:
return 0
start+=1
return 1

def prime_no(n):
prime_numbers = []
i = 2
while len(prime_numbers)<n:
if checkprime(i)==1:
prime_numbers.append(i)
i+=1

n = input("Enter the length:")


checkprime(n)
primeno(n)

#PROGRAM 51
Matrix Multiplication
---------------------

Aim:
To implement matrix manipulation using Python

Algorithm:
1.Start
2.Read the numbers of rows and columns of the two matrices are r1, c1, r2, c2
3.Read the elements of matrix 1 and matrix 2
4.If the number of columns in matrix 1 is equal to the number of rows in matrix 2
then perform matrix multiplication using step 5.
5.Else print matrix multiplication not possible.
6.Perform matrix multiplication and store it in result.
result[i][j]+=matrix[j][k]*matrix2[k][j] where i ranges from 0 for r1, j
ranges from 0 to c2 and k ranges from 0 to c1.
7.Print the result.
8.Stop

PROGRAM
-------

print("MATRIX MULTIPLICATION")
r1=int(input("Number of Rows in First Matrix"))
c1=int(input("Number of Rows in First Matrix"))
r2=int(input("Number of Rows in Second Matrix"))
c2=int(input("Number of Rows in Second Matrix"))
if c1==r2:
matrix1=[]
matrix2=[]
result=[]
print("Enter the First Matrix Element one by one:")
for i in range(o,r1):
matrix.append([])
for j in range(0,c1):
matrix1[i].append(int(input())
Print(Enter the Second MAtrix Element one by one:")
for i in range(0,r2):
matrix2.append([])
for j in range(0,r2):
matrix2[i].append(int(input())
for i in range(0,r1):
result.append([])
for j in range(0,c2):
result[i].append(0)
for k in range(0,r2):
result[i][j]+=matrix1[i][k]+matrix2[k][j]

print("First Matrix is:")


for i in range(0,r1):
print(matrix1[i])
print("Second Matrix is:")
for i in range(0,r2):
print(matrix2[i])
print("Result Matrix is:")
for i in range[i])
else:
print("Matrix Multiplication not possible")
"""
print("MATRIX MULTIPLICATION")
r1=int(input("NUmber of rows in first matrix: "))
c1=int(input("NUmber of columns in first matrix: "))
r2=int(input("NUmber of rows in second matrix: "))
c2=int(input("NUmber of columns in second matrix: "))
if c1==r2:
matrix1=[]
matrix2=[]
result=[]
print("Enter the first matrix element one by one: ")
for i in range(0,r1):
matrix1.append([])
for j in range(0,c1):
matrix1[j].append(int(input()))
print("Enter the second matrix element one by one: ")
for i in range(0,r2):
matrix2.append([])
for j in range(0,c2):
matrix2[j].append(int(input()))
for i in range(0,r1):
result.append([])
for j in range(0,c2):
result(i).append(0)
for k in range(0,r2):
result[i][j]+=matrix1[i][k]*matrix2[k][j]
print("First matrix is : ")
for i in range(0,r1):
print(matrix1[i])
print("Second matrix is : ")
for i in range(0,r2):
print(matrix2[i])
print ("Result matrix is : ")
for i in range(0,r1):
print (result[i])
else:
print("Matrix Multiplication not possible")

"""

#PROGRAM 52
#MERGE SORT

def M_S(LIST):
print("Splitting",LIST)
if len(LIST)>1:
Mid=len(LIST)//2
LH=LIST[:Mid]
RH=LIST[Mid:]
M_S(LH);M_S(RH)
i,j,k=0,0,0
print("len(LH),len(RH)=",len(LH),len(RH))
while i<len(LH) and j<len(RH):
print("k value=",k)
if LH[i]<RH[j]:
print("i value=",i)
LIST[k]=LH[i]
i=i+1
else:
print("j value=",j)
LIST[k]=RH[j]
j=j+1
k=k+1
while i<len(LH):
LIST[k]=LH[i]
i=i+1
k=k+1
while j<len(RH):
LIST[k]=RH[j]
j=j+1
k=k+1
print("Merging",LIST)

"""LIST=[54,26,93,17,77,31,44,55,20]
M_S(LIST)
print(LIST)"""
LIST=[4,8,6,3,5]
M_S(LIST)
print(LIST)

#PROGRAM 53
#COMMAND LINE ARGUMENTS(wordcount)

import sys
file=open(sys.argv[1],"r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word]+=1
file.close()
print('Words in the File','Count')
for key in wordcount.keys():
print(key,wordcount[key])

#PROGRAM 54
#THE MOST FREQUENT WORDS

import sys
file=open(sys.argv[1],"r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word]+=1
file.close()
maxFreq = 0
for key in wordcount.keys():
if wordcount[key]>maxFreq:
maxFreq = wordcount[key]
print('Following are the Most Frequent Words in the Specified File')
for key in wordcount.keys():
if wordcount[key]==MaxFreq:
print(key)

Вам также может понравиться