0% found this document useful (0 votes)
8 views28 pages

Python Programs for Grades, Arrays, and Searches

The document contains a series of practical programming tasks in Python, including functions for finding student grades, counting digits, inserting and deleting elements in an array, reversing digits, finding prime numbers, matrix multiplication, and loan eligibility checks. It also includes user input handling and examples of linear and binary search algorithms. Each task is accompanied by code snippets and expected outputs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views28 pages

Python Programs for Grades, Arrays, and Searches

The document contains a series of practical programming tasks in Python, including functions for finding student grades, counting digits, inserting and deleting elements in an array, reversing digits, finding prime numbers, matrix multiplication, and loan eligibility checks. It also includes user input handling and examples of linear and binary search algorithms. Each task is accompanied by code snippets and expected outputs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Practical No.

1
1. Write a program to

a. Find the grade of student, based on the given marks from 0 to 100.(0-39 ‘F’, 40-49 ‘D’, etc.…)

def find_grade(marks):

if marks < 0 or marks > 100:

return "Invalid marks! Please enter a number between 0 and 100."

elif marks >= 90:

return "A"

elif marks >= 80:

return "B"

elif marks >= 70:

return "C"

elif marks >= 60:

return "D"

elif marks >= 40:

return "E"

else:

return "F"

try:

marks = float(input("Enter the marks (0-100): "))

grade = find_grade(marks)

print(f"The grade is: {grade}")

except ValueError:

print("Invalid input! Please enter a numeric value.")

output:

Enter the marks (0-100): 60


The grade is: D
The grade is: D
b. Find the number of digits in the given number (should also work for negative numbers)

d ef count_digits(num):

num = abs(num)

return len(str(num))

number = -12345
print("Number of digits:", count_digits(number))

output:

Number of digits: 5

2. Write a menu driven python program to insert and delete an element at a specific position in an
array.

def display_menu():
print("\nMenu:")
print("1. Insert an element")
print("2. Delete an element")
print("3. Display the array")
print("4. Exit")

def insert_element(arr, element, position):


if position < 0 or position > len(arr):
print("Invalid position! Position must be between 0 and", len(arr))
else:
[Link](position, element)
print(f"Element {element} inserted at position {position}.")

def delete_element(arr, position):


if position < 0 or position >= len(arr):
print("Invalid position! Position must be between 0 and", len(arr) - 1)
else:
removed_element = [Link](position)
print(f"Element {removed_element} deleted from position {position}.")

def main():
arr = [] # Initial empty array

while True:
display_menu()
try:
choice = int(input("Enter your choice: "))
except ValueError:
print("Invalid input! Please enter a number.")
continue

if choice == 1:
try:
element = int(input("Enter the element to insert: "))
position = int(input("Enter the position to insert at: "))
insert_element(arr, element, position)
except ValueError:
print("Invalid input! Please enter valid numbers.")

elif choice == 2:
try:
position = int(input("Enter the position to delete from: "))
delete_element(arr, position)
except ValueError:
print("Invalid input! Please enter a valid number.")

elif choice == 3:
print("Current array:", arr)

elif choice == 4:
print("Exiting the program. Goodbye!")
break

else:
print("Invalid choice! Please select a valid option.")

# Run the program


if __name__ == "__main__":
main()

Output:

Menu:
1. Insert an element
2. Delete an element
3. Display the array
4. Exit
Enter your choice: 1
Enter the element to insert: 5
Enter the position to insert at: 0
Element 5 inserted at position 0.

Menu:
1. Insert an element
2. Delete an element
3. Display the array
4. Exit
Enter your choice: 3
Current array: [5]

Menu:
1. Insert an element
2. Delete an element
3. Display the array
4. Exit
Enter your choice: 2
Enter the position to delete from: 0
Element 5 deleted from position 0.
Practical No. 2
1. Write a program to
a. Reverse the Digits in the given number (should also work for negative numbers)

