Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

1.

Write a Python program to find String palindrome

Program:
a=input("Enter a string:")b=a.lower()
c=b[::-1]
if b==c:
print(a,"is a palindrome")else:
print(a,"is not a palindrome")

Output:
Enter a string: madam
Madam is a palindrome

2. Write a Python program to perform linear search using list


Program:
def linear(lst,sval):
for i in range(len(lst)):
if lst[i]==sval:
return(i)
return -1
n=int(input("Enter no. of elements:"))
l=[]
for i in range(n):
val=int(input("enter value:"))
l.append(val)
print(l)
searchval= int(input("enter value to be searched:"))
a=linear(l,searchval)
if a==-1:
print("Element not found")
else:
print("Element found at index",a)
Output:

Enter no. of elements:5


entervalue:23
enter value:45
enter value:67
enter value:89
enter value:100
[23,45,67,89,100]
enter value to be searched:67
Element found at index 2

3. Write a Python program to perform binary search using list


Program:
def binsearch(lst,sval):
low,high=0,(len(lst)-1)
while (low<high):
mid=(low+high)//2
if lst[mid]<sval:
low=mid+1
elif lst[mid]>sval:
high=mid-1
else:
return(mid)
return -1
n=int(input("Enter the no of elements in list:"))
l =[]
for i in range(n):
ele=int(input("Enter the list elements:"))
l.append(ele)
x = int(input("Enter the element to search:"))
a=binsearch(l,x)
if a==-1:
print("Element not found")
else:
print("Element found at index",a)
Output:
Enter the no of elements in list:5
Enter the list elements:2
Enter the list elements:3
Enter the list elements:4
Enter the list elements:5
Enter the list elements:6
Enter the element to search:8
Element not found

4. Implement python script to


i. Add matrices
ii. Multiply matrices
iii. Find Transpose of a matrix

#i) MATRIX MULTIPLICATION

A=[[1,2,3],[1,2,3],[1,2,3]]
B=[[2,3,1],[2,3,1],[2,3,1]]
C=[[0,0,0],[0,0,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]
for r in C:
print(r)
Output :
[12, 18, 6]
[12, 18, 6]
[12, 18, 6]

#ii) MATRIX ADDITION

A=[[3,3,3],[2,2,2],[1,1,1]]
B=[[1,1,1],[2,2,2],[3,3,3]]
C=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(A)):
for j in range(len(A[0])):
C[i][j]=A[i][j]+B[i][j]
for r in C:
print(r)
Output :
[4, 4, 4]
[4, 4, 4]
[4, 4, 4]

#iii) TRANSPOSE OF MATRIX

A=[[1,2,3],[4,5,6]]
B=[[0,0],[0,0],[0,0]]
for i in range(len(A)):
for j in range(len(A[0])):
B[j][i] = A[i][j]
for r in B:
print(r)

Output :

[1, 4]

[2, 5]

[3, 6]

5. Write a Python Program to perform list intersection .


list1=[2,8,4,5]
list2=[4,7,8,9]
list_intersection = list(set(list1) ^ set(list2))
print("Intersection of {} and {} is : {}".format(list1, list2, list_intersection))
Output:

Intersection of [2, 8, 4, 5] and [4, 7, 8, 9] is : [2, 5, 7, 9]

6. Write a function called is_anagram that takes two strings and returns True if they are anagrams.

def is_anagram(s1,s2):
s1=sorted(s1)
s2=sorted(s2)
if(s1==s2):
return True
else:
return False
a=input("enter 1st string:")
b=input("enter 2nd string:")
print("Is Anagram:",is_anagram(a.lower(),b.lower()))

Output:

enter 1st string:Ajax


enter 2nd string:Jaxa
Is Anagram: True

7. Write a function deleteChar() which takes two parameters one is a string and other is a
character. The function should create a new string after deleting all occurrences of the character from
the string and return the new string.

def delchar(string,char):
str=" "
for i in string:
if i==char:
str=string.replace(i, '')
return str
a=input("enter string:")
b=input("enter char to be deleted:")
print("the string:", delchar(a, b))

Output :
enter string:abcdxyzd
enter char to be deleted:d
the string: abcxyz
8. Write a Python program to count Uppercase, Lowercase, special character and numeric
values in a given string.
v='Shop open@3pm'
s=v.replace(" ","")
a,b,c,d=0
for i in s:
if i.isdigit()==True:
a+=1
elif i.isupper()==True:
b+=1
elif i.islower()==True:
c+=1
else:
d+=1
print('digit values:',a)
print('uppercase letters:',b)
print('lower case letters:',c)
print('special char:',d)

Output:
digit values: 1
uppercase letters: 1
lower case letters: 9
special charc: 1

9. Count no. of vowels and consonants in stringProgram:

str=input("Enter string:")
str1="".join(str.split())
vowel="aeiou"
vcount=0
ccount=0
for i in str1:
if i.lower() in vowel:
vcount+=1
else:
ccount+=1
print("No. of vowels in string ",str ,vcount)
print("No. of consonents in string ",str ,ccount)
Output
Enter string:python program
No. of vowels in string python program 3
No. of consonents in string p ython program 10

10.Python program for implementation of Selection sort

Working of selection sort:

