Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Python Lab Programs

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


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

num2 = int(input("Enter 2nd number: "))

i=1

while(i <= num1 and i <= num2):

if(num1 % i == 0 and num2 % i == 0):

gcd = i

i=i+1

print("GCD is", gcd)

2. To write a Python Program to find the square root of a number


by Newton’s Method.
def newton_method(number, number_iters = 100):

    a = float(number) 

    for i in range(number_iters): 
        number = 0.5 * (number + a / number) 
    return number

3. To write a Python program to find the exponentiation of a number.


base = 7

exponent = 9

print "Exponential Value is: ", base ** exponent
4. To write a Python Program to find the maximum from a list of
numbers.
list1 = [9,1,32,76,2,65,12]

print("Largest element is:", max(list1))

5. To write a Python Program to perform Linear Search


def linearsearch(arr, x):

   for i in range(len(arr)):

      if arr[i] == x:

         return i

   return -1

arr = ['p','u','s,'o','l','i','n','m']

x = 'a'

print("element found at index "+str(linearsearch(arr,x)))

6. To write a Python program for binary search


def binary_search(alist, key):

"""Search key in alist[start... end - 1]."""

start = 0

end = len(alist)

while start < end:

mid = (start + end)//2

if alist[mid] > key:


end = mid

elif alist[mid] < key:

start = mid + 1

else:

return mid

return -1

 alist = input('Enter the sorted list of numbers: ')

alist = alist.split()

alist = [int(x) for x in alist]

key = int(input('The number to search for: '))

index = binary_search(alist, key)

if index < 0:

print('{} was not found.'.format(key))

else:

print('{} was found at index {}.'.format(key, index))

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

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

for i in range(len(A)):

min_idx = i

for j in range(i+1, len(A)):

if A[min_idx] > A[j]:


min_idx = j

A[i], A[min_idx] = A[min_idx], A[i]

print ("Sorted array")

for i in range(len(A)):

print("%d" %A[i]),

8. To write a Python Program to perform insertion sort.


def insertionSort(arr):

for i in range(1, len(arr)):

key = arr[i]

j = i-1

while j >=0 and key < arr[j] :

arr[j+1] = arr[j]

j -= 1

arr[j+1] = key

arr = [12, 11, 13, 5, 6]

insertionSort(arr)

print ("Sorted array is:")

for i in range(len(arr)):

print ("%d" %arr[i])


9. To write a Python Program to perform Merge sort.
def merge(arr, l, m, r):

n1 = m - l + 1

n2 = r- m

L = [0] * (n1)

R = [0] * (n2)

for i in range(0 , n1):

L[i] = arr[l + i]

for j in range(0 , n2):

R[j] = arr[m + 1 + j]

i=0 # Initial index of first subarray

j=0 # Initial index of second subarray

k=l # Initial index of merged subarray

while i < n1 and j < n2 :

if L[i] <= R[j]:

arr[k] = L[i]

i += 1

else:

arr[k] = R[j]

j += 1

k += 1

while i < n1:

arr[k] = L[i]
i += 1

k += 1

while j < n2:

arr[k] = R[j]

j += 1

k += 1

def mergeSort(arr,l,r):

if l < r:

m = (l+(r-1))//2

mergeSort(arr, l, m)

mergeSort(arr, m+1, r)

merge(arr, l, m, r)

arr = [21, 19, 13, 5, 6, 7]

n = len(arr)

print ("Given array is")

for i in range(n):

print ("%d" %arr[i]),

mergeSort(arr,0,n-1)

print ("\n\nSorted array is")

for i in range(n):

print ("%d" %arr[i])


10. To write a Python program to find first n prime numbers
def print_primes_till_N(N):

i, j, flag = 0, 0, 0;

print("Prime numbers between 1 and ", N , " are:");

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

if (i == 1 or i == 0):

continue;

flag = 1;

for j in range(2, ((i // 2) + 1), 1):

if (i % j == 0):

flag = 0;

break;

if (flag == 1):

print(i);

N = 100;

print_primes_till_N(N);

11. To write a Python program to multiply matrices.


A = [[1, 7, 3],

[4, 5, 6],

[7, 8, 9]]

B = [[5, 8, 1],
[6, 7, 3],

[4, 5, 9]]

result = [[0, 0, 0],

[0, 0, 0],

[0, 0, 0]]

# iterating by row of A

for i in range(len(A)):

# iterating by coloum by B

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

# iterating by rows of B

for k in range(len(B)):

result[i][j] += A[i][k] * B[k][j]

for r in result:

print(r)

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

# python3 filename.py 1 2 3 4
import sys
 
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
 
# Arguments passed
print("\nName of Python script:", sys.argv[0])
 
print("\nArguments passed:", end = " ")
for i in range(1, n):
    print(sys.argv[i], end = " ")
Sum = 0
for i in range(1, n):
    Sum += int(sys.argv[i])     
print("\n\nResult:", Sum)

# Result=10

13. To write a Python program to find the most frequent words in a text
read from a file.
fname=input("enter file name: ")
count=0 #count of a specific word
maxcount=0 #maximum among the count of each words
l=[] #list to store the words with maximum count

with open(fname,'r') as f:
contents=f.read()
words=contents.split()
for i in range(len(words)):
for j in range(i,len(words)):
if(words[i]==words[j]): #finding count of each word
count+=1
if(count==maxcount): #comparing with maximum count
l.append(words[i])
elif(count>maxcount): #if count greater than maxcount
l.clear()
l.append(words[i])
maxcount=count
else:
l=l
count=0
print(l)
14. Reshaping 5*10 array into a 2*10 array
import numpy as np

a=np.array([[1,2,3,4],[2,3,4,5],[7,6,5,8],[2,4,6,1,],[7,3,9,6]])

print(a)

new_a=a.reshape(2,10)

print("new array:-")

print(new_a)

15. Flattening a 5*3 array


import numpy as np

a=np.array([[1,2,3],[2,3,4],[7,6,5],[2,4,6,],[7,3,9]])

print(a)

new_a=a.flatten()

print("new array:-")

print(new_a)

16. Split 6*8 array into 2 arrays


import numpy as np

a=np.array([[1,2,3,4,5,6,7,8],[2,3,4,4,5,6,7,8],[7,6,5,4,5,6,7,8],[2,4,6,4,5,6,7,8],[7,3,9,4,5,6,7,8],[
7,3,9,4,5,6,7,8]])

print(a)

new_a=np.split(a,2)

print("new array:-")

print(new_a)
17. Sorting dataframe in ascending
import pandas as pd

df = pd.DataFrame({

'col1': ['A', 'A', 'B', 'F', 'D', 'C'],

'col2': [2, 1, 9, 8, 7, 4],

'col3': [0, 1, 9, 4, 2, 3],

'col4': ['a', 'B', 'c', 'D', 'e', 'F']

})

print(df)

df.sort_values(by=['col1'])

print(df)

18. Finding max in dataframe


import pandas as pd

df = pd.DataFrame({

'col1': ['A', 'A', 'B', 'F', 'D', 'C'],

'col2': [2, 1, 9, 8, 7, 4],

'col3': [0, 1, 9, 4, 2, 3],

'col4': ['a', 'B', 'c', 'D', 'e', 'F']

})

print(df.max())
19. Finding min value in a dataframe
import pandas as pd

df = pd.DataFrame({

'col1': ['A', 'A', 'B', 'F', 'D', 'C'],

'col2': [2, 1, 9, 8, 7, 4],

'col3': [0, 1, 9, 4, 2, 3],

'col4': ['a', 'B', 'c', 'D', 'e', 'F']

})

print(df.min())

You might also like