Function - `sum_of_squares_of_even` Section 2 | Problem 1Let's solve your problem step by step!is_odd_length_palindrome Section 1 | Problem 2Checks if the input string is a palindrome with an _odd_ length.Program - Vowels Uppercase, Others Lowercase Section 2 | Problem 2Let's create a fun Python program for your task! 😃Python OOPE Exam 2024 Sep Oppe 1 Set 1🧮 Function: is_positive_odd_or_negative_even Let’s build a Python function that checks if a number is either a positive odd or a negative even. 🎯 🚩 Function Definition def is_positive_odd_or_negative_even(n): # Check for positive odd OR negative even return (n > 0 and n % 2 == 1) or (n < 0 and n % 2 == 0) 📝 Step-by-Step Explanation Positive Odd Number: Condition: n > 0 and n % 2 == 1 Checks if the number is positive AND odd. Negative Even Number: Condition: n < 0 and n % 2 == 0 Checks if the number is negative AND even. Logical OR: The function returns True if any one of the above conditions is met. 🧪 Practice Questions Practice 1 print(is_positive_odd_or_negative_even(7)) # _______ 7 is positive and odd. Output: True Practice 2 print(is_positive_odd_or_negative_even(-4)) # _______ -4 is negative and even. Output: True Practice 3 print(is_positive_odd_or_negative_even(-3)) # _______ -3 is negative and odd. Output: False Practice 4 print(is_positive_odd_or_negative_even(8)) # _______ 8 is positive and even. Output: False Practice 5 print(is_positive_odd_or_negative_even(0)) # _______ 0 is neither positive nor negative (and it’s even). Output: False ✨ Key Points Odd number: Remainder when divided by 2 is 1 (n % 2 == 1). Even number: Remainder when divided by 2 is 0 (n % 2 == 0). Positive Odd or Negative Even: Only one of these is needed for True. Zero case: 0 is not positive or negative, so always returns False. Happy Coding! 🚀Python OOPE Exam 2024 Sep Oppe 1 Set 1📝 Function: within_and_has_double_quotes Let’s build a Python function to check if a string: Starts and ends with double quotes (") Has at least one double quote somewhere inside (not including the first and last characters) 🧑💻 Function Implementation def within_and_has_double_quotes(s): # Check if string has at least 2 characters and starts/ends with a double quote if len(s) < 2 or s[0] != '"' or s[-1] != '"': return False # Check for another double quote in the interior (exclude first/last char) return '"' in s[1:-1] 🔍 Step-by-Step Explanation Check the boundary quotes: The string must be at least 2 characters. The first character is " and the last character is ". Check for an internal quote: Use s[1:-1] to get the inner part of the string (excluding first and last characters). Test if " exists in this interior slice. 🧪 Practice Questions Practice 1 print(within_and_has_double_quotes('"hello"')) # _______ Interior: hello (no quotes) Output: False Practice 2 print(within_and_has_double_quotes('"he"llo"')) # _______ Interior: he"llo Yes, has an interior double quote! Output: True Practice 3 print(within_and_has_double_quotes('""')) # _______ Interior: empty string "" Output: False Practice 4 print(within_and_has_double_quotes('"a"b"c"')) # _______ Interior: a"b"c Yes, contains double quotes inside! Output: True Practice 5 print(within_and_has_double_quotes('"no inner quote')) # _______ No ending double quote. Output: False ✅ Key Points Checks boundaries (" at both ends) Looks inside (middle of string) for at least one more double quote Returns True only if both conditions are met Happy Coding! 🚀Python OOPE Exam 2024 Sep Oppe 1 Set 1📝 Function: Replace Middle Element with n Copies Let’s build a helpful Python function that replaces the middle element of a tuple with n copies of itself! 🧑💻✨ 🚩 Function Definition def replace_middle_with_n_copies(t, n): # Find the middle index mid = len(t) // 2 # Create a tuple with 'n' copies of the middle element middle_replacement = (t[mid],) * n # Build the new tuple: before + replacement + after return t[:mid] + middle_replacement + t[mid+1:] 🔍 Step-by-Step Explanation Find the Middle Index Since the tuple has odd length, the middle index is len(t) // 2. Create Replacement (t[mid],) * n makes n copies of the middle element as a tuple. Assemble the Result Use slicing: t[:mid] (elements before the middle), middle_replacement, and t[mid+1:] (elements after the middle). 🤔 Practice Questions Practice 1 t = (1, 2, 3, 4, 5) n = 3 print(replace_middle_with_n_copies(t, n)) # What do you expect? Middle element: 3 Should be replaced by (3, 3, 3) Result: (1, 2, 3, 3, 3, 4, 5) Practice 2 t = ('a', 'b', 'c') n = 2 print(replace_middle_with_n_copies(t, n)) Middle element: 'b' Result: ('a', 'b', 'b', 'c') Practice 3 t = (10,) n = 4 print(replace_middle_with_n_copies(t, n)) Single element tuple: replace with 4 copies of itself. Result: (10, 10, 10, 10) ✨ Tips Tuples are immutable: You can’t change them; instead, create and return a new tuple. Odd length guaranteed: No need to check for even-length inputs. Works for any tuple type: numbers, strings, or mixed! Happy Python-ing! 🐍🚀Python OOPE Exam 2024 Sep Oppe 1 Set 1🔢 Function: Count Positive Integers (Ignore None) Let’s build an easy-to-use Python function! ✨ 🚩 Function Definition def count_positive_integers(lst): return sum(1 for x in lst if x is not None and isinstance(x, int) and x > 0) 📝 Step-by-Step Explanation Iterate through each element x in the list. Ignore None values (x is not None). Check if the value is an integer (isinstance(x, int)). Count only if the integer is positive (x > 0, so zero is ignored). Sum up the count (sum(1 for ...)). 🧪 Practice Questions Practice 1 lst = [4, -3, None, 7, 0, None, 10] print(count_positive_integers(lst)) # _______ Answer: 3 (Counts 4, 7, 10)Python OOPE Exam 2024 Sep Oppe 1 Set 1🔄 Sum and Absolute Difference Alternately Let’s solve the problem step by step and make the code easy-to-follow with emojis, practice questions, and explanations! 🚀 📝 Full Python Code n = int(input()) for i in range(n): line = input().strip() # Split by comma and convert to integers a, b = map(int, line.split(',')) if i % 2 == 0: # Odd-numbered pair (1-based): print sum print(a + b) else: # Even-numbered pair (1-based): print absolute difference print(abs(a - b)) 🔍 Step-by-Step Explanation Read the number of pairs: The first input line is the integer n. Process each pair: For every line, read two comma-separated integers. Odd pair (1st, 3rd, 5th…): Print their sum. Even pair (2nd, 4th, 6th…): Print the absolute difference. Print the results one per line. 🧪 Practice Questions (with Solutions!) Practice 1 Input:Python OOPE Exam 2024 Sep Oppe 1 Set 1🏃♂️ Matrix Walk Function Let’s design a Python function that follows three special matrix paths — “L”, “Z”, and “O” shapes — and collects the matrix elements accordingly! 🚀 🧑💻 Function Definition def matrix_walk(matrix, path): n = len(matrix) result = [] if path == "L": # Down the first column for i in range(n): result.append(matrix[i][0]) # Across the bottom row, excluding first element for j in range(1, n): result.append(matrix[n-1][j]) return result elif path == "Z": # Top row for j in range(n): result.append(matrix[0][j]) # Diagonal except first and last row for i in range(1, n-1): result.append(matrix[i][n-i-1]) # Bottom row for j in range(n): result.append(matrix[n-1][j]) return result elif path == "O": # Top row for j in range(n): result.append(matrix[0][j]) # Right column (excluding top and bottom) for i in range(1, n-1): result.append(matrix[i][n-1]) # Bottom row (reverse, excluding last element) for j in range(n-1, -1, -1): result.append(matrix[n-1][j]) # Left column (reverse, excluding top and bottom) for i in range(n-2, 0, -1): result.append(matrix[i][0]) return result else: return [] 🔍 Step-by-Step Explanation 1. L-Shape (“L”) Walk down the first column (leftmost). Then walk right along the bottom row (skipping the already-added first element). 2. Z-Shape (“Z”) Walk across the top row (left to right). Walk diagonally from the top-right to bottom-left, excluding corners. Walk across the bottom row (left to right). 3. O-Shape (“O”) Walk around the outside (clockwise): Top row (left to right), Right column (top to bottom, skipping corners), Bottom row (right to left), Left column (bottom to top, skipping corners). 🧪 Practice Questions with Solutions Example Matrix matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] Practice 1: L-Shape print(matrix_walk(matrix, "L")) # Output: [1, 4, 7, 8, 9] Practice 2: Z-Shape print(matrix_walk(matrix, "Z")) # Output: [1, 2, 3, 5, 7, 8, 9] Practice 3: O-Shape print(matrix_walk(matrix, "O")) # Output: [1, 2, 3, 6, 9, 8, 7, 4] ✨ Key Points The function traverses only as per the specified path — “L”, “Z”, or “O”. For unknown paths, returns an empty list. Works for any square matrix of size 1 or more. Happy Matrix Walking! 🟦🟩🟨🟥Python OOPE Exam 2024 Sep Oppe 1 Set 1✨ Print “X” Pattern Program Let’s write a Python program that prints an “X” shaped pattern using backslashes (\), forward slashes (/), and a lowercase x in the center! 😃 📋 Problem Description Input: An integer n (n >= 0) Output: An “X” shape with a center "x" and n identical rows above and below, built with slashes. No extra spaces to the right of the pattern. 🧑💻 Full Python Code n = int(input()) # Print the top part for i in range(n): # i spaces, then '\', then (2*n - 2*i - 1) spaces, then '/' left_spaces = ' ' * i middle_spaces = ' ' * (2 * n - 2 * i - 1) print(left_spaces + '\\' + middle_spaces + '/') # Print the central x print(' ' * n + 'x') # Print the bottom part (mirror of above) for i in range(n-1, -1, -1): left_spaces = ' ' * i middle_spaces = ' ' * (2 * n - 2 * i - 1) print(left_spaces + '/' + middle_spaces + '\\') 🔍 Step-by-Step Explanation Top Rows: For each row i from 0 to n-1: Print i spaces. Print a backslash (\). Print (2*n - 2*i - 1) spaces (between slashes). Print a forward slash (/). Central Row: Print n spaces, then the character 'x'. Bottom Rows: Repeat in reverse for i from n-1 to 0: Print i spaces. Print a forward slash (/). Print (2*n - 2*i - 1) spaces. Print a backslash (\). No trailing spaces are added to the right of the pattern. 🧪 Practice Examples Example 1 Input:Python OOPE Exam 2024 Sep Oppe 1 Set 1Check if a Number is Divisible by Exactly One of the Given NumbersWrite a function div_by_exactly_one that takes three integers num, a, and b. The function should return True if num is divisible by exactly one of the numbers a or b, and False otherwise. NOTE: This is a function type question, you don’t have to take input or print the output, just have to complete the required function definition.Python OOPE Exam 2024 Sep Oppe 1 Set 1🗓️ mm_dd_yy_to_yy_dd_mm Function Implementation Here’s how you can implement the mm_dd_yy_to_yy_dd_mm function to convert a date string from the format mm-dd-yy to yy-dd-mm. def mm_dd_yy_to_yy_dd_mm(date: str) -> str: """ Convert a date string from the format mm-dd-yy to yy-dd-mm. Args: date (str): The date in the format "mm-dd-yy". Returns: str: The date in the format "yy-dd-mm". Example: >>> mm_dd_yy_to_yy_dd_mm("12-25-21") "21-25-12" """ mm, dd, yy = date.split('-') return f"{yy}-{dd}-{mm}" 🐍 Step-by-Step Explanation Split the String: The split('-') method divides the input string into three parts: "mm", "dd", and "yy". Unpack and Rearrange: Assign these parts to mm, dd, and yy. Then, use an f-string to rearrange them into yy-dd-mm. Return the Result: The function returns the reformatted date string. 💡 Example Usage Input: "12-25-21" Output: "21-25-12" print(mm_dd_yy_to_yy_dd_mm("12-25-21")) # Output: 21-25-12 📚 Practice Questions What will mm_dd_yy_to_yy_dd_mm("04-01-99") return? Try mm_dd_yy_to_yy_dd_mm("11-30-00") What if the input is "07-04-76"? ✅ Solutions "99-01-04" "00-30-11" "76-04-07" 🚩 Note If the input is not in the expected "mm-dd-yy" format (for example, missing dashes or incorrect number of components), the function will raise a ValueError.Python OOPE Exam 2024 Sep Oppe 1 Set 1🚀 Function: increment_value_with_max_limit Here’s a function to increment the value for a given key in a dictionary, making sure it never exceeds a specified maximum limit! def increment_value_with_max_limit(d, key, inc, limit): """ Increment the value of d[key] by inc, but do not let it exceed limit. Args: d (dict): Dictionary with integer values. key: Key whose value you want to increment. inc (int): The increment value. limit (int): The maximum allowed value. Returns: None: The dictionary is modified in-place. Example: d = {'a': 5} increment_value_with_max_limit(d, 'a', 10, 12) # Now d['a'] == 12 """ if key in d: d[key] = min(d[key] + inc, limit) ✨ Step-by-Step Explanation Check Key Exists: Make sure the key is present in the dictionary. Increment and Cap: Add the inc value to the current value for the key. Use min(new_value, limit) to cap the result at limit if it would go over. Update In Place: The original dictionary is modified directly. No return value necessary! 📝 Practice Questions If d = {'x': 7}, what does increment_value_with_max_limit(d, 'x', 4, 10) do? What happens for d = {'b': 2}, increment_value_with_max_limit(d, 'b', 5, 5)? Try d = {'score': 20}, increment_value_with_max_limit(d, 'score', 3, 22) ✅ Solutions The value becomes min(7+4, 10) = 10. So, d['x'] will be 10. The value becomes min(2+5, 5) = 5. So, d['b'] will be 5. The value becomes min(20+3, 22) = 22. So, d['score'] will be 22. 💡 Now you can safely increment dictionary values without ever exceeding the maximum you set!Python OOPE Exam 2024 Sep Oppe 1 Set 1🔎 Function: Find Last Word Starting with Uppercase Here’s how you can implement the last_word_starts_with_upper_case function to find the last word in a sentence that starts with an uppercase letter. If no such word exists, it returns None. 🛠️ Function Definition def last_word_starts_with_upper_case(sentence: str): """ Find the last word in a sentence that starts with an uppercase letter. Args: sentence (str): The input sentence. Returns: str or None: The last word starting with an uppercase letter, or None if no such word exists. """ result = None for word in sentence.split(): if word and word[0].isupper(): result = word return result ✨ Step-by-Step Explanation Step 1: Split the sentence into individual words using split(). Step 2: Loop through each word: If the word starts with an uppercase letter (word.isupper()), save it as the current result. Step 3: After checking all words, return the last word found that met the criteria, or None if none did. 🚦 Example Usage print(last_word_starts_with_upper_case("This is a Test sentence")) # Output: "Test" print(last_word_starts_with_upper_case("no uppercase words here")) # Output: None 📝 Practice Questions What will last_word_starts_with_upper_case("Alice and Bob went to Paris") return? Try last_word_starts_with_upper_case("all lowercase words"). What is the result of last_word_starts_with_upper_case("Python Is Easy To Learn")? ✅ Solutions "Paris" None "Learn" With this function, you can quickly scan sentences for the last word that begins with a capital letter. Perfect for text analysis and simple parsing tasks! 🐍💡Python OOPE Exam 2024 Sep Oppe 1 Set 1🔄 Swap and Reverse Lines Program in Python Below is a Python program that reads multiple lines of input, swaps every two consecutive lines, and then reverses every odd-numbered line in the resulting output sequence. This meets the problem’s requirements exactly. 🛠️ Complete Code def main(): n = int(input()) lines = [input() for _ in range(n)] # Swap every two consecutive lines for i in range(0, n - 1, 2): lines[i], lines[i + 1] = lines[i + 1], lines[i] # Reverse every odd-numbered line in the output (1-based index) for i in range(n): if (i + 1) % 2 == 1: # odd line number lines[i] = lines[i][::-1] # Print the transformed lines for line in lines: print(line) if __name__ == "__main__": main() 📝 Explanation Input Reading: Read the integer n for the number of lines, then read each line into a list. Swapping Consecutive Lines: Iterate through the list in steps of two, swapping the pair at indices i and i+1. Reversing Odd-Numbered Lines: After swapping, reverse every odd line (1st, 3rd, 5th, …) by checking (i+1) % 2 == 1. Output: Print each line after these transformations. 🌟 Example Run Input:Python OOPE Exam 2024 Sep Oppe 1 Set 1📝 Filter Words by Custom Criteria Below is the requested function to filter a list of words based on one of four criteria: continuous, vowel_rich, consonant_rich, or sorted. Words are checked case-insensitively, and helper functions are included for each criteria. def filter_words(words, criteria): """ Filters a list of words based on the given criteria. Args: words (list of str): Input list of words. criteria (str): One of 'continuous', 'vowel_rich', 'consonant_rich', 'sorted'. Returns: list or None: Filtered list based on criteria, or None if invalid. Criteria: • 'continuous': words ending with 'ing' (case-insensitive) • 'vowel_rich': words with more than 5 vowels • 'consonant_rich': words with more than 5 consonants • 'sorted': words whose letters are in ascending order (case-insensitive) """ def is_continuous(word): return word.lower().endswith('ing') def count_vowels(word): return sum(1 for ch in word.lower() if ch in "aeiou") def count_consonants(word): return sum(1 for ch in word.lower() if ch.isalpha() and ch not in "aeiou") def is_sorted(word): letters = [ch.lower() for ch in word if ch.isalpha()] return letters == sorted(letters) if criteria == 'continuous': return [w for w in words if is_continuous(w)] elif criteria == 'vowel_rich': return [w for w in words if count_vowels(w) > 5] elif criteria == 'consonant_rich': return [w for w in words if count_consonants(w) > 5] elif criteria == 'sorted': return [w for w in words if is_sorted(w)] else: return None ✨ Step-by-Step Explanation Helper Functions: is_continuous: Checks if the word ends with “ing” (case-insensitive). count_vowels: Counts vowels (a, e, i, o, u). count_consonants: Counts consonants (alphabetic letters that are not vowels). is_sorted: Checks if the letters of the word are in ascending order. Criteria Check: The function checks the criteria argument and applies the relevant helper. If an unknown criteria is given, returns None. 🧪 Practice Questions Try calling the function on the following list:Python OOPE Exam 2024 Sep Oppe 1 Set 1def print_n_pattern(n): """ Prints an "N" shaped pattern with n rows. The pattern has vertical bars (|) on the left and right sides of each row, with a backslash (\) moving diagonally from the top-left to the bottom-right. There are no spaces to the right of the pattern. Args: n (int): The number of rows for the pattern (n > 0). """ for i in range(n): # Start each row with a vertical bar row = "|" # Add leading spaces before the diagonal backslash # The number of leading spaces is equal to the current row index 'i' row += " " * i # Add the diagonal backslash row += "\\" # Add trailing spaces after the diagonal backslash # The total width of the inner part (between vertical bars) is (n - 1) characters. # So, the number of trailing spaces is (n - 1) - i row += " " * (n - 1 - i) # End each row with a vertical bar row += "|" # Print the constructed row print(row) if __name__ == "__main__": try: # Read the integer input from the user n = int(input()) # Validate the input: n must be greater than 0 if n <= 0: print("Input 'n' must be a positive integer (n > 0).") else: # Call the function to print the pattern print_n_pattern(n) except ValueError: # Handle cases where the input is not a valid integer print("Invalid input. Please enter a single integer.")Remove two elements Section 1 | Problem 3Let's break down the task and provide a clear solution!Student Filter Function Section 3 | Problem 1Let's create a function that helps you filter student roll numbers by different criteria in a marks list! 🔎sum_squares_abs_diff_squares Section 1 | Problem 1🧮 Function - `sum_squares_abs_diff_squares`V Shaped Pattern Printer Section 3 | Problem 2Let's create a fun program that prints a "V" shaped pattern using slashes and a 'v' at the bottom! 🎉