Python Naan Mudhalvan Record
Python Naan Mudhalvan Record
Sequential Removal
AIM
To write a PROGRAM IS TO read the input string and develop a sequence output string
based on the formula.
Algorithm
1. Input: Read the input string s.
2. Sequence Generation: Generate the sequence of indices based on the formula 2^n
(i.e., 2, 4, 8, 16, ...).
3. Remove Characters:
o Initialize an empty result string.
o Iterate through each character of the input string.
o If the index is in the generated sequence, skip it.
o Otherwise, append the character to the result string.
4. Output: Print the resulting string.
Class Diagram
+----------------------------+
| StringCleaner |
+------------------------------+
| - input_string |
| - indices_to_remove |
+---------------------------------------+
| + __init__(input_string: str) |
| + generate_indices() |
| + clean_string() |
| + get_cleaned_string() |
+--------------------------------------+
Python Code
class StringCleaner:
def __init__(self, input_string: str):
self.input_string = input_string
self.indices_to_remove = self.generate_indices()
def generate_indices(self):
indices = []
n = 1 # start with 1 to generate 2^n
while True:
index = 2 ** n # calculate 2^n
if index >= len(self.input_string):
break
[Link](index)
n += 1
return indices
def clean_string(self):
result = ""
for i in range(len(self.input_string)):
if i + 1 not in self.indices_to_remove: # Adjust for 1-based index
result += self.input_string[i]
return result
def get_cleaned_string(self):
return self.clean_string()
# Example usage
if __name__ == "__main__":
s = "Infosys global"
cleaner = StringCleaner(s)
cleaned_string = cleaner.get_cleaned_string()
print(cleaned_string)
OUTPUT:
Infosy global
3. String validation II
AIM
To write a program to check the word has vowel or cosonant
Algorithm
1. Input: Read the input word W.
2. Length Check:
o If the length of W is less than 3, output "invalid".
3. Character Check:
o Extract the 2nd character of the word (index 1).
o If the 2nd character is an alphabet:
▪ Check if it is a vowel ('a', 'e', 'i', 'o', 'u' both lowercase and uppercase):
▪ If yes, output "vowel".
▪ If no, output "consonant".
o If the 2nd character is a digit (0-9), output "digit".
o If it is any other character, output "other".
4. Output: Print the result based on the checks above.
Class Diagram
+---------------------------+
| WordChecker |
+---------------------------+
| - word: str |
+---------------------------+
| + __init__(word: str) |
| + check_length() |
| + check_character() |
| + get_result() |
+-----------------------------+
Python Code
def check_second_character(word: str) -> str:
# Step 2: Check the length of the word
if len(word) < 3:
return "invalid"
# Step 3: Extract the 2nd character
second_char = word[1]
# Step 4: Check the type of the 2nd character
if second_char.isalpha(): # Check if it's an alphabet
if second_char.lower() in 'aeiou': # Check for vowel
return "vowel"
else:
return "consonant"
elif second_char.isdigit(): # Check if it's a digit
return "digit"
else: # Any other character
return "other"
# Example usage
if __name__ == "__main__":
W = input().strip() # Read input
result = check_second_character(W)
print(result) # Output the result
sample output:
• For input "apple",
the output will be:
vowel
• For input "bcd",
the output will be:
consonant
• For input "2bc",
the output will be:
digit
• For input "a",
the output will be:
invalid
[Link] Operations -
AIM
To write a program to perform the following Given a number XXX:
1. If XXX is a single-digit number, output its square.
2. If XXX has more than one digit, check the second digit and determine the output
based on its properties.
Algorithm
1. Input: Read the integer XXX.
2. Single Digit Check:
o If XXX is a single-digit number (0 to 9), calculate and output the square of
XXX.
3. Multi-Digit Check:
o If XXX has more than one digit, convert XXX to a string to easily access the
digits.
o Extract the second digit:
▪ If the second digit is divisible by both 2 and 4, output "24".
▪ Else if XXX is even, output "2".
▪ Else if XXX is odd, output "1".
4. Output: Print the result based on the checks.
Class Diagram
+--------------------------------+
| NumberChecker |
+---------------------------------+
| - number: int |
+---------------------------------+
| + __init__(number: int) |
| + is_single_digit() |
| + check_digits() |
| + get_result() |
+---------------------------------+
Python Code
class NumberChecker:
def __init__(self, number: int):
[Link] = number
def is_single_digit(self) -> bool:
"""Check if the number is a single digit."""
return 0 <= [Link] <= 9
def check_digits(self) -> str:
num_str = str([Link])
if len(num_str) < 2: # This means it's a single digit
return str([Link] ** 2)
second_digit = int(num_str[1]) # Get the second digit
if second_digit % 2 == 0 and second_digit % 4 == 0:
return "24"
elif [Link] % 2 == 0:
return "2"
else:
return "1"
def get_result(self) -> str:
"""Get the result based on the number."""
if self.is_single_digit():
return str([Link] ** 2)
return self.check_digits()
# Example usage
if __name__ == "__main__":
X = int(input().strip()) # Read input
checker = NumberChecker(X)
result = checker.get_result()
print(result) # Output the result
Output
• For input 3, the output will be:
9
• For input 24, the output will be:
24
• For input 30, the output will be:
2
• For input 13, the output will be:
1
5. Duplicate Number
AIM
To write a program that does the following Given an array AAA of NNN integers,
identify the single duplicate number. If no duplicates exist, return -1.
Algorithm
1. Input: Read the array AAA from the input, ensuring it's a list of integers.
2. Data Structure: Use a set to track seen numbers.
3. Duplicate Check:
o Iterate through each number in the array AAA:
▪ If the number is already in the set, it is the duplicate. Print the number
and exit.
▪ Otherwise, add the number to the set.
4. No Duplicates: If the loop completes without finding a duplicate, print -1.
5. Output: Display the duplicate number or -1 based on the findings.
Class Diagram
+------------------------+
| DuplicateFinder |
+----------------------------+
| - array: List[int] |
| - seen: Set[int] |
+----------------------------------+
| + __init__(array: List[int]) |
| + find_duplicate() |
| + get_result() |
+-----------------------------------+
Python Code
class DuplicateFinder:
def __init__(self, array: list):
[Link] = array
[Link] = set()
def find_duplicate(self):
"""Find and return the duplicate number in the array."""
for number in [Link]:
if number in [Link]:
return number
[Link](number)
return -1 # No duplicates found
def get_result(self):
"""Get the result of the duplicate check."""
duplicate = self.find_duplicate()
return duplicate
# Example usage
if __name__ == "__main__":
input_data = input("Enter elements of the array separated by commas: ")
array = list(map(int, input_data.split(','))) # Convert input string to list of integers
finder = DuplicateFinder(array)
result = finder.get_result()
print(result) # Output the result
Output
• For input 1,2,3,4,5,6,3, the output will be:
3
• For input 5,1,2,5,3,4, the output will be:
5
• For input 1,2,3,4,5, the output will be:
-1
[Link] of two arrays –
Aim
To compute the intersection of two arrays A and B such that the result contains only
unique elements.
Algorithm
1. Input Parsing:
o Read the input string containing two arrays separated by #.
o Split the input string into two parts, then split each part by , to get the
individual elements.
2. Convert to Sets:
o Convert both arrays into sets to eliminate duplicates.
3. Compute Intersection:
o Use the intersection operation on the two sets to find common elements.
4. Return Unique Elements:
o Convert the intersection result back to a sorted list and return it as an array of
integers.
Class Diagram
+-------------------------------------------------------+
| ArrayUtils |
+-------------------------------------------------- ----+
| +compute_intersection(input: str) -> List[int] |
+-------------------------------------------------------+
Python Program:
class ArrayUtils:
@staticmethod
def compute_intersection(input_str: str) -> list:
# Step 1: Input Parsing
parts = input_str.split('#')
if len(parts) != 2:
return []
# Step 2: Convert to Sets
array_a = set(map(int, parts[0].split(',')))
array_b = set(map(int, parts[1].split(',')))
Output:
[3, 4, 5]
[Link] unique character
Aim
To find the index of the first non-repeating character in a string SSS. If all characters
are repeating, return -1.
Algorithm
1. Initialize a Dictionary: Use a dictionary to count the occurrences of each character in
the string.
2. Count Character Frequencies: Iterate through the string and populate the dictionary
with character counts.
3. Find First Non-Repeating Character:
o Iterate through the string again and check the count of each character in the
dictionary.
o Return the index of the first character with a count of 1.
4. Return -1 if Not Found: If no non-repeating character is found, return -1.
Class Diagram
+--------------------+
| StringUtils |
+--------------------+
| +find_first_non_repeating_char(S: str) -> int |
+--------------------+
Python Program
class StringUtils:
# Example Usage
input_string = "leetcode"
result = StringUtils.find_first_non_repeating_char(input_string)
print(result) # Output: 0 (index of 'l')
output:
0 (index of 'l')
8. Reverse vowels –
Aim
To reverse the vowels in a given string while keeping the order of consonants
unchanged.
Algorithm
1. Identify Vowels: Create a set of vowels (a, e, i, o, u) to identify which characters to
reverse.
2. Extract Vowels: Traverse the input string and collect all the vowels in the order they
appear.
3. Reverse the Vowels: Reverse the list of collected vowels.
4. Reconstruct the String:
o Create a new list based on the original string.
o Replace the positions of the vowels in the original string with the reversed
vowels.
5. Return the New String: Join the modified list back into a string and return it.
Class Diagram
+---------------------+
| VowelReverser |
+---------------------+
| +reverse_vowels(s: str) -> str |
+---------------------+
Python Program
class VowelReverser:
def reverse_vowels(s: str) -> str:
# Step 1: Identify vowels
vowels = set('aeiouAEIOU')
# Step 2: Extract vowels
vowel_list = [char for char in s if char in vowels]
Aim
To count all possible pairs of twin primes in a given array of natural numbers, where
twin primes are defined as pairs of prime numbers that have a difference of two.
Algorithm
1. Input Parsing:
o Read the input string and convert it into a list of integers.
2. Check for Primality:
o Define a function to check if a number is prime.
3. Identify Twin Primes:
o Create an empty list to store the prime numbers found in the array.
o Iterate through the array and use the primality check to populate the list of
prime numbers.
4. Count Twin Prime Pairs:
o Iterate through the list of primes and check for pairs that differ by two.
o Count and return the number of such pairs.
Class Diagram
+------------------------------------------------+
| TwinPrimeCounter |
+--------------------+
| +count_twin_primes(A: List[int]) -> int |
| -is_prime(n: int) -> bool |
+------------------------------------------------+
Python Program
class TwinPrimeCounter:
def is_prime(n: int) -> bool:
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def count_twin_primes(A: list) -> int:
# Step 1: Filter out prime numbers from the array
primes = [num for num in A if TwinPrimeCounter.is_prime(num)]
# Step 2: Count twin prime pairs
count = 0
for i in range(len(primes)):
for j in range(i + 1, len(primes)):
if primes[j] - primes[i] == 2:
count += 1
return count
# Example Usage
input_string = "3,5,11,13,17,19,23,29"
input_array = list(map(int, input_string.split(',')))
result = TwinPrimeCounter.count_twin_primes(input_array)
print(result) # Output: 5 (pairs: (3, 5), (11, 13), (17, 19), (29, 31))
Output:
5 (pairs: (3, 5), (11, 13), (17, 19), (29, 31))
10. Electricity bill
Aim
To calculate the electricity bill amount based on the number of metered units
consumed using specified rate slabs.
Algorithm
1. Input Reading: Read the number of metered units UUU.
2. Initialize Bill Amount: Set the initial bill amount BBB to 0.
3. Calculate Bill Based on Slabs:
o If UUU is between 1 and 25, multiply UUU by $1.25.
o If UUU is between 26 and 50, calculate the bill for the first 25 units and the
remaining units at $1.45.
o If UUU is between 51 and 75, calculate the bill for the first 50 units and the
remaining units at $1.65.
o If UUU is between 76 and 95, calculate the bill for the first 75 units and the
remaining units at $1.95.
o If UUU is above 95, calculate the bill for the first 95 units and the remaining
units at $2.00.
4. Output the Bill Amount: Print the calculated bill amount formatted as currency.
Class Diagram
+------------------------------------+
| ElectricityBill |
+------------------------------------+
| +calculate_bill(U: int) -> float |
+-------------------------------------+
Python Code
class ElectricityBill:
+------------------------------------------+
| ShoppingCart |
+------------------------------------------+
| - items: int |
| - price_per_item: float |
+------------------------------------------+
| + calculate_total_amount() : float |
| + apply_item_discount() : float |
| + apply_amount_discount() : float |
| + get_final_amount() : float |
+--------------------------------------- --+
Python Program:
class ShoppingCart:
def __init__(self, items, price_per_item):
[Link] = items
self.price_per_item = price_per_item
def calculate_total_amount(self):
return [Link] * self.price_per_item
def get_final_amount(self):
total_amount = self.calculate_total_amount()
total_after_item_discount = self.apply_item_discount(total_amount)
amount_discount = self.apply_amount_discount(total_after_item_discount)
final_amount = total_after_item_discount - amount_discount
return final_amount
# Input
input_data = input("Enter N and P separated by a comma: ")
N, P = map(int, input_data.split(','))
cart = ShoppingCart(N, P)
# Output
final_amount = cart.get_final_amount()
print(f"Total price: {final_amount:.2f}")
output:
Enter N and P separated by a comma: 85,200
Total price: 12000.00
11. Name password generation:
Aim
To create a Python program that generates a secure password from a given name, following
specific formatting rules based on the length of the name.
Algorithm
1. Input: Read the name NNN from the user.
2. Validation: Ensure the length of the name is at least 3 characters. If not, prompt the
user for a valid input.
3. Determine Length:
o If the length of the name is even:
▪ Set lc to the last character of the name.
▪ Set le to the length of the name.
▪ Set fc to the first character of the name.
▪ Generate the password as:
password=lc+le+"@"+fc+"654"+lc\text{password} = lc + le + "@" +
fc + "654" + lcpassword=lc+le+"@"+fc+"654"+lc
o If the length of the name is odd:
▪ Generate the password as:
password=lc+le+"!"+fc+"432"+lc\text{password} = lc + le + "!" + fc +
"432" + lcpassword=lc+le+"!"+fc+"432"+lc
4. Output: Display the generated password.
Class Diagram
+----------------------------------+
| PasswordGen |
+----------------------------------+
| - name: str |
+----------------------------------+
| + generate_password() : str |
+----------------------------------+
Python Code
class PasswordGen:
def __init__(self, name):
[Link] = name
def generate_password(self):
if len([Link]) < 3:
return "Error: Name must contain at least 3 characters."
lc = [Link][-1] # Last character
le = len([Link]) # Length of the name
fc = [Link][0] # First character
if le % 2 == 0: # Even length
password = f"{lc}{le}@{fc}654{lc}"
else: # Odd length
password = f"{lc}{le}!{fc}432{lc}"
return password
# Input
name = input("Enter your name: ")
# Create instance of PasswordGen
password_generator = PasswordGen(name)
# Generate and output password
generated_password = password_generator.generate_password()
print(f"Generated password: {generated_password}")
output:
Enter your name: auxilia
Generated password: a7!a432a
[Link] attendance record
Aim
To determine if a student can be rewarded based on their attendance record, ensuring it
contains no more than one 'A' (Absent) and no more than two consecutive 'L' (Late).
Algorithm
1. Input: Read the attendance record string.
2. Count 'A': Check the number of 'A's in the string.
o If more than one 'A' is found, the student cannot be rewarded.
3. Check 'L': Iterate through the string to count consecutive 'L's:
o Maintain a counter for consecutive 'L's. Reset the counter if a different
character is encountered.
o If the counter exceeds two at any point, the student cannot be rewarded.
4. Output: Return True if the student can be rewarded, otherwise return False.
Class Diagram
+---------------------------------+
| AttendanceChecker |
+----------------------------------+
| - record: str |
+----------------------------------+
| + can_be_rewarded() : bool |
+---------------------------------+
Python Code
class AttendanceChecker:
def __init__(self, record):
[Link] = record
def can_be_rewarded(self):
absent_count = 0
consecutive_late_count = 0
for char in [Link]:
if char == 'A':
absent_count += 1
if char == 'L':
consecutive_late_count += 1
if consecutive_late_count > 2:
return False # More than two consecutive 'L'
else:
consecutive_late_count = 0 # Reset on 'P'
if absent_count > 1:
return False # More than one 'A'
return True # Conditions for reward are met
# Input
attendance_record = input("Enter the attendance record: ")
# Create an instance of AttendanceChecker
checker = AttendanceChecker(attendance_record)
# Check if the student can be rewarded
result = checker.can_be_rewarded()
# Output result
print(result)
Output:
[Link] With Fully Present String:
Enter the attendance record: PPPPPPPPPP
True
2. Output With Absent String:
Enter the attendance record: AAPPPPPPPPPP
False
3. Output With Late String:
Enter the attendance record: PPPPPPPPPPLLLLAAPPP
False
13. Permutations
Aim
To create a Python program that generates all possible permutations of a given array of
integers, constrained by the input size and value ranges.
Algorithm
1. Input: Read the array elements from the user, separated by commas.
2. Parse Input: Convert the input string into a list of integers.
3. Generate Permutations:
o Use a recursive function to generate all permutations.
o For each number in the list, fix the number and recursively generate
permutations of the remaining numbers.
o Collect all unique permutations in a result list.
4. Output: Print the list of all permutations, formatted as required.
Class Diagram
+----------------------------------------------------------+
| PermutationGenerator |
+----------------------------------------------------------+
| - array: list |
+---------------------------------------------------------+
| + generate_permutations() : list |
| + _permute(current: list, remaining: list) : None |
+---------------------------------------------------------+
Python Code
class PermutationGenerator:
def __init__(self, array):
[Link] = array
def generate_permutations(self):
result = []
self._permute([], [Link], result)
return result
def _permute(self, current, remaining, result):
if not remaining:
[Link](current)
return
for i in range(len(remaining)):
# Fix the current element and generate permutations of the remaining elements
self._permute(current + [remaining[i]], remaining[:i] + remaining[i+1:], result)
# Input
input_data = input("Enter the elements of the array A separated by commas: ")
array = list(map(int, input_data.split(',')))
# Create an instance of PermutationGenerator
permutation_generator = PermutationGenerator(array)
# Generate and output permutations
permutations = permutation_generator.generate_permutations()
# Format output
formatted_output = ','.join(str(p) for p in permutations)
print(f"[{formatted_output}]")
Output:
Enter the elements of the array A separated by commas: 1,2,3
[[1, 2, 3],[1, 3, 2],[2, 1, 3],[2, 3, 1],[3, 1, 2],[3, 2, 1]]
[Link] matrix zeroes:
Aim
To create a Python program that modifies an m×nm \times nm×n matrix such that if an
element is zero, its entire row and column are set to zero.
Algorithm
1. Input: Read the matrix from the user in the specified format.
2. Parse Input: Convert the input string into a 2D list (matrix).
3. Identify Zeros:
o Create two sets to store the rows and columns that need to be zeroed.
o Iterate through the matrix and if a zero is found, add the corresponding row
and column indices to the sets.
4. Set Rows and Columns to Zero:
o For each row index in the set, set all elements in that row to zero.
o For each column index in the set, set all elements in that column to zero.
5. Output: Print the modified matrix.
Class Diagram
+------------------------+
| MatrixModifier |
+------------------------+
| - matrix: list |
+-------------------------+
| + set_zeros() : None |
+--------------------------+
Python Code
class MatrixModifier:
def __init__(self, matrix):
[Link] = matrix
def set_zeros(self):
if not [Link]:
return
rows, cols = len([Link]), len([Link][0])
zero_rows = set()
zero_cols = set()
# Step 1: Identify which rows and columns to zero out
for i in range(rows):
for j in range(cols):
if [Link][i][j] == 0:
zero_rows.add(i)
zero_cols.add(j)
# Step 2: Set the identified rows to zero
for row in zero_rows:
for j in range(cols):
[Link][row][j] = 0
# Step 3: Set the identified columns to zero
for col in zero_cols:
for i in range(rows):
[Link][i][col] = 0
# Input
input_data = input("Enter the matrix elements (columns separated by commas and rows by
#): ")
# Parse the input
matrix = [list(map(int, [Link](','))) for row in input_data.split('#')]
# Create an instance of MatrixModifier
matrix_modifier = MatrixModifier(matrix)
# Modify the matrix
matrix_modifier.set_zeros()
# Output the modified matrix
print(matrix_modifier.matrix)
output:
Enter the matrix elements (columns separated by commas and rows by #): 1,1,1#2,2,2#3,3,3
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
[Link] swap
Aim
To create a Python program that calculates the minimum number of swaps needed to sort a
jumbled array of integers in ascending order, ensuring no number is swapped with more than
two others. If a number requires more than two swaps, the program should output "Messed up
queue."
Algorithm
1. Input: Read the jumbled array of integers from the user.
2. Identify the Sorted State: Create a sorted version of the input array to determine the
target positions of each number.
3. Create a Mapping: Create a mapping from each number to its position in the sorted
array.
4. Track Swaps:
o Iterate through each number in the original array and check its position in the
sorted array.
o For each number, determine if it's already in the correct position.
o If not, perform swaps to move it to its correct position while counting the
number of swaps.
o Maintain a count of how many times each number has been involved in swaps.
o If any number is swapped more than two times, print "Messed up queue."
5. Output: If all numbers can be sorted within the constraints, print the total number of
swaps.
Class Diagram
+----------------------------+
| QueueSorter |
+---------------------------+
| - array: list |
| - swap_count: int |
| - swap_map: dict |
+---------------------------+
| + sort_queue() : None |
+---------------------------+
Python Code
class QueueSorter:
def __init__(self, array):
[Link] = array
self.swap_count = 0
self.swap_map = {}
def sort_queue(self):
sorted_array = sorted([Link])
index_map = {value: i for i, value in enumerate(sorted_array)}
for i in range(len([Link])):
while [Link][i] != sorted_array[i]:
target_index = index_map[[Link][i]]
# Increment swap count
self.swap_count += 1
# Count swaps for the current number
if [Link][target_index] in self.swap_map:
self.swap_map[[Link][target_index]] += 1
else:
self.swap_map[[Link][target_index]] = 1
# Check if any number exceeds 2 swaps
if self.swap_map[[Link][target_index]] > 2:
print("Messed up queue")
return
# Perform the swap
[Link][i], [Link][target_index] = [Link][target_index], [Link][i]
print(self.swap_count)
# Input
input_data = input("Enter a set of integers separated by commas: ")
array = list(map(int, input_data.split(',')))
# Create an instance of QueueSorter
queue_sorter = QueueSorter(array)
# Sort the queue and print the number of swaps
queue_sorter.sort_queue()
output:
[Link] number not swapped more than 2 times:
Enter a set of integers separated by commas: 2,3,7,2,4,9,1,23,11,70
5
[Link] for a messed up queue:
Enter a set of integers separated by commas:
12,34,2,5,97,5,76,45,33,89,64,3,2,5,78,54,5676,764,343
Messed up queue
16. Tongue twister
Aim
To create a Python program that evaluates a paragraph to determine if it
qualifies as a tongue twister based on specified criteria regarding words that
start with a given anchor letter.
Algorithm
1. Input: Read the paragraph and anchor letter from the user, separated by #.
2. Validate Input:
o Ensure the paragraph is non-empty and the anchor letter is a single
character.
3. Split the Paragraph: Split the paragraph into words using spaces as
delimiters.
4. Count Anchor Words:
o Initialize a counter for words starting with the anchor letter.
o Track the last anchor word to ensure no two consecutive anchor
words are the same.
5. Check Conditions:
o Ensure there are at least 7 and no more than 20 words starting with
the anchor letter.
o Ensure that no two consecutive words starting with the anchor
letter are the same.
6. Output: Print "Good Tongue Twister" if all conditions are met; otherwise,
print "Inappropriate Entry".
Class Diagram
+--------------------------+
| TongueTwister |
+--------------------------+
| - paragraph: str |
| - anchor: str |
| - word_count: int |
| - last_anchor_word: str |
+-----------------------------+
| + validate_entry() : None |
+-----------------------+
Python Code:
class TongueTwister:
def __init__(self, input_data):
parts = input_data.split('#')
[Link] = parts[0].strip()
[Link] = parts[1].strip()
self.word_count = 0
self.last_anchor_word = ""
def validate_entry(self):
if not [Link] or len([Link]) != 1:
print("Inappropriate Entry")
return
words = [Link]()
for word in words:
if [Link]().startswith([Link]()):
if [Link]() == self.last_anchor_word.lower():
print("Inappropriate Entry")
return
self.last_anchor_word = [Link]()
self.word_count += 1
if 7 <= self.word_count <= 20:
print("Good Tongue Twister")
else:
print("Inappropriate Entry")
# Input
input_data = input("Enter the paragraph and anchor letter separated by '#': ")
tongue_twister = TongueTwister(input_data)
# Validate entry
tongue_twister.validate_entry()
output:
Enter the paragraph and anchor letter separated by '#': she #sells#sea shells on
the sea shore
Inappropriate Entry
[Link] decoding
Aim
To decode an encoded string EEE by reconstructing the original string based on
the method of encoding that involved repeatedly moving the middle character of
the original string to EEE.
Algorithm
1. Initialize Variables: Create an empty list to hold the characters of the
decoded string.
2. Iterate Over the Encoded String: Loop through each character in the
encoded string EEE and:
o Insert the character at the correct position based on its encoding
position.
o The character will be inserted at the middle index of the current
decoded string.
3. Construct the Original String: After processing all characters, convert
the list of characters into a string.
4. Return the Decoded String: Output the decoded string.
Class Diagram
plaintext
Copy code
+---------------------+
| Decoder |
+---------------------+
| - encoded_string: str |
| - decoded_list: list |
+---------------------+
| + decode() |
+---------------------+
Python Code
class Decoder:
def __init__(self, encoded_string):
self.encoded_string = encoded_string
self.decoded_list = []
def decode(self):
for char in self.encoded_string:
# Calculate the middle index for insertion
middle_index = len(self.decoded_list) // 2
# Insert the character at the middle index
self.decoded_list.insert(middle_index, char)
# Example usage
if __name__ == "__main__":
encoded_string = input("Enter the encoded string: ")
decoder = Decoder(encoded_string)
decoded_string = [Link]()
print("Decoded string:", decoded_string)
output:
Enter the encoded string: great job
Decoded string: ra objteg
[Link] Multiplication
Aim
To calculate the product of two N×NN \times NN×N matrices M1M1M1 and
M2M2M2 based on the provided input format and constraints.
Algorithm
1. Input Parsing:
o Read the input line containing nnn, followed by the two matrices
separated by '@'.
o Split the input to extract nnn and the two matrices.
o Convert the matrices into 2D lists of integers.
2. Matrix Multiplication:
o Initialize a result matrix product\text{product}product with
dimensions N×NN \times NN×N filled with zeros.
o Use three nested loops to calculate the product:
▪ Loop through each row of M1M1M1.
▪ Loop through each column of M2M2M2.
▪ For each element in the product matrix, compute the sum of
the products of corresponding elements from the row of
M1M1M1 and column of M2M2M2.
3. Output Formatting:
o Format the product matrix for output.
4. Print the Result:
o Output the product matrix.
Class Diagram
+------------------------+
| MatrixMultiplier |
+-------------------------+
| - n: int |
| - M1: list |
| - M2: list |
| - product: list |
+-------------------------+
| + parse_input() |
| + multiply() |
| + format_output() |
| + calculate_product()|
+-------------------------+
Python Code
class MatrixMultiplier:
def __init__(self, input_str):
self.input_str = input_str
self.n = 0
self.M1 = []
self.M2 = []
[Link] = []
def parse_input(self):
# Split input to get n and matrices
parts = self.input_str.split('@')
self.n = int(parts[0].strip())
matrix_parts = parts[1].strip().split('#')
# Parse M1
self.M1 = [list(map(int, [Link](','))) for row in
matrix_parts[0].strip().split('#')]
# Parse M2
self.M2 = [list(map(int, [Link](','))) for row in
matrix_parts[1].strip().split('#')]
def multiply(self):
# Initialize the product matrix with zeros
[Link] = [[0] * self.n for _ in range(self.n)]
# Perform matrix multiplication
for i in range(self.n):
for j in range(self.n):
for k in range(self.n):
[Link][i][j] += self.M1[i][k] * self.M2[k][j]
def format_output(self):
# Format the output for the product matrix
output_str = '[' + ', '.join(['[' + ', '.join(map(str, row)) + ']' for row in
[Link]]) + ']'
return output_str
def calculate_product(self):
self.parse_input()
[Link]()
return self.format_output()
# Example usage
if __name__ == "__main__":
input_str = input("Enter the matrices in the specified format: ")
matrix_multiplier = MatrixMultiplier(input_str)
product_matrix = matrix_multiplier.calculate_product()
print("Product Matrix:", product_matrix)
output:
19. Coin Change
Aim
To determine the minimum number of $5 and $1 coins needed to provide an
exact change of amount ZZZ using available XXX number of $5 coins and
YYY number of $1 coins. If exact change cannot be made, print "NP".
Algorithm
1. Input Reading: Read the input values for XXX, YYY, and ZZZ.
2. Calculate Maximum $5 Coins: Determine the maximum number of $5
coins that can be used without exceeding ZZZ or XXX.
3. Iterate Through $5 Coins: Loop through the possible number of $5
coins from maximum down to 0:
o Calculate the remaining amount after using the selected number of
$5 coins.
o Check if the remaining amount can be covered by the available $1
coins.
o If it can, print the number of $1 coins and the number of $5 coins.
4. Output "NP": If no combination of coins can provide the exact change,
print "NP".
Class Diagram
+---------------------+
| CoinChanger |
+---------------------+
| - X: int |
| - Y: int |
| - Z: int |
+---------------------+
| + find_change() |
| + print_change() |
| + main() |
+---------------------+
Python Code
class CoinChanger:
def __init__(self, x, y, z):
self.x = x # Number of $5 coins
self.y = y # Number of $1 coins
self.z = z # Amount to be changed
def find_change(self):
# Maximum number of $5 coins that can be used
max_five_coins = min(self.z // 5, self.x)
for five_coins in range(max_five_coins, -1, -1):
remaining_amount = self.z - (five_coins * 5)
if remaining_amount <= self.y:
return remaining_amount, five_coins
return None # If no combination works
def print_change(self):
result = self.find_change()
if result is None:
print("NP")
else:
one_coins, five_coins = result
print(f"{one_coins} and {five_coins}")
# Example usage
if __name__ == "__main__":
x, y, z = map(int, input("Enter X, Y, Z: ").split(','))
changer = CoinChanger(x, y, z)
changer.print_change()
output:
Enter X, Y, Z: 1,4,7
2 and 1