def reverse_digits(num):
# Convert the number to a string, reverse the digits, and handle the sign
if num < 0:
reversed_num = int("-" + str(abs(num))[::-1])
else:
reversed_num = int(str(num)[::-1])
return reversed_num

# Example usage
number = -12345
print("Original number:", number)
print("Reversed number:", reverse_digits(number))

output:

For number = -12345, the output will be:

Original number: -12345


Reversed number: -54321

For number = 67890, the output will be:

Original number: 67890


Reversed number: 9876
b. Find all prime numbers less than the entered number

def find_primes_less_than(n):
if n < 2:
return [] # No primes less than 2

primes = []
for num in range(2, n):
is_prime = True
for i in range(2, int(num ** 0.5) + 1): # Check divisors up to the square root
if num % i == 0:
is_prime = False
break
if is_prime:
[Link](num)
return primes

# Example usage
try:
number = int(input("Enter a number: "))
if number < 0:
print("Please enter a non-negative number.")
else:
primes = find_primes_less_than(number)
print(f"Prime numbers less than {number}: {primes}")
except ValueError:
print("Invalid input! Please enter a valid integer.")

output:

Enter a number: 10
Prime numbers less than 10: [2, 3, 5, 7]

2. WPP to multiply two matrices uses a traditional method (don’t use standard library function).

def matrix_multiplication(matrix1, matrix2):


# Get dimensions of the matrices
rows_matrix1 = len(matrix1)
cols_matrix1 = len(matrix1[0])
rows_matrix2 = len(matrix2)
cols_matrix2 = len(matrix2[0])

# Check if matrices can be multiplied


if cols_matrix1 != rows_matrix2:
raise ValueError("Matrix multiplication not possible. Columns of matrix1 must equal rows of matrix2.")

# Initialize the result matrix with zeros


result = [[0 for _ in range(cols_matrix2)] for _ in range(rows_matrix1)]

# Perform multiplication
for i in range(rows_matrix1):
for j in range(cols_matrix2):
for k in range(cols_matrix1): # or rows_matrix2 (same value)
result[i][j] += matrix1[i][k] * matrix2[k][j]

return result
# Example usage
if __name__ == "__main__":
# Define two matrices
matrix1 = [
[1, 2, 3],
[4, 5, 6],
]

matrix2 = [
[7, 8],
[9, 10],
[11, 12],
]

try:
result = matrix_multiplication(matrix1, matrix2)
print("Resultant matrix after multiplication:")
for row in result:
print(row)
except ValueError as e:
print(e)

output
: Resultant matrix after multiplication:
[58, 64]
[139, 154]
Practical No.3
1. Find the length of longest word from the set of words entered by the user(take input from
user till he enters -1)

def find_longest_word():
longest_word = ""

print("Enter words one by one. Type '-1' to stop:")


while True:
word = input("Enter a word: ")
if word == "-1": # Stop if user enters -1
break
if len(word) > len(longest_word): # Update the longest word if current word is longer
longest_word = word

if longest_word:
print(f"The longest word is '{longest_word}' with length {len(longest_word)}.")
else:
print("No words were entered.")

# Run the program


if __name__ == "__main__":
find_longest_word()

output:
Enter words one by one. Type '-1' to stop:
Enter a word: apple
Enter a word: banana
Enter a word: watermelon
Enter a word: pear
Enter a word: -1
The longest word is 'watermelon' with length 10.

[Link] to search a particular data from the given array of numbers using the Linear Search.

def linear_search(arr, target):

# Iterate through the array

for i in range(len(arr)):

if arr[i] == target:

return i # Return the index if target is found

return -1 # Return -1 if target is not found

# Example usage

if __name__ == "__main__":
# Input array from the user

n = int(input("Enter the number of elements in the array: "))

arr = []

print("Enter the elements:")

for _ in range(n):

[Link](int(input()))

# Input the target value to search

target = int(input("Enter the number to search: "))

# Perform Linear Search

result = linear_search(arr, target)

# Display the result

if result != -1:

