0% found this document useful (0 votes)
29 views9 pages

Pratham FDS

object orient
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views9 pages

Pratham FDS

object orient
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

PR:-2

Title:- Write a Python program to compute following operations on String:


a) To display word with the longest length
b) To determines the frequency of occurrence of particular character in the string
c) To check given string is palindrome or not
d) To display index of first substring
e) To count the occurrences of each word in string
Code:-
text = input("Enter a string: ")

longest = max(text.split(), key=len)


print("Longest Word:", longest)

char = input("Enter a character to find its frequency: ")


print(f"Frequency of '{char}':", text.count(char))

cleaned_text = text.replace(" ", "").lower()


print("Is Palindrome:", cleaned_text == cleaned_text[::-1])

substring = input("Enter a substring to find its first occurrence: ")


print(f"Index of first occurrence of '{substring}':", text.find(substring))

word_counts = {}
for word in text.split():
word_counts[word] = word_counts.get(word, 0) + 1
print("Word Count:",word_counts)

Output
Enter a string: Pranav
Longest Word: Pranav
Enter a character to find its frequency: 1
Frequency of '1': 0
Is Palindrome: False
Enter a substring to find its first occurrence: praval10
Index of first occurrence of 'pranav': -1
Word Count: {'Pranav': 1}
PR:-1
Title:- Write a Python program to store marks scored in subject “Fundamental of Data
Structure” by N students in the class. Write functions to compute following:
a) The average score of class
b) Highest score and lowest score of class
c) Count of students who were absent for the test
d) Display mark with highest frequency
Code:-
num_students = int(input("Enter the number of students: "))
marklist = []
print("Enter the marks scored by each student (use 'None' for absent students):")
for i in range(num_students):
mark = input(f"Student {i + 1} mark: ")

if mark.lower() == "none":
marklist.append(None)
else:
try:
marklist.append(int(mark))
except ValueError:
print(f"Invalid input for student {i + 1}. Please enter a valid number or 'None'.")
marklist.append(None)

avg = 0
absent = 0
present_marks = []
total = 0

for mark in marklist:


if mark is None:
absent += 1
else:
present_marks.append(mark)

if present_marks:
total = sum(present_marks)
avg = total / len(present_marks)
print("The average score of class:", avg)
print("Highest score and lowest score of class: Max =", max(present_marks), "Min =",
min(present_marks))
else:
print("No students were present for the test.")
print("Count of students who were absent for the test:", absent)

freq = {}
for mark in present_marks:
if mark in freq:
freq[mark] += 1
else:
freq[mark] = 1

if freq:
highest_freq_mark = max(freq, key=freq.get)
highest_freq_count = freq[highest_freq_mark]
print("Marks with the highest frequency are:", highest_freq_mark, "with a frequency
of:", highest_freq_count)
else:
print("No marks available to calculate frequency.")

Output:-
Enter the number of students: 5
Enter the marks scored by each student (use 'None' for absent students):
Student 1 mark: 80
Student 2 mark: 78
Student 3 mark: 98
Student 4 mark: 65
Student 5 mark: 84
The average score of class: 84
Highest score and lowest score of class: Max = 98 Min = 65
Marks with the highest frequency are: 78 with a frequency of: 1
PR:-3
Title:- Write a Python program to compute following computation on matrix:
a)Addition of two matrices
b) Subtraction of two matrices
c) Multiplication of two matrices
d) Transpose of a matrix
Code:-
row = int(input("Enter the row count: "))
col = int(input("Enter the column count: "))

mat1 = [[0 for i in range(col)] for i in range(row)]


mat2 = [[0 for i in range(col)] for i in range(row)]

# Input matrices
print("Enter data for matrix 1:")
for i in range(row):
for j in range(col):
mat1[i][j] = int(input(f"Enter value for row {i + 1} and col {j + 1}: "))

print("Enter data for matrix 2:")


for i in range(row):
for j in range(col):
mat2[i][j] = int(input(f"Enter value for row {i + 1} and col {j + 1}: "))

def display_matrix(matrix, matrix_name):


print(f"\n{matrix_name}:")
for row in matrix:
print(" ".join(f"{value:5}" for value in row))

display_matrix(mat1, "Matrix 1")


display_matrix(mat2, "Matrix 2")

addition_result = [[mat1[i][j] + mat2[i][j] for j in range(col)] for i in range(row)]


print("\nAddition:")
display_matrix(addition_result, "Addition Result")

subtraction_result = [[mat1[i][j] - mat2[i][j] for j in range(col)] for i in range(row)]


print("\nSubtraction:")
display_matrix(subtraction_result, "Subtraction Result")

transpose_result = [[mat1[j][i] for j in range(row)] for i in range(col)]


print("\nTranspose of Matrix 1:")
display_matrix(transpose_result, "Transpose Result")

if len(mat1[0]) == len(mat2):
multiplication_result = [[0 for _ in range(len(mat2[0]))] for _ in range(len(mat1))]
for i in range(row):
for j in range(len(mat2[0])):
for k in range(col):
multiplication_result[i][j] += mat1[i][k] * mat2[k][j]
print("\nMultiplication:")
display_matrix(multiplication_result, "Multiplication Result")
else:
print("\nMultiplication not possible due to incompatible dimensions.")

Output:-

Enter the row count: 2