1. Partition the list into sorted and unsorted sections. The sorted section is initially emptywhile the
unsorted section contains the entire list
2. Set the first element of the unsorted array as minimum element
3. Compare the minimum element with the second element of unsorted array. If thesecond
element is smaller than the first, we assign it as a minimum element.
4. Again compare the second element to the third and if the third element is smaller thansecond,
assign it as minimum. Repeat the process until the last element of unsorted array is reached. Thus
find the minimum value from unsorted array
5. Swap the minimum value with the first element of the unsorted array
6. Repeat steps 2 to 5 until we get the sorted array.
Program:
def selectionsort(A):
for i in range(len(A)): # Traverse all array elements min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]: # Find min
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i] # Swap
A = [12, 10, 16, 11, 9, 7]
selectionsort(A)
print ("Sorted array", A)

Output:
Sorted array [7,9,10,11,12,16]

11.Python program for implementation of Insertion Sort

Steps for Insertion sort:

Step 1 − Consider first element as already sorted.Step 2


− Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than thevalue to be
sorted
Step 5 − Insert the value to be sorted in the correct position in sorted sub-listStep 6 −
Repeat from step 2 until list is sorted
Program:
def insertion_sort(x):
for i in range(1,len(x)): # Traverse through 1 to len(x)loc=i
temp=x[loc]
while (loc>0) and x[loc-1]>temp:
x[loc]=x[loc-1] # Shift elements to the rightloc=loc-1
x[loc]=tempreturn
x

a=[42,33,19,55,16]
print(“Sorted array is: “, insertion_sort(a))

Output:
Sorted array is : [16,19,33,42,55]

12.Python program for implementation of merge Sort


Steps for merge sort:

1. Split the unsorted list until it contains single element in the sublist
2. Compare each of the element and group them as sorted
3. Repeat step 2 until whole list is merged and sorted
Program:

def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)

#merging left half and right half into a single sorted list
i=j=k=0
while i<len(lefthalf) and j <len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
k=k+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
while i<len(lefthalf):
nlist[k]=lefthalf[i]
i=i+1
k=k+1
while j <len(righthalf):
nlist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",nlist)
nlist = [14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist)
Output:
Splitting [14, 46, 43, 27, 57, 41, 45, 21, 70]
Splitting [14, 46, 43, 27]
Splitting [14, 46]
Splitting [14]
Splitting [46]
Merging [14, 46]
Splitting [43, 27]
Splitting [43]
Splitting [27]
Merging [27, 43]
Merging [14, 27, 43, 46]
Splitting [57, 41, 45, 21, 70]
Splitting [57, 41]
Splitting [57]
Splitting [41]
Merging [41, 57]
Splitting [45, 21, 70]
Splitting [45]
Splitting [21, 70]
Splitting [21]
Splitting [70]
Merging [21, 70]
Merging [21, 45, 70]
Merging [21, 41, 45, 57, 70]
Merging [14, 21, 27, 41, 43, 45, 46, 57, 70]
[14, 21, 27, 41, 43, 45, 46, 57, 70]

13.How to plot a histogram chart in Python

Histogram is an accurate method for the graphical representation of numerical data


distribution. It is a type of bar plot where X-axis represents the bin ranges while Y-axis gives
information about frequency.

from matplotlib import pyplot as plt


percentage=[97,54,45,10,20,10,30,97,50,71,40,49,40,74,95,80,65,82,70,65,55,70,75,
60,52,44,43,42,45]
binrange = [0,20,40,60,80,100]
plt.hist(percentage, bins=binrange, histtype='bar', rwidth=0.8)
plt.xlabel('percentage')
plt.ylabel('No.of students')
plt.title('Histogram')
plt.show()

Output:
14.Write a python program to plot a line graph

import matplotlib.pyplot as plt


Year = [1920,1930,1940,1950,1960,1970,1980,1990,2000,2010]
Unemployment_Rate = [9.8,12,8,7.2,6.9,7,6.5,6.2,5.5,6.3]
plt.plot(Year, Unemployment_Rate) plt.title('Unemployment
Rate Vs Year')plt.xlabel('Year')
plt.ylabel('Unemployment Rate')
plt.show()

Output
15.Write a Python program to compute element-wise sum of given tuples.

x = (1,2,3,4)
y = (3,5,2,1)
z = (2,2,3,1)
print("Original lists:")print(x)
print(y)
print(z)
print("\nElement-wise sum of the said tuples:")result = tuple(map(sum, zip(x, y, z)))
print(result)

Output:
Original lists:
(1, 2, 3, 4)
(3, 5, 2, 1)
(2, 2, 3, 1)
Element-wise sum of the said tuples:
(6, 9, 8, 6)

16.Write a Python program to count the occurrences of letter in a string usingdictionaries.


Program:

def lettercount(str):d={}
str=str.lower() str="".join(str.split())

for i in str:
if i in d:
d[i]=d[i]+1else:
d[i]=1
return d

print(lettercount("python prog"))

Output:

{'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 1, 'r': 1, 'g': 1}

17.Write a recursive Python function that recursively computes sum of elementsin a list of lists.
Program:

def lsum(l):

sum=0
for i in l:
if type(i)== list:
sum=sum+lsum(i)
else:
sum=sum+i
return sum
lst=[1,2,[3,4],[5,6,7],8]
print(lsum(lst))

Output:
36

You might also like