print(f"Number {target} found at index {result}.")

else:

print(f"Number {target} not found in the array.")

output:

Enter the number of elements in the array: 5

Enter the elements:

10

20

30

40

50

Enter the number to search: 30

Number 30 found at index 2


Practical No. 4

1. A Government wants to provide student loans to students in their country. But in order for
a student to be eligible to get a loan, He/ She must be in the age range 17 to 21, and must
have a minimum of 80% score in academics. Write a program to accept a name, age, and
marks of student and display if he/she is eligible for the loan or not.

def check_loan_eligibility(name, age, marks):

if 17 <= age <= 21 and marks >= 80:

return f"{name} is eligible for the student loan."

else:

return f"{name} is not eligible for the student loan."

name = input("Enter the student's name: ")

try:

age = int(input("Enter the student's age: "))

marks = float(input("Enter the student's academic percentage: "))

result = check_loan_eligibility(name, age, marks)

print(result)

except ValueError:

print("Invalid input. Please enter numeric values for age and marks.")

output:

Enter the student's name: Srushti

Enter the student's age: 20

Enter the student's academic percentage: 86

Srushti is eligible for the student loan..

2. Write a Python Program to search a particular data from the given array of strings using the
Linear Search.

def linear_search(arr, target):

for i in range(len(arr)):
if arr[i] == target:

return i # Return the index if target string is found

return -1 # Return -1 if target string is not found

if __name__ == "__main__":

# Input array from the user

n = int(input("Enter the number of strings in the array: "))

arr = []

print("Enter the strings:")

for _ in range(n):

[Link](input())

target = input("Enter the string to search: ")

result = linear_search(arr, target)

if result != -1:

print(f"String '{target}' found at index {result}.")

else:

print(f"String '{target}' not found in the array.")

output:

Enter the number of strings in the array: 4

Enter the strings:

apple

banana

cherry

date

Enter the string to search: cherry

String 'cherry' found at index 2.


Practical No.5
1. Write a python program that repeatedly prompts a user for integer numbers until the user
enters 'Done'. Once 'Done' is entered, print out the number of positive, number of negative,
number of zeros, sum & average of positive digits and sum& average of negative digits entered by
the user. If the user enters anything other than a valid number, print an appropriate message and
ignore the entered character

def main():

positive_count = 0

negative_count = 0

zero_count = 0

positive_sum = 0

negative_sum = 0

positive_numbers = []

negative_numbers = []

while True:

user_input = input("Enter an integer or 'Done' to finish: ")

if user_input.lower() == 'done':

break

try:

number = int(user_input)

if number > 0:

positive_count += 1

positive_sum += number

positive_numbers.append(number)

elif number < 0:

negative_count += 1

negative_sum += number

negative_numbers.append(number)

else:
zero_count += 1

except ValueError:

print(f"'{user_input}' is not a valid integer. Please enter a valid integer or 'Done'.")

print("\nResults:")

print(f"Number of positive numbers: {positive_count}")

print(f"Number of negative numbers: {negative_count}")

print(f"Number of zeros: {zero_count}")

if positive_count > 0:

positive_avg = positive_sum / positive_count

print(f"Sum of positive numbers: {positive_sum}")

print(f"Average of positive numbers: {positive_avg}")

else:

print("No positive numbers entered.")

# Calculate and print sum and average of negative numbers

if negative_count > 0:

negative_avg = negative_sum / negative_count

print(f"Sum of negative numbers: {negative_sum}")

print(f"Average of negative numbers: {negative_avg}")

else:

print("No negative numbers entered.")

if __name__ == "__main__":

main()

output:

Enter an integer or 'Done' to finish: 5

Enter an integer or 'Done' to finish: -3

Enter an integer or 'Done' to finish: 0

Enter an integer or 'Done' to finish: 10

Enter an integer or 'Done' to finish: Done


Results:

Number of positive numbers: 2

Number of negative numbers: 1

Number of zeros: 1

Sum of positive numbers: 15

Average of positive numbers: 7.5

