0% found this document useful (0 votes)
1 views22 pages

Madurai Python

The document outlines various Python programming experiments focusing on conditional and looping statements, string manipulation, list operations, and user-defined functions. Each program includes an aim, algorithm, source code, and output, demonstrating problem-solving techniques using Python. The experiments successfully execute and verify the outputs for tasks such as checking character order, FizzBuzz, and binary search.

Uploaded by

maduraimaniv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views22 pages

Madurai Python

The document outlines various Python programming experiments focusing on conditional and looping statements, string manipulation, list operations, and user-defined functions. Each program includes an aim, algorithm, source code, and output, demonstrating problem-solving techniques using Python. The experiments successfully execute and verify the outputs for tasks such as checking character order, FizzBuzz, and binary search.

Uploaded by

maduraimaniv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Exp.

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:

def check_a_before_b(s): index


= 0 found_b =
False
while index < len(s):
current = s[index] if
current ==
'b':
found_b = True elif
current == 'a':
if found_b == True:
return False
index += 1
return True
s = "aaabbb" result = check_a_before_b(s)
print("Output:", result)

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:

Step 1: Start from number 1 and loop up to n.


Step 2: For each number:
• If divisible by both 3 and 5, add "FizzBuzz" to the result list.
• Else if divisible by 3, add "Fizz".
• Else if divisible by 5, add "Buzz".
• Otherwise, add the number itself as a string.
Step 3: After the loop ends, return the result list. Step 4:
End the program.

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:

Step 1: Start with the given number num.


Step 2: Initialize a counter steps= 0.
Step 3: While num is greater than 0:
• If num is even (num % 2 == 0), divide it by 2 (num = num // 2).
• Otherwise, subtract 1 (num = num - 1).
• Increment steps by 1 after each operation.
Step 4: When num becomes 0, return the steps.
Step 5: End the program.

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 = number_of_steps(n) print("Output:",


output)

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.

Exp. No : 2 CREATE AND MANIPULATE STRINGS USING INDEXING,


Date : SLICING, AND VARIOUS STRING FUNCTIONS

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:

s="A man,a plan,a canal:panama"


lower=s.lower() subset=lower[::- 1]
replace=subset.replace(":","").replace("
","").replace(",","") if(replace==replace[::-1]): print("true")
else:
print("false")

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.

Exp. No: 3 CREATE AND MANIPULATE LISTS USING OPERATIONS,


Date: SLICES, METHODS, LIST COMPREHENSION, AND
LOOPING.

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:

Step 1: Start the program.


Step 2: Initialize an empty set char_set to store unique characters in the current window.
Step 3: Initialize two pointers:
• left = 0 (start of the window)
• max_len = 0 (to track the maximum length found)
Step 4: Loop through each character using a right pointer from 0 to length of string - 1:
• While the character at s[right] is already in char_set:
• Remove the character at s[left] from char_set
• Move left pointer one step forward
• Add s[right] to char_set
• Update max_len as the maximum of max_len and (right - left + 1) Step 5: Return
max_len as the result. Step 6: End the program.

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:

Step 1: Start the program.


Step 2: Import defaultdict from the collections module.
Step 3: Initialize an empty dictionary anagrams using defaultdict(list). Step 4:
Loop through each word in the input list:
• Sort the characters in the word to form a key (e.g., "eat" → "aet").
• Append the original word to the list corresponding to this key in the anagrams dictionary.
Step 5: Convert the values of the dictionary to a list of lists. Step 6: Return the list of anagram
groups.
Step 7: End.
SOURCE CODE:

from collections import defaultdict def Anagrams(strs): anagrams = defaultdict(list)


for word in strs: key =
''.join(sorted(word)) # Sort the letters to form the key anagrams[key].append(word) return
list(anagrams.values())
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
result = Anagrams(strs) print("Output:",
result)

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:

Step 1: Start the program.


Step 2: Initialize two pointers: left = 0 and right = len(nums) - 1.
Step 3: Loop while left <= right:
• Calculate the middle index: mid = (left + right) // 2.
• If nums[mid] == target, return mid.

• 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:

def binary_search(nums, target):


left, right = 0, len(nums) - 1
while left <= right:

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:

Step 1: Start the program.


Step 2: If n <= 2, return n (as there are n distinct ways for 1 or 2 steps).
Step 3: If result for n exists in memo, return it.
Step 4: Compute the number of ways by solving for n-1 and n-2, and store the result in memo.
Step 5: Return the stored result for n. Step 6: End.

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:

Step 1: Start the program.


Step 2: Initialize rev = 0 and store the sign of x.
Step 3: Work with the absolute value of x.
Step 4: While x ≠ 0:
• Extract last digit: digit = x % 10
• Update rev = rev * 10 + digit
• Remove last digit from x using x //= 10 Step 5: Apply the original
sign to rev.
Step 6: If rev is within [-2³¹, 2³¹−1], return it; else return 0. Step 7:
End.

SOURCE CODE:

def reverse(x): sign = -1 if x < 0 else 1


rev = int(str(abs(x))[::-1]) * sign if
-2**31 <= rev <= 2**31 - 1:
return rev
return 0
print(reverse(123))

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.

Exp. No: 6 INHERITANCE AND UNDERSTAND THE DIFFERENT


Date: TYPES OF INHERITANCE.

PROGRAM:6a
AIM:
To implement inheritance and method overriding using a base class Animal and a subclass
Dog.

ALGORITHM:

Step 1: Start the program.


Step 2: Create a base class Animal with a method speak() that returns a generic sound.
Step 3: Define a subclass Dog that inherits from Animal.
Step 4: Override the speak() method in Dog to return "Woof!".
Step 5: Create an object of the Dog class and call its speak() method.
Step 6: Print the result to show method overriding in action. Step 7: End.

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:

Step 1: Start the program.


Step 2: Create a class LastWordLength that stores the sentence.
Step 3: Define a method len () to calculate the length of the last word in the sentence.
Step 4: Remove extra spaces and split the sentence into words.
Step 5: Return the length of the last word.
Step 6: Create an object of the class and print the length.
Step 7: End.
SOURCE CODE: class
LastWordLength:
def init (self, sentence):
self.sentence = sentence
def len (self):
return len(self.sentence.strip().split()[-1]) if self.sentence.strip() else 0
s = LastWordLength("Hello World") print(len(s))

OUTPUT:

717824l226
RESULT:

These programs demonstrate polymorphism in Python through method overloading, method


overriding, and operator overloading .Thus the program was successfully executed and output was
verified.

717824l226

You might also like