0% found this document useful (0 votes)
25 views26 pages

Pgm-Op (1) - Merged

Uploaded by

Bhavya Naik
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)
25 views26 pages

Pgm-Op (1) - Merged

Uploaded by

Bhavya Naik
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/ 26

Python Programming 21EC643

Program-1: Write a program to find factorial of a number using function.

def factorial(n):

if n <= 1:

return 1

else:

return n * factorial(n - 1)

num = int(input("Enter the number: "))

print(f"The factorial of {num} is {factorial(num)}")

Output :

Department of ECE Page 1


Python Programming 21EC643

Program – 2 : Write a program to generate Fibonacci series

def fibonacci(n):

prev = 0

next = 1

# Print the first two terms

if n >= 1:

print(prev, end=' ')

if n >= 2:

print(next, end=' ')

# Generate the rest of the series

for i in range(2, n):

present = prev + next

print(present, end=' ')

prev = next

next = present

number = int(input("Enter the number of terms: "))

print("Your Fibonacci series is:")

fibonacci(number)

Output :

Department of ECE Page 2


Python Programming 21EC643

Program-3 : Write a menu driven program to implement stack using Lists

class Stack:

def __init__(self):

self.stack = []

def push(self, item):

self.stack.append(item)

print(f"{item} pushed to stack")

def pop(self):

if not self.is_empty():

item = self.stack.pop()

print(f"{item} popped from stack")

return item

else:

print("Stack is empty")

return None

def peek(self):

if not self.is_empty():

return self.stack[-1]

else:

print("Stack is empty")

return None

def is_empty(self):

return len(self.stack) == 0

Department of ECE Page 3


Python Programming 21EC643

def display(self):

if not self.is_empty():

print("Stack elements are:")

for item in reversed(self.stack):

print(item)

else:

print("Stack is empty")

def menu():

stack = Stack()

while True:

print("\nMenu:")

print("1. Push")

print("2. Pop")

print("3. Peek")

print("4. Display")

print("5. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

item = input("Enter the item to push: ")

stack.push(item)

elif choice == 2:

stack.pop()

elif choice == 3:

top = stack.peek()

if top is not None:

print(f"Top element is: {top}")

Department of ECE Page 4


Python Programming 21EC643

elif choice == 4:

stack.display()

elif choice == 5:

print("Exiting...")

break

else:

print("Invalid choice! Please try again.")

if __name__ == "__main__":

menu()

Output :

Department of ECE Page 5


Python Programming 21EC643

Program-4 : Create a DB using dictionaries containing key as USN and related fields
containing Name, gender, Marks1, Marks2 & Marks3 of students. Implement the following
functions to perform i) Update Name/gender/marks ii) search for usn and display the relevant
fields iii) delete based on search for name iv)generate the report with avg marks more than
70%

# Initialize the student database