Sum of negative numbers: -3

Average of negative numbers: -3.0

WPP to search a particular data from the given array of numbers using the Binary Search

def binary_search(arr, target):

left, right = 0, len(arr) - 1

while left <= right:

mid = left + (right - left) // 2

if arr[mid] == target:

return mid # Target found, return index

elif arr[mid] > target:

right = mid - 1

If the target is larger, ignore the left half

else:

left = mid + 1

is not present in the array

return -1

arr = [2, 3, 4, 10, 40] # Example sorted array

target = 10 # Element to search

result = binary_search(arr, target)

if result == -1:

print("Element not found")

else:

print(f"Element found at index: {result}")


Practical No.6

1. A Government wants to provide student loans to students in their country. But in order for a student to

be eligible to get a loan, he/she must be in the age range 17 to 21, and must have a minimum of 80%

score in academics. Write a program to accept a name, age, and marks of student and display if he/she is

eligible for the loan or not.

def check_loan_eligibility(name, age, marks):

if 17 <= age <= 21 and marks >= 80:

return f"{name} is eligible for the student loan."

else:

return f"{name} is not eligible for the student loan."

name = input("Enter the student's name: ")

try:

age = int(input("Enter the student's age: "))

marks = float(input("Enter the student's academic percentage: "))

result = check_loan_eligibility(name, age, marks)

print(result)

except ValueError:

print("Invalid input. Please enter numeric values for age and marks.")

output:

Enter the student's name: Srushti

Enter the student's age: 20

Enter the student's academic percentage: 86

Srushti is eligible for the student loan..

3. WPP to search a particular data from the given array of strings using the BinarySearch

def binary_search(arr, target):

left, right = 0, len(arr) - 1

while left <= right:


mid = left + (right - left) // 2

if arr[mid] == target:

return mid # Target found, return index

elif arr[mid] > target:

right = mid - 1

If the target is larger, ignore the left half

else:

left = mid + 1

is not present in the array

return -1

arr = [2, 3, 4, 10, 40] # Example sorted array

target = 10 # Element to search

result = binary_search(arr, target)

if result == -1:

print("Element not found")

else:

print(f"Element found at index: {result}")


Practical No. 7
1. Write a python code to

a. Create two sets. Find out the Union, intersection, difference and symmetric difference between
these two sets. # Create two sets

set1 = {1, 2, 3, 4, 5}

set2 = {4, 5, 6, 7, 8}

union_set = [Link](set2)

print(f"Union of set1 and set2: {union_set}")

# Intersection of the two sets (elements that are in both set1 and set2)

intersection_set = [Link](set2)

print(f"Intersection of set1 and set2: {intersection_set}")

# Difference between the two sets (elements that are in set1 but not in set2)

difference_set = [Link](set2)

print(f"Difference of set1 - set2: {difference_set}")

# Symmetric Difference (elements that are in either set1 or set2, but not in both)

symmetric_difference_set = set1.symmetric_difference(set2)

print(f"Symmetric Difference between set1 and set2: {symmetric_difference_set}")

output:

Union of set1 and set2: {1, 2, 3, 4, 5, 6, 7, 8}

Intersection of set1 and set2: {4, 5}

Difference of set1 - set2: {1, 2, 3}

Symmetric Difference between set1 and set2: {1, 2, 3, 6, 7, 8}


b. print a dictionary where the keys are numbers between 1 and 15 (both included) and the values
are square of keys.

# Create a dictionary where keys are numbers from 1 to 15 and values are the squares of keys

squares_dict = {x: x**2 for x in range(1, 16)}

# Print the dictionary

print(squares_dict)

output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}

2. Write a Python Program to sort an array of numbers using the Bubble Sort. def bubble_sort(arr)

for i in range(n):

for j in range(0, n-i-1):

if arr[j] > arr[j+1]:

arr[j], arr[j+1] = arr[j+1], arr[j]

return arr

if __name__ == "__main__":