Enter the column count: 2
Enter data for matrix 1:
Enter value for row 1 and col 1: 2
Enter value for row 1 and col 2: 5
Enter value for row 2 and col 1: 9
Enter value for row 2 and col 2: 7
Enter data for matrix 2:
Enter value for row 1 and col 1: 5
Enter value for row 1 and col 2: 4
Enter value for row 2 and col 1: 6
Enter value for row 2 and col 2: 8

Matrix 1:
2 5
9 7

Matrix 2:
5 4
6 8

Addition:

Addition Result:
7 9
15 15

Subtraction:

Subtraction Result:
-3 1
3 -1

Transpose of Matrix 1:

Transpose Result:
2 9
5 7

Multiplication:

Multiplication Result:
40 48
87 92
PR:-4
Title:- Write a Python program to store first year percentage of students in array. Write
function for sorting array of floating point numbers in ascending order using
a)SelectionSort
b) Bubble sort and display top five scores
Code:-
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]

def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]

def top_five_scores(arr):
return arr[-5:][::-1]

n = int(input("Enter the number of students: "))


percentages = [float(input(f"Enter percentage of student {i + 1}: ")) for i in range(n)]

selection_sorted = percentages[:]
selection_sort(selection_sorted)
print("\nSorted by Selection Sort:", selection_sorted)
print("Top 5 Scores (Selection Sort):", top_five_scores(selection_sorted))

bubble_sorted = percentages[:]
bubble_sort(bubble_sorted)
print("\nSorted by Bubble Sort:", bubble_sorted)
print("Top 5 Scores (Bubble Sort):", top_five_scores(bubble_sorted))

Output:-
Enter the number of students: 5
Enter percentage of student 1: 45
Enter percentage of student 2: 89
Enter percentage of student 3: 98
Enter percentage of student 4: 85
Enter percentage of student 5: 84

Sorted by Selection Sort: [45.0, 84.0, 85.0, 89.0, 98.0]


Top 5 Scores (Selection Sort): [98.0, 89.0, 85.0, 84.0, 45.0]

Sorted by Bubble Sort: [45.0, 84.0, 85.0, 89.0, 98.0]


Top 5 Scores (Bubble Sort): [98.0, 89.0, 85.0, 84.0, 45.0]
PR:-5
Title:- Write a Python program to store second year percentage of students in array.
Write function for sorting array of floating point numbers in ascending order using a)
Insertion sort b) Shell Sort and display top five scores
Code:-
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j = j- 1
arr[j + 1] = key

def shell_sort(arr):
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j=i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
arr[j] = temp
gap //= 2

def top_five_scores(arr):
return arr[-5:][::-1]

n = int(input("Enter the number of students: "))


percentages = [float(input(f"Enter percentage of student {i + 1}: ")) for i in range(n)]

insertion_sorted = percentages[:]
insertion_sort(insertion_sorted)
print("\nSorted by Insertion Sort:", insertion_sorted)
print("Top 5 Scores (Insertion Sort):", top_five_scores(insertion_sorted))

shell_sorted = percentages[:]
shell_sort(shell_sorted)
print("\nSorted by Shell Sort:", shell_sorted)
print("Top 5 Scores (Shell Sort):", top_five_scores(shell_sorted))

Output:-
Enter the number of students: 5
Enter percentage of student 1: 89
Enter percentage of student 2: 87
Enter percentage of student 3: 85
Enter percentage of student 4: 77
Enter percentage of student 5: 76

Sorted by Insertion Sort: [76.0, 77.0, 85.0, 87.0, 89.0]


Top 5 Scores (Insertion Sort): [89.0, 87.0, 85.0, 77.0, 76.0]

Sorted by Shell Sort: [76.0, 77.0, 85.0, 87.0, 89.0]


Top 5 Scores (Shell Sort): [89.0, 87.0, 85.0, 77.0, 76.0]
PR:-6
Title:- Write a Python program to store first year percentage of students in array. Write
function for sorting array of floating point numbers in ascending order using quick sort
and display top five scores.
Code:-
def partition(per, lo, hi):
if lo < hi:
pivot = lo
i = lo
j = hi
while i < j:
while per[j] <= per[pivot] and i < hi:
i=i+1
while per[j] > per[pivot]:
j=j-1
if i < j:
temp = per[i]
per[i] = per[j]
per[j] = temp
temp = per[pivot]
per[pivot] = per[j]
per[j] = temp
return j

def quicksort(per, lo, hi):


if lo < hi:
pi = partition(per, lo, hi)
quicksort(per, lo, pi - 1)
quicksort(per, pi + 1, hi)

per = []
n = int(input("Enter the number of students: "))
for i in range(n):
m = float(input("Enter the student %i percentage: " % (i + 1)))
per.append(m)

quicksort(per, 0, n - 1)

print("Sorted array is: ")


for i in range(n):
print("%0.1f" % per[i])

print("Top 5 scores are: ")


for i in range(min(5, n)):
print("%0.1f" %per[n-i-1])

Output:-
Enter the number of students: 5
Enter the student 1 percentage: 98
Enter the student 2 percentage: 78
Enter the student 3 percentage: 65
Enter the student 4 percentage: 87
Enter the student 5 percentage: 75
Sorted array is:
65.0
75.0
78.0
87.0
98.0
Top 5 scores are:
98.0
87.0
78.0
75.0
65.0

You might also like