students_db = {

'2AB21EC018': {'Name': 'Shashank', 'Gender': 'M', 'Marks1': 85, 'Marks2': 78,


'Marks3': 92},

'2AB21EC014': {'Name': 'Preetam', 'Gender': 'M', 'Marks1': 65, 'Marks2': 74,


'Marks3': 80},

'2AB21EC015': {'Name': 'Rohit', 'Gender': 'M', 'Marks1': 95, 'Marks2': 88, 'Marks3':
90}

def update_student(usn, field, new_value):

if usn in students_db:

if field in students_db[usn]:

students_db[usn][field] = new_value

print(f"Updated {field} for USN {usn} to {new_value}.")

else:

print(f"Field {field} not found.")

else:

print(f"USN {usn} not found.")

def search_student(usn):

if usn in students_db:

print(f"Details for USN {usn}: {students_db[usn]}")

else:

print(f"USN {usn} not found.")

Department of ECE Page 6


Python Programming 21EC643

def delete_student_by_name(name):

to_delete = None

for usn, details in students_db.items():

if details['Name'] == name:

to_delete = usn

break

if to_delete:

del students_db[to_delete]

print(f"Deleted student with name {name} (USN {to_delete}).")

else:

print(f"Student with name {name} not found.")

def generate_report():

print("Students with average marks greater than 70%:")

for usn, details in students_db.items():

avg_marks = (details['Marks1'] + details['Marks2'] + details['Marks3']) / 3

if avg_marks > 70:

print(f"USN: {usn}, Name: {details['Name']}, Average Marks:


{avg_marks:.2f}")

# Update a student's information

update_student('2AB21EC014', 'Name', 'SOMA')

update_student('2AB21EC018', 'Marks1', 85)

# Search for a student by USN

search_student('2AB21EC018')

search_student('2AB21EC015')

Department of ECE Page 7


Python Programming 21EC643

# Delete a student by name

delete_student_by_name('Shashank')

delete_student_by_name('Rohit')

# Generate a report of students with average marks greater than 70%

generate_report()

Output :

Department of ECE Page 8


Python Programming 21EC643

Program-5: Write a program to implement search and replace multiple occurrences of a given
substring in the main string in a list.

def search_and_replace(strings_list, search_substring, replace_substring):

# Iterate through each string in the list

for i in range(len(strings_list)):

# Replace all occurrences of the search substring with the replace substring

strings_list[i] = strings_list[i].replace(search_substring, replace_substring)

return strings_list

# Example usage

strings_list = [

"This is a test string. This string is for testing.",

"Another test string with multiple test cases.",

"Test string without the target substring."

print("Your String is:")

print(strings_list)

print("\n")

search_substring = str(input("Enter Search string : "))

replace_substring = str(input("Enter the String to be replaced : "))

# Perform search and replace

print("\nYour Updated String is :\n")

updated_list = search_and_replace(strings_list, search_substring, replace_substring)

Department of ECE Page 9


Python Programming 21EC643

# Print the updated list

for string in updated_list:

print(string)

Output :

Department of ECE Page 10


Python Programming 21EC643

Program – 6 : Write a function called most_frequent that takes a string and prints the letters
in decreasing order of frequency.

def most_frequent(s):

# Create a dictionary to count the frequency of each character

frequency = {}

for char in s:

if char.isalpha(): # Consider only alphabetic characters

if char in frequency:

frequency[char] += 1

else:

frequency[char] = 1

# Sort the dictionary by frequency in decreasing order

sorted_frequency = sorted(frequency.items(), key=lambda item: item[1],


reverse=True)

# Print the characters in decreasing order of frequency

for char, freq in sorted_frequency:

print(f"{char}: {freq}")

# Example usage

input_string = input("Enter a string: ")

most_frequent(input_string)

Output:

Department of ECE Page 11


Python Programming 21EC643

Program- 7 : Write a program that reads a file, display the contents, builds a histogram of the
words in the file and print most common words in the file.

import string

from collections import Counter

def read_file(file_path):

"""Reads the content of the file and returns it as a string."""

with open(file_path, 'r') as file:

content = file.read()

return content

def build_histogram(content):

"""Builds a histogram (word frequency count) from the content."""

# Remove punctuation and convert to lowercase

translator = str.maketrans('', '', string.punctuation)

cleaned_content = content.translate(translator).lower()

# Split the content into words

words = cleaned_content.split()

# Count the frequency of each word

word_counts = Counter(words)

return word_counts

def print_most_common_words(word_counts, num_common=10):

"""Prints the most common words and their frequencies."""

most_common = word_counts.most_common(num_common)

for word, freq in most_common:

Department of ECE Page 12


Python Programming 21EC643

print(f"{word}: {freq}")

# Example usage

file_path = input("Enter the path of the file: ")

# Read the file content

content = read_file(file_path)

# Display the content

print("\nContents of the file:")

print(content)

# Build the histogram

word_counts = build_histogram(content)

# Print the most common words

print("\nMost common words:")

print_most_common_words(word_counts)

Output:

Department of ECE Page 13


Python Programming 21EC643

Program- 8: Write a program that searches a directory and all of its subdirectories,
recursively, and returns a list of complete paths for all files with a given suffix.

import os

def find_files_with_suffix(directory, suffix):

"""Searches a directory and its subdirectories for files with a given suffix."""

files_with_suffix = []

for root, _, files in os.walk(directory):

for file in files:

if file.endswith(suffix):

files_with_suffix.append(os.path.join(root, file))

return files_with_suffix

# Example usage

directory = input("Enter the directory to search: ")

suffix = input("Enter the file suffix to search for (e.g., .txt, .py): ")

# Find files with the given suffix

files = find_files_with_suffix(directory, suffix)

# Print the complete paths of the files found

print(f"\nFiles with suffix '{suffix}':")

for file in files:

print(file)

Output :

Department of ECE Page 14


Python Programming 21EC643

Program – 9: Write python code to extract From: and To: Email Addresses from the given text
file using regular expressions.

import re

def extract_emails(file_path):

"""Extracts 'From:' and 'To:' email addresses from a text file."""

with open(file_path, 'r') as file:

content = file.read()

# Regular expression pattern to match 'From:' and 'To:' email addresses

from_pattern = r'From:\s*([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})'

to_pattern = r'To:\s*([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})'

# Find all matches

from_emails = re.findall(from_pattern, content)

to_emails = re.findall(to_pattern, content)

return from_emails, to_emails

# Example usage

file_path = input("Enter the path of the text file: ")

from_emails, to_emails = extract_emails(file_path)

print("\nFrom: email addresses:")

for email in from_emails:

print(email)

Department of ECE Page 15


Python Programming 21EC643

print("\nTo: email addresses:")

for email in to_emails:

print(email)

Output:

Department of ECE Page 16


Python Programming 21EC643

Program – 10 : Consider the sentence “From rjlowe@iupui.edu Fri Jan 4 14:50:18 2008” ,
Write python code to extract email address and time of the day from the given sentence.

import re

def extract_email_and_time(sentence):

"""Extracts email address and time of the day from the given sentence."""

# Regular expression patterns to match the email address and time

email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'

time_pattern = r'\b\d{2}:\d{2}:\d{2}\b'

# Find the email address and time using regular expressions

email_match = re.search(email_pattern, sentence)

time_match = re.search(time_pattern, sentence)

email = email_match.group() if email_match else None

time_of_day = time_match.group() if time_match else None

return email, time_of_day

# Example usage

sentence = "From rjlowe@iupui.edu Fri Jan 4 14:50:18 2008"

email, time_of_day = extract_email_and_time(sentence)

print(f"Email: {email}")

print(f"Time of the day: {time_of_day}")

Output:

Department of ECE Page 17


Python Programming 21EC643

Program- 11 : Write a program to read, display and count number of sentences of the given
file.

import re

def read_file(file_path):

"""Reads the content of the file and returns it as a string."""

with open(file_path, 'r') as file:

content = file.read()

return content

def count_sentences(content):

"""Counts the number of sentences in the content."""

# Regular expression pattern to match sentence-ending punctuation

sentence_pattern = r'[.!?]'

sentences = re.split(sentence_pattern, content)

# Remove empty strings resulting from split

sentences = [sentence for sentence in sentences if sentence.strip()]

return len(sentences)

# Example usage

file_path = input("Enter the path of the text file: ")

# Read the file content

content = read_file(file_path)

# Display the content

print("\nContents of the file:")

Department of ECE Page 18


Python Programming 21EC643

print(content)

# Count the number of sentences

num_sentences = count_sentences(content)

# Print the number of sentences

print(f"\nNumber of sentences in the file: {num_sentences}")

Output :

Department of ECE Page 19


Python Programming 21EC643

Program – 12 : Write a program that gets the current date and prints the day of the week.

import datetime

def get_current_day_of_week():

"""Gets the current date and prints the day of the week."""

# Get the current date

current_date = datetime.datetime.now()

# Get the day of the week

day_of_week = current_date.strftime("%A")

print(f"Today is: {day_of_week}")

# Example usage

get_current_day_of_week()

Output :

Department of ECE Page 20


Python Programming 21EC643

Program – 13: Write a function called print_time that takes two Time objects and prints total
time it in the form hour:minute:second.

class Time:

def __init__(self, hour=0, minute=0, second=0):

self.hour = hour

self.minute = minute

self.second = second

def add_times(t1, t2):

"""Adds two Time objects and returns the result as a new Time object."""

# Add seconds, minutes and hours

total_seconds = t1.second + t2.second

total_minutes = t1.minute + t2.minute + total_seconds // 60

total_hours = t1.hour + t2.hour + total_minutes // 60

# Calculate remaining seconds and minutes

seconds = total_seconds % 60

minutes = total_minutes % 60

hours = total_hours

return Time(hours, minutes, seconds)

def print_time(t1, t2):

"""Prints the total time of two Time objects in the form hour:minute:second."""

total_time = add_times(t1, t2)

print(f"{total_time.hour}:{total_time.minute:02}:{total_time.second:02}")

Department of ECE Page 21


Python Programming 21EC643

# Example usage

time1 = Time(1, 45, 30)

time2 = Time(2, 30, 45)

print_time(time1, time2)

Output :

Department of ECE Page 22


Python Programming 21EC643

Program – 14 : Write a program that takes a birthday as input and prints the user’s age and
the number of days, hours, minutes and seconds until their next birthday.

from datetime import datetime, timedelta

def calculate_age(birthday):

"""Calculates the age of the user."""

today = datetime.now()

age = today.year - birthday.year - ((today.month, today.day) < (birthday.month,


birthday.day))

return age

def time_until_next_birthday(birthday):

"""Calculates the time until the next birthday in days, hours, minutes, and seconds."""

today = datetime.now()

next_birthday = datetime(today.year, birthday.month, birthday.day)

# If the next birthday is in the past, add one year

if next_birthday < today:

next_birthday = next_birthday.replace(year=today.year + 1)

time_difference = next_birthday - today

days = time_difference.days

hours, remainder = divmod(time_difference.seconds, 3600)

minutes, seconds = divmod(remainder, 60)

return days, hours, minutes, seconds

# Example usage

Department of ECE Page 23


Python Programming 21EC643

birthday_input = input("Enter your birthday (YYYY-MM-DD): ")

birthday = datetime.strptime(birthday_input, "%Y-%m-%d")

age = calculate_age(birthday)

days, hours, minutes, seconds = time_until_next_birthday(birthday)

print(f"Your age is: {age} years")

print(f"Time until your next birthday: {days} days, {hours} hours, {minutes} minutes,
and {seconds} seconds")

Output :

Department of ECE Page 24


ANJUMAN INSTITUTE OF TECHNOLOGY AND
MANAGEMENT
Bhatkal – 581320, Karnataka, India
ELECTRONICS & COMMUNICATION

ASSIGNMENT
2023 – 2024

NAME: _____________________________________________ ROLL NO :

BRANCH: __________________________________USN:

SEMESTER: 6

SUBJECT: 21EC63

SIGNATURE OF THE STUDENT

Signature
Sl. Date of Marks
Descripti of the
No. Submission Awarded
on Facult
y
1

TOTAL MARKS AWARDED (in figures and words): ________________

SIGNATURE OF THE FACULTY


ANJUMAN INSTITUTE OF TECHNOLOGY AND
MANAGEMENT
Bhatkal – 581320, Karnataka, India
ELECTRONICS & COMMUNICATION

ASSIGNMENT
2023 – 2024

NAME: _____________________________________________ ROLL NO:

BRANCH: __________________________________USN:

SEMESTER: 6

SUBJECT: 21EC62

SIGNATURE OF THE STUDENT

Signature
Sl. Date of Marks
Description of the
No. Submission Awarded
faculty
1

TOTAL MARKS AWARDED (in figures and words): ________________

SIGNATURE OF THE FACULTY

You might also like