You are on page 1of 12

Advanced Programming Practice

ASSIGNMENT WEEK 11
NAME: DEBASISH DAS
REG no: RA2211003011991
SEC: N2

Question 1
Implement a python program to find the first largest and second largest numbers in an array.
Note: Do not use any built-in sorting functions or libraries.
def find_largest_and_second_largest(arr):
if len(arr) < 2:
print("Array should have at least two elements")
return largest = second_largest = float('-inf')
for num in arr: if num > largest:
second_largest = largest largest = num elif
num > second_largest and num != largest:
second_largest = num if
second_largest == float('-inf'):
print("No second largest element found.") else:
print(f"The first largest element is: {largest}")
print(f"The second largest element is: {second_largest}")
if __name__ == "__main__": try:
arr = list(map(int, input("Enter the array elements separated by spaces:
").split())) find_largest_and_second_largest(arr) except ValueError:
print("Invalid input. Please enter integers separated by spaces.")
OUTPUT

Question 2
Write a Python program to calculate the sum of even numbers and the sum of odd numbers in an
array.
def sum_even_and_odd_numbers(arr):
sum_even = 0
sum_odd = 0 for
num in arr: if
num % 2 == 0:
sum_even += num
else:
sum_odd += num return
sum_even, sum_odd if
__name__ == "__main__":
try:
arr = list(map(int, input("Enter the array elements separated by spaces:
").split())) even_sum, odd_sum = sum_even_and_odd_numbers(arr)
print(f"Sum of even numbers: {even_sum}") print(f"Sum of odd numbers:
{odd_sum}") except ValueError: print("Invalid input. Please enter
integers separated by spaces.")
OUTPUT

Question 3
Write a python program to count the Occurrences of a Specific Element in an Array.
def count_occurrences(arr, target):
count = 0 for num
in arr: if num ==
target:
count += 1 return count if
__name__ == "__main__":
try:
arr = list(map(int, input("Enter the array elements separated by spaces:
").split())) target = int(input("Enter the element to count: "))
occurrences = count_occurrences(arr, target) print(f"The element {target}
occurs {occurrences} times in the array.") except ValueError:
print("Invalid input. Please enter integers separated by spaces.")
OUTPUT

Question 4
Write a Python program that takes a sentence as input and identifies and prints all the palindromic
words in the sentence. Use an array to store the palindromic words.
def is_palindrome(word): word =
word.replace(" ", "").lower() return
word == word[::-1] def
find_palindromic_words(sentence):
words = sentence.split()
palindromic_words = [] for
word in words: if
is_palindrome(word):
palindromic_words.append(word)
return palindromic_words if
__name__ == "__main__":
input_sentence = input("Enter a sentence: ") palindromic_words
= find_palindromic_words(input_sentence)
if palindromic_words:
print("Palindromic words in the sentence:") for
word in palindromic_words:
print(word) else:
print("No palindromic words found in the sentence.")
OUTPUT

Question 5
Write a Python program that takes a list of numbers and removes all duplicates from the list,
preserving the original order of elements.
def remove_duplicates(input_list):
unique_dict = {} result =
[] for item in input_list:
if item not in unique_dict:
unique_dict[item] = True
result.append(item) return
result if __name__ ==
"__main__":
try: input_list = list(map(int, input("Enter a list of numbers separated by
spaces: ").split())) result_list = remove_duplicates(input_list)
print("List with duplicates removed while preserving the order:")
print(result_list) except ValueError:
print("Invalid input. Please enter a list of numbers separated by spaces.")
OUTPUT

Question 6
Write a Python program that performs matrix multiplication. Ask the user to input two matrices as
lists of lists (2D arrays) and then multiply them if possible. Make sure to check if the matrices are
compatible for multiplication and handle errors gracefully.
def matrix_multiplication(matrix1, matrix2):
if len(matrix1[0]) != len(matrix2): print("Matrix multiplication is not
possible. Number of columns in the
first matrix must be equal to the number of rows in the second matrix.")
return None result = [[0 for _ in range(len(matrix2[0]))] for _ in
range(len(matrix1))] 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 def input_matrix(prompt):
matrix = [] try:
rows = int(input(prompt + "Enter the number of rows: "))
cols = int(input(prompt + "Enter the number of columns: "))
print(f"Enter the elements row by row for {prompt}:") for _
in range(rows):
row = list(map(float, input().split())) if
len(row) != cols:
raise ValueError("Invalid number of elements in a row.")
matrix.append(row) return matrix except ValueError: print("Invalid
input. Please enter valid numeric values for matrix
elements.") return None if
__name__ == "__main__":
print("Matrix Multiplication Program")
print("Enter the first matrix:") matrix1 =
input_matrix("Matrix 1: ") print("Enter the
second matrix:") matrix2 = input_matrix("Matrix
2: ") if matrix1 is not None and matrix2 is not
None: result = matrix_multiplication(matrix1,
matrix2) if result:
print("Matrix Multiplication Result:") for
row in result:
print(row)

OUTPUT

Question 7
Write a python program to print diamond number pattern using Nested Loops. 1
123
12345
123
1
def print_diamond_pattern(n): for
i in range(1, n + 1, 2):
print(" " * ((n - i) // 2), end="") for
j in range(1, i + 1):
print(j, end="") print() for
i in range(n - 2, 0, -2):
print(" " * ((n - i) // 2), end="") for
j in range(1, i + 1):
print(j, end="") print()
if __name__ == "__main__":
try: n = int(input("Enter the number of rows (odd number): "))
if n % 2 == 0:
raise ValueError("Please enter an odd number.")
print_diamond_pattern(n) except ValueError as
e: print(f"Error: {e}")

OUTPUT

Question 8
Write a Python program that simulates a simple guessing game. Generate a random number and
have the user guess it. Provide hints like “too high” or “too low” until they guess correctly.
import random def
guessing_game():
secret_number = random.randint(1, 100)
print("Welcome to the Guessing Game!") print("I'm
thinking of a number between 1 and 100.") attempts =
0 while True:
try: user_guess = int(input("Take a guess: "))
attempts += 1 if user_guess <
secret_number: print("Too low!
Try again.") elif user_guess >
secret_number: print("Too high!
Try again.") else:
print(f"Congratulations! You guessed the number {secret_number}
in {attempts} attempts.") break except ValueError:
print("Invalid input. Please enter a valid integer.")
if __name__ == "__main__":
guessing_game()

OUTPUT

Question 9
Write a Python program that checks the strength of a password entered by a user. The program
should assess the password based on criteria like length, use of uppercase and lowercase letters,
digits, and special characters. Use control structures and arrays to provide a detailed evaluation.
import string def check_password_strength(password): length_criteria =
len(password) >= 8 uppercase_criteria = any(char.isupper() for char in
password) lowercase_criteria = any(char.islower() for char in password)
digit_criteria = any(char.isdigit() for char in password)
special_char_criteria = any(char in string.punctuation for char in password)
is_strong = all([length_criteria, uppercase_criteria, lowercase_criteria,
digit_criteria, special_char_criteria])
evaluation = [] if not length_criteria:
evaluation.append("Password should be at least 8 characters long.") if
not uppercase_criteria:
evaluation.append("Password should contain at least one uppercase
letter.") if not lowercase_criteria:
evaluation.append("Password should contain at least one lowercase
letter.") if not digit_criteria:
evaluation.append("Password should contain at least one digit.")

if not special_char_criteria: evaluation.append("Password should


contain at least one special
character (e.g., !@#$%^&*).")
return is_strong, evaluation if
__name__ == "__main__":
password = input("Enter your password: ") is_strong,
evaluation = check_password_strength(password) if
is_strong:
print("Password is strong!") else:
print("Password is weak. Here are some suggestions:") for
criterion in evaluation:
print("- " + criterion)

def generate_fibonacci(n):
fibonacci_sequence = [] if n <=
0: return fibonacci_sequence
elif n == 1:
fibonacci_sequence.append(0) return
fibonacci_sequence
elif n == 2: fibonacci_sequence.extend([0,
1])

OUTPUT
Question 10
Write a Python program that generates the Fibonacci sequence up to a specified number of terms
using a loop and stores it in an array.
return fibonacci_sequence a, b =
0, 1
fibonacci_sequence.extend([a, b])
for _ in range(n - 2):
a, b = b, a + b
fibonacci_sequence.append(b)
return fibonacci_sequence if
__name__ == "__main__":
try: n = int(input("Enter the number of terms in the Fibonacci sequence:
")) if n < 0: raise ValueError("Number of terms should be
a non-negative integer.") result = generate_fibonacci(n)
print("Fibonacci sequence up to", n, "terms:")
print(result) except ValueError as e:
print("Error:", e)

OUTPUT

You might also like