Madurai Python
Madurai Python
No: 1
Date: WRITE CONDITIONAL AND LOOPING STATEMENTS IN
PYTHON
PROGRAM: 1a AIM:
To check if all 'a'characters appear before any 'b' character in a given string s containing
only 'a' and 'b'.
ALGORITHM:
Step 1: Start reading the string from the beginning.
Step 2: If you see a 'b', remember that you have seen it.
Step 3: After seeing a 'b', if you ever see an 'a', return False.
Step 4: If you finish reading the string without a problem, return True Step
5: End the program.
SOURCE CODE:
OUTPUT:
717824l226
PROGRAM:1b
AIM:
To print numbers from 1 to n, replacing multiples of 3 with "Fizz", multiples of 5 with
"Buzz", and multiples of both with "FizzBuzz".
ALGORITHM:
SOURCE CODE:
def fizzBuzz(n):
result = [] for i in range (1, n +
1): if i % 3 == 0 and i % 5 ==
0:
result.append("FizzBuzz")
elif i % 3 == 0: result.append("Fizz")
elif i % 5 == 0: result.append("Buzz")
else:
result.append(str(i))
return result
n = 15 output = fizzBuzz(n)
print(output)
OUTPUT:
717824l226
PROGRAM:1c
AIM:
To find the number of steps needed to reduce a non-negative integer to zero by dividing by 2
if even or subtracting 1 if odd.
ALGORITHM:
SOURCE CODE:
def number_of_steps(num):
steps = 0 while num > 0:
if num % 2 == 0: num =
num // 2 else: num =
num - 1
steps = steps + 1
return steps
n = 14
OUTPUT:
717824l226
RESULT:
Thus, the programs use simple logic and loops to solve problems efficiently and the
program has been successfully executed and the output was verified.
PROGRAM:2a
AIM:
To reverse a given array of characters in-place without using extra space for another array.
ALGORITHM:
Step 1: Start the program.
Step 2: Take the list mylist.
Step 3: Use slicing [::-1] to reverse the list.
Step 4: Store the reversed list in
subset. Step 5: Print subset. Step 6:
End.
SOURCE CODE:
mylist=["h","e","l","l","o"]
subset=mylist[::-1]
print(subset)
OUTPUT:
PROGRAM:2b
AIM:
717824l226
To find the longest string that all the input strings share at the beginning.
ALGORITHM:
Step 1: Start the program.
Step 2: If the list is empty, return an empty string.
Step 3: Start with the first string as the prefix.
Step 4: Compare the prefix with each string in the list.
Step 5: If the prefix is not a prefix of the string, shorten the prefix by removing characters from
the end until it matches.
Step 6: If the prefix becomes empty, return an empty string.
Step 7: Return the prefix after all comparisons.
Step 8: End
SOURCE CODE: def
longestCommonPrefix(strs): if
not strs: return "" prefix =
strs[0] for string in strs[1:]:
while not
string.startswith(prefix): prefix = prefix[:-
1] if not prefix:
return ""
return prefix
strs = ["flower", "flow", "flight"] print(longestCommonPrefix(strs))
OUTPUT:
PROGRAM:2c
AIM:
To check if a string is a palindrome after converting it to lowercase and removing spaces,
commas, and colons.
ALGORITHM:
717824l226
Step 1: Start the program Step 2:
Take the string s.
Step 3: Convert all characters to lowercase and store it in lower.
Step 4: Reverse the lowercase string and store it in subset.
Step 5: Remove colons (:), spaces ( ), and commas (,) from the reversed string, and store it in
replace.
Step 6: Compare replace with its own reverse.
Step 7: If they are the same, print "true", else print "false". Step 8:
End.
SOURCE CODE:
OUTPUT:
717824l226
RESULT:
These programs use string operations like reversing, comparing, and cleaning to solve
problems. Thus the program has been successfully executed and the output is verified.
PROGRAM:3a
AIM:
To find two indices in a list such that the numbers at those indices add up to a given target.
ALGORITHM:
Step 1: Start a loop from the first element to the second last element.
Step 2: For each element, start another loop from the next element to the last.
Step 3: Check if the sum of the two elements equals the target.
Step 4: If yes, return their indices. Step 5: End the loops.
SOURCE CODE:
def twoSum(nums, target): for i in
range(len(nums)): for j in range(i + 1,
len(nums)): if nums[i] + nums[j] ==
target: return
[i, j]
nums = [2, 7, 11, 15] target = 9 result
= twoSum(nums, target)
print("Output:", result)
OUTPUT:
717824l226
PROGRAM:3b
AIM:
To rotate the elements of an array to the right by k steps.
ALGORITHM:
Step 1: Start.
Step 2: Find the length n of the array.
Step 3: Compute k % n to handle cases where k is larger than n.
Step 4: Slice the array into two parts:
• Last k elements.
• Remaining first n-k elements.
Step 5: Rearrange the array by placing the last k elements first, followed by the first n-k elements.
Step 6: End.
SOURCE CODE:
def rotate(nums, k): n = len(nums) k
= k % n # In case k > n nums[:]
= nums[-k:] + nums[:-k]
nums = [1, 2, 3, 4, 5, 6, 7] k =
3 rotate(nums, k)
print("Output:", nums)
OUTPUT:
PROGRAM:3c
AIM:
To generate Pascal’s Triangle up to a given number of rows.
ALGORITHM:
717824l226
Step 1: Start the program.
Step 2: Create an empty list triangle to store all rows. Step 3:
Loop from 0 to numRows - 1:
• Create a new row filled with 1s.
• For each element (except the first and last), set it as the sum of two numbers above it from
the previous row.
Step 4: Append each completed row to triangle. Step 5:
After the loop, return triangle.
SOURCE CODE:
def generate(numRows): triangle =
[] for row_num in range(numRows): row
= [1] * (row_num + 1) # Start with 1s for j in
range(1, row_num): row[j] = triangle[row_num -
1][j - 1] + triangle[row_num -
1][j] triangle.append(row) return
triangle numRows
=5
# Function call and Output result =
generate(numRows)
print("Output:", result)
OUTPUT:
717824l226
RESULT:
The program successfully identifies and returns the indices of two numbers in a list whose
sum equals the given target value and the output was verified.
Exp. No: 4
Date: CREATE AND MANIPULATE TUPLES, DICTIONARIES, AND
SETS, AND UNDERSTAND THE DIFFERENCES BETWEEN
MUTABLE AND IMMUTABLE TYPES.
PROGRAM:4a
AIM:
To write a Python program to check if a list contains any duplicate elements.
ALGORITHM:
Step 1: Start.
Step 2: Define function Duplicate(nums).
Step 3: Return True if length of nums ≠ length of set(nums), else False.
Step 4: Create a list and call the function.
Step 5: Print the result.
Step 6: End.
SOURCE CODE:
def Duplicate(nums):
return len(nums) != len(set(nums))
nums = [1, 2, 3, 1] print("Output:",
Duplicate(nums))
OUTPUT:
717824l226
PROGRAM:4b
AIM:
To find the length of the longest substring without repeating characters in a given string.
ALGORITHM:
SOURCE CODE:
def Substring(s): char_set
= set() left = 0 max_len
= 0 for right in
range(len(s)):
while s[right] in char_set: char_set.remove(s[left]
) left += 1 char_set.add(s[right])
max_len = max(max_len, right - left +
1)
return max_len
s = "abcabcbb" print("Output:",
Substring(s))
OUTPUT:
717824l226
PROGRAM:4c
AIM:
To group a list of strings into sets of anagrams using a dictionary-based approach.
ALGORITHM:
OUTPUT:
717824l226
RESULT:
These programs efficiently use Python's data structures like sets, dictionaries, and tuples to handle
uniqueness, grouping, and substring operations.Thus the program was successfully executed and
the output was verified.
Exp. No: 5
Date: IMPLEMENT USER-DEFINED FUNCTIONS AND
UNDERSTAND THE DIFFERENT TYPES OF
FUNCTION ARGUMENTS, SUCH AS POSITIONAL,
KEYWORD, AND DEFAULT ARGUMENTS.
PROGRAM:5a
AIM:
To implement binary search on a sorted list to find the index of a target element in logarithmic
time.
ALGORITHM:
• If nums[mid] < target, search the right half (left = mid + 1). Else, search the
left half (right = mid - 1).
Step 4: If not found, return -1. Step
5: End.
SOURCE CODE:
717824l226
mid = (left + right) // 2 if
nums[mid] == target:
return mid elif nums[mid]
< target: left
= mid + 1
else:
right = mid - 1
return -1
print(binary_search([-1, 0, 3, 5, 9, 12], 9))
OUTPUT:
PROGRAM:5b
AIM:
To calculate the number of distinct ways to climb a staircase with n steps, where one can take
either 1 or 2 steps at a time, using recursion with memoization.
ALGORITHM:
SOURCE CODE:
def climb_stairs(n, memo={}):
if n in memo:
return memo[n] if
n <= 2:
return n
memo[n] = climb_stairs(n-1, memo) + climb_stairs(n-2, memo) return
memo[n]
print(climb_stairs(2))
717824l226
OUTPUT:
PROGRAM:5c AIM:
To reverse the digits of a signed 32-bit integer and return the reversed number if it remains
within the valid 32-bit signed integer range.
ALGORITHM:
SOURCE CODE:
OUTPUT:
717824l226
RESULT:
These programs apply fundamental algorithmic techniques like recursion, iteration, and digit
manipulation to solve real-world problems efficiently.Thus the program was successfully
executed and the output was verified.
PROGRAM:6a
AIM:
To implement inheritance and method overriding using a base class Animal and a subclass
Dog.
ALGORITHM:
SOURCE CODE:
717824l226
class Animal:
def speak(self): return "Some generic
sound"
class Dog(Animal): def speak(self):
return
"Woof!" dog
= Dog()
print(dog.speak())
OUTPUT:
PROGRAM:6b
AIM:
To demonstrate the concept of multiple inheritance in Python, where a class inherits traits
from two parent classes.
ALGORITHM:
Step 1: Define the first parent class Mother with a method traits() returning a specific string. Step
2: Define the second parent class Father with a method traits() returning another string.
Step 3: Create a Child class that inherits from both Mother and Father.
Step 4: Override the traits() method in Child to combine and return both parent traits.
Step 5: Create an object of the Child class and call the traits() method. Step 6: Print
the combined result.
SOURCE CODE:
class Mother: def traits(self):
return "Kind and caring"
class Father:
def traits(self): return
"Strong and brave" class
Child(Mother, Father):
def traits(self): return f"{Mother.traits(self)} &
717824l226
{Father.traits(self)}" child
= Child() print(child.traits())
OUTPUT:
PROGRAM:6c
AIM:
To implement inheritance and method overriding using a base class Animal and a subclass
Dog.
ALGORITHM:
Step 1: Start the program.
Step 2: Define the base class Person with an init () method to initialize the name and a display ()
method to print it.
Step 3: Define the subclass Student that inherits from Person:
• Use super() . init () to call the base constructor.
• Add student_id attribute and extend the display () method to show it. Step 4:
Define another subclass GraduateStudent that inherits from Student:
• Use super() . init () to initialize name and student_id.
• Add a new attribute research_topic and extend the display () method to show it.
Step 5: Create an object of GraduateStudent and initialize it with appropriate values. Step 6:
Call the display () method to show all the details. Step 7: End the program.
SOURCE CODE:
class Person:
def init (self, name): # Fixed init self.name
= name def display(self):
print(f"Name:
{self.name}") class Student(Person):
def init (self, name, student_id): # Fixed init
717824l226
super(). init (name) self.student_id = student_id def
display(self):
super().display() print(f"Student ID:
{self.student_id}")
class GraduateStudent(Student): def init (self, name, student_id,
research_topic): # Fixed init super(). init (name, student_id)
self.research_topic = research_topic def display(self):
super().display() print(f"Research Topic: {self.research_topic}")
gs = GraduateStudent("Alice", "ST123", "Machine Learning") gs.display()
OUTPUT:
RESULT:
The program demonstrates the implementation of single, multiple, and multilevel inheritance in
Python using simple class structures and the program was successfully executed.
Exp. No: 7
IMPLEMENT POLYMORPHISM THROUGH METHOD
Date:
OVERLOADING, OVERRIDING, AND OPERATOR
OVERLOADING.
PROGRAM:7a
AIM:
To implement a class method that searches for the index of a substring within a string using
Python’s built-in string functions.
ALGORITHM:
Step 1: Start the program.
Step 2: Define a class StringSearch with a method find_index(haystack, needle).
Step 3: If needle is not provided, return a message.
Step 4: Otherwise, return the index of needle in haystack using find ().
717824l226
Step 5: Create an object and call the method with input strings.
Step 6: Print the result. Step 7: End.
SOURCE CODE:
class StringSearch: def find_index(self, haystack,
needle=None): if needle is None:
return
"Needle not provided"
return haystack.find(needle)
searcher = StringSearch() print
(searcher.find_index("sadbutsad", "sad"))
OUTPUT:
PROGRAM:7b
AIM:
To implement a base class and a subclass that validates whether a string of brackets is
properly closed and nested using stack logic.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a base class with a default validation method.
Step 3: In the subclass, override the method to use a stack for matching brackets.
Step 4: Push opening brackets; for closing brackets, check and pop the stack. Step
5: Return True if the stack is empty and all pairs match. Step 6: End.
SOURCE CODE:
class Validator:
def is_valid(self, s): return
False class
ParenthesesValidator(Validator):
717824l226
def is_valid(self, s): stack = []
mapping = {')': '(', '}': '{', ']':
'['} for char in s:
if char in mapping: top = stack.pop() if stack
else '#' if mapping[char] != top:
return False
else:
stack.append(char)
return not stack
validator = ParenthesesValidator() print(validator.is_valid("()"))
OUTPUT:
PROGRAM:7c
AIM:
To create a class that calculates the length of the last word in a given sentence using Python's
special method len ().
ALGORITHM:
OUTPUT:
717824l226
RESULT:
717824l226