NAME - S.
Abhisesha Kumaara
                                                   REG NO - RA2211026010487
                     21CSC203P - ADVANCED PROGRAMMING
                             PRACTICE WEEK - 11
                         PYTHON PROGRAM USING CONTROL
                             STRUCTURES AND ARRAYS
1. Implement a python program to find the first largest and second
largest numbers in an Array.
Note: should not use any built-in sorting functions or libraries.
def find_largest_and_second_largest(arr):
  if len(arr) < 2:
     return "The array should contain at least two elements."
  first_largest = second_largest = float('-inf')
  for num in arr:
     if num > first_largest:
        second_largest = first_largest
        first_largest = num
     elif num > second_largest and num != first_largest:
        second_largest = num
  if second_largest == float('-inf'):
     return "There is no second largest element."
   return f"The first largest number is {first_largest} and the second largest number is
{second_largest}"
arr = [12, 34, 56, 23, 67, 45, 90]
result = find_largest_and_second_largest(arr)
print(result)
OUTPUT :
1. 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
arr = [1, 2, 3, 4, 5, 6, 7, 8]
sum_even, sum_odd = sum_even_and_odd_numbers(arr)
print(f"Sum of even numbers: {sum_even}")
print(f"Sum of odd numbers: {sum_odd}")
OUTPUT :
1. Write a python program to count the Occurrences of a Specific
Element in an Array.
def count_occurrences(arr, element):
  count = 0
  for item in arr:
     if item == element:
        count += 1
  return count
arr = [1, 2, 3, 4, 2, 5, 2]
element_to_count = 2
occurrences = count_occurrences(arr, element_to_count)
print(f"The element {element_to_count} appears {occurrences} times in the array.")
OUTPUT :
1. 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):
  • Helper function to check if a word is a palindrome
  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
input_sentence = "madam is driving her civic racecar"
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 :
1. 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_list = []
  for item in input_list:
        if item not in unique_list:
          unique_list.append(item)
  return unique_list
input_list = [1, 2, 2, 3, 4, 4, 5, 6, 6]
result_list = remove_duplicates(input_list)
print("Original list:", input_list)
print("List with duplicates removed:", result_list)
OUTPUT :
1. 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):
  rows1 = len(matrix1)
  cols1 = len(matrix1[0])
  rows2 = len(matrix2)
  cols2 = len(matrix2[0])
  if cols1 != rows2:
    print("Matrix multiplication is not possible. Number of columns in the first matrix
must match the number of rows in the second matrix.")
    return None
  result = [[0 for _ in range(cols2)] for _ in range(rows1)]
  for i in range(rows1):
     for j in range(cols2):
       for k in range(cols1):
          result[i][j] += matrix1[i][k] * matrix2[k][j]
  return result
def input_matrix(prompt):
  matrix = []
  print(prompt)
  while True:
     row = input()
       if not row:
         break
       matrix.append([int(x) for x in row.split()])
   return matrix
try:
  matrix1 = input_matrix("Enter the first matrix (each row on a new line, elements
separated by space, and an empty line to finish):")
   matrix2 = input_matrix("Enter the second matrix (each row on a new line,
elements separated by space, and an empty line to finish):")
   result = matrix_multiplication(matrix1, matrix2)
   if result:
       print("Matrix multiplication result:")
       for row in result:
         print(' '.join(map(str, row)))
except ValueError:
   print("Invalid input. Please enter valid integers in the matrices.")
except Exception as e:
   print("An error occurred:", e)
OUTPUT :
1. Write a python program to print diamond number pattern using Nested
Loops.
  def print_diamond_pattern(n):
  for i in range(1, n + 1, 2):
      spaces = " " * ((n - i) // 2)
      print(spaces, end="")
      for j in range(1, i + 1):
        print(j, end="")
      for j in range(i - 1, 0, -1):
        print(j, end="")
      print()
  for i in range(n - 2, 0, -2):
    • Print leading spaces
    spaces = " " * ((n - i) // 2)
    print(spaces, end="") for j
    in range(1, i + 1):
       print(j, end="")
    for j in range(i - 1, 0, -1):
       print(j, end="")
      print()
n=5
print_diamond_pattern(n)
OUTPUT :
1. 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():
  lower_limit = 1
  upper_limit = 100
  secret_number = random.randint(lower_limit, upper_limit)
  attempts = 0
   print(f"Welcome to the guessing game! I'm thinking of a number between
{lower_limit} and {upper_limit}.")
   while True:
    try:
       user_guess = int(input("Guess the number: "))
       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}
correctly in {attempts} attempts.")
           break
    except ValueError:
       print("Invalid input. Please enter a valid number.")
if __name__ == "__main__":
  guessing_game()
OUTPUT :
1. 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 = 8
  uppercase_criteria = 1
  lowercase_criteria = 1
  digit_criteria = 1
  special_character_criteria = 1
  uppercase_count = 0
  lowercase_count = 0
  digit_count = 0
  special_character_count = 0
  special_characters = string.punctuation
  if len(password) < length_criteria:
     return "Weak password: Password should be at least 8 characters long."
  for char in password:
     if char.isupper():
        uppercase_count += 1
     elif char.islower():
        lowercase_count += 1
     elif char.isdigit():
        digit_count += 1
     elif char in special_characters:
        special_character_count += 1
  evaluation = []
  if uppercase_count < uppercase_criteria:
     evaluation.append("Add more uppercase letters.")
  if lowercase_count < lowercase_criteria:
     evaluation.append("Add more lowercase letters.")
  if digit_count < digit_criteria:
     evaluation.append("Add more digits.")
  if special_character_count < special_character_criteria:
     evaluation.append("Add more special characters.")
  if len(evaluation) == 0:
     return "Strong password: Password meets all criteria."
  else:
     return " ".join(evaluation)
password = input("Enter a password: ")
strength_evaluation = check_password_strength(password)
print(strength_evaluation)
OUTPUT :
1. 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.
def generate_fibonacci_sequence(n):
  if n <= 0:
     return []
  fibonacci_sequence = [0, 1]
  while len(fibonacci_sequence) < n:
        next_term = fibonacci_sequence[-1] + fibonacci_sequence[-2]
        fibonacci_sequence.append(next_term)
  return fibonacci_sequence
num_terms = int(input("Enter the number of Fibonacci terms to generate: "))
fib_sequence = generate_fibonacci_sequence(num_terms)
if fib_sequence:
  print("Fibonacci sequence:")
  print(fib_sequence)
else:
  print("Please enter a positive number of terms to generate.")
OUTPUT :