arr = list(map(int, input("Enter numbers separated by space: ").split()))

sorted_arr = bubble_sort(arr)

print(f"Sorted array: {sorted_arr}")


Practical No.8
1. Write a python code

a. For Addition and multiplication of matrix# Function to add two matrices

def add_matrices(matrix1, matrix2):

# Check if matrices have the same dimensions

if len(matrix1) != len(matrix2) or len(matrix1[0]) != len(matrix2[0]):

print("Matrices must have the same dimensions for addition.")

return None

result = []

for i in range(len(matrix1)):

row = []

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

[Link](matrix1[i][j] + matrix2[i][j])

[Link](row)

return result

# Function to multiply two matrices

def multiply_matrices(matrix1, matrix2):

# Check if multiplication is possible (columns of matrix1 must be equal to rows of matrix2)

if len(matrix1[0]) != len(matrix2):

print("Matrices cannot be multiplied. Number of columns in matrix1 must be equal to number of rows in
matrix2.")

return None

# Initialize result matrix with zeros

result = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))]


# Perform matrix multiplication

for i in range(len(matrix1)):

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

for k in range(len(matrix2)):

result[i][j] += matrix1[i][k] * matrix2[k][j]

return result

# Function to print the matrix

def print_matrix(matrix):

for row in matrix:

print(row)

# Example usage

if __name__ == "__main__":

# Matrix 1

matrix1 = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

# Matrix 2

matrix2 = [

[9, 8, 7],

[6, 5, 4],

[3, 2, 1]

]
# Matrix Addition

print("Matrix 1 + Matrix 2 (Addition):")

addition_result = add_matrices(matrix1, matrix2)

if addition_result:

print_matrix(addition_result)

# Matrix Multiplication

print("\nMatrix 1 * Matrix 2 (Multiplication):")

multiplication_result = multiply_matrices(matrix1, matrix2)

if multiplication_result:

print_matrix(multiplication_result)

output:

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

Matrix 1 + Matrix 2 (Addition):

[10, 10, 10]

[10, 10, 10]

[10, 10, 10]

b. For creating the dictionary with name as key and age as value and find the maximum aged
person in the dictionary.

def find_max_age_person(age_dict):

# Find the name with the maximum age

max_age_name = max(age_dict, key=age_dict.get)

return max_age_name, age_dict[max_age_name]


# Example usage

if __name__ == "__main__":

# Creating the dictionary with name as key and age as value

age_dict = {

"Alice": 30,

"Bob": 25,

"Charlie": 35,

"David": 40,

"Eve": 28

# Find the person with the maximum age

name, age = find_max_age_person(age_dict)

# Print the result

print(f"The person with the maximum age is {name} with age {age}.")

output:

The person with the maximum age is David with age 40.

2. Write a Python Program to sort an array of strings using the Bubble Sort.

def bubble_sort(arr):

n = len(arr)

# Traverse through all elements in the array

for i in range(n):

# Last i elements are already in place

for j in range(0, n-i-1):


# Swap if the element found is greater than the next element

if arr[j] > arr[j+1]:

arr[j], arr[j+1] = arr[j+1], arr[j]

return arr

# Example usage

if __name__ == "__main__":

# Input array from the user

arr = list(map(int, input("Enter numbers separated by space: ").split()))

# Sort the array using Bubble Sort

sorted_arr = bubble_sort(arr)

# Print the sorted array

print(f"Sorted array: {sorted_arr}")

output:

Enter numbers separated by space: 64 25 12 22 11

Sorted array: [11, 12, 22, 25, 64]


Practical No.9
1. Write a python code

a. To print factorial of each number in list # Function to calculate factorial of a number

def factorial(n):

if n == 0 or n == 1:

return 1

else:

result = 1

for i in range(2, n + 1):

result *= i

return result

# Example usage

if __name__ == "__main__":

# List of numbers

numbers = [0, 1, 2, 3, 4, 5, 6]

for num in numbers:

print(f"Factorial of {num} is {factorial(num)}")

output:

Factorial of 0 is 1

Factorial of 1 is 1

Factorial of 2 is 2

Factorial of 3 is 6

Factorial of 4 is 24

Factorial of 5 is 120

Factorial of 6 is 720
b. To find the odd numbers from the lists

# Function to find odd numbers from a list

def find_odd_numbers(numbers):

# Using list comprehension to find odd numbers

odd_numbers = [num for num in numbers if num % 2 != 0]

return odd_numbers

# Example usage

if __name__ == "__main__":

# Input list of numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Get odd numbers

odd_numbers = find_odd_numbers(numbers)

# Print the odd numbers

print("Odd numbers from the list:", odd_numbers)

output:

Odd numbers from the list: [1, 3, 5, 7, 9]

2. Write a Python Program to sort an array of numbers using the Quick Sort.

# Function to perform Quick Sort

def quick_sort(arr):

# Base case: If the array has 0 or 1 element, it's already sorted

if len(arr) <= 1:

return arr

# Choose a pivot element (we can choose the last element as pivot)

pivot = arr[-1]
# Partitioning step: elements less than the pivot go to the left, greater go to the right

left = [x for x in arr[:-1] if x <= pivot]

right = [x for x in arr[:-1] if x > pivot]

# Recursively apply quick_sort to the left and right sub-arrays

return quick_sort(left) + [pivot] + quick_sort(right)

# Example usage

if __name__ == "__main__":

# Input array of numbers

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

# Sort the array using Quick Sort

sorted_arr = quick_sort(arr)

# Print the sorted array

print(f"Sorted array: {sorted_arr}")

output:

Sorted array: [11, 12, 22, 25, 64]


Practical No.10
1. Write a python code to

a. Multiply and sum all items in list

# Function to multiply and sum all items in a list

def multiply_and_sum(numbers):

total_sum = sum(numbers) # Sum of all numbers in the list

total_product = 1

for num in numbers:

total_product *= num # Multiply all numbers in the list

return total_sum, total_product

# Example usage

if __name__ == "__main__":

# Input list of numbers

numbers = [1, 2, 3, 4, 5]

# Multiply and sum all items in the list

total_sum, total_product = multiply_and_sum(numbers)

print(f"Sum of all items: {total_sum}")

print(f"Product of all items: {total_product}")

output:

Sum of all items: 15

Product of all items: 120

b. To find Smallest and largest number in list

# Function to find smallest and largest number in a list

def find_smallest_and_largest(numbers):

smallest = min(numbers) # Find the smallest number


largest = max(numbers) # Find the largest number

return smallest, largest

# Example usage

if __name__ == "__main__":

# Input list of numbers

numbers = [10, 2, 33, 45, 1, 100, 0]

# Find smallest and largest number in the list

smallest, largest = find_smallest_and_largest(numbers)

print(f"Smallest number: {smallest}")

print(f"Largest number: {largest}")

output:

Smallest number: 0

Largest number: 100

2. Write a Python Program to sort an array of string using the Quick Sort Method

# Function to perform Quick Sort

def quick_sort(arr):

# Base case: If the array has 0 or 1 element, it's already sorted

if len(arr) <= 1:

return arr

# Choose a pivot element (we can choose the last element as pivot)

pivot = arr[-1]

# Partitioning step: elements less than the pivot go to the left, greater go to the right

left = [x for x in arr[:-1] if x <= pivot]

right = [x for x in arr[:-1] if x > pivot]


# Recursively apply quick_sort to the left and right sub-arrays

return quick_sort(left) + [pivot] + quick_sort(right)

# Example usage

if __name__ == "__main__":

# Input array of strings

arr = ["banana", "apple", "grape", "orange", "kiwi"]

# Sort the array using Quick Sort

sorted_arr = quick_sort(arr)

# Print the sorted array

print(f"Sorted array: {sorted_arr}")

Output:

Sorted array: ['apple', 'banana', 'grape', 'kiwi', 'orange']

You might also like