0% found this document useful (0 votes)
16 views16 pages

Krish 5-12 PR

The document outlines a series of practical Python programming exercises aimed at demonstrating various concepts such as sets, dictionaries, strings, and regular expressions. Each practical includes specific aims, code implementations, and examples for tasks like finding uncommon elements, counting character frequencies, and validating passwords. The exercises are structured to enhance understanding of Python programming fundamentals.

Uploaded by

vraj kapadiya
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)
16 views16 pages

Krish 5-12 PR

The document outlines a series of practical Python programming exercises aimed at demonstrating various concepts such as sets, dictionaries, strings, and regular expressions. Each practical includes specific aims, code implementations, and examples for tasks like finding uncommon elements, counting character frequencies, and validating passwords. The exercises are structured to enhance understanding of Python programming fundamentals.

Uploaded by

vraj kapadiya
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/ 16

Enrollment. No.

: 202303103510150

Practical 5

Aim: Write a python program to,

a. Demonstrates necessary methods of set.


b. Find the list of uncommon elements from 2 lists using a set.
c. Find the longest common prefix of all strings.

Code: a. Demonstrates necessary methods of set.


def demonstrate_set_methods():
set_a = {1, 2, 3}
set_b = {3, 4, 5}

print("Set A:", set_a)


print("Set B:", set_b)

# Union
print("Union:", set_a.union(set_b))

# Intersection
print("Intersection:", set_a.intersection(set_b))

# Difference
print("Difference (A - B):", set_a.difference(set_b))

# Symmetric Difference
print("Symmetric Difference:", set_a.symmetric_difference(set_b))

# Adding an element
set_a.add(6)
print("Set A after adding 6:", set_a)

# Removing an element
set_a.remove(6)
print("Set A after removing 6:", set_a)

Code: b. Find the list of uncommon elements from 2 lists using a set.

def find_uncommon_elements(list1, list2):


set1 = set(list1)
set2 = set(list2)
uncommon = set1.symmetric_difference(set2)
return list(uncommon)

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Code: c. Find the longest common prefix of all strings.


def longest_common_prefix(strings):
if not strings:
return ""
prefix = strings[0]
for string in strings[1:]:
while not string.startswith(prefix):
prefix = prefix[:-1]
if not prefix:
return ""
return prefix

Output:

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Practical 6

Aim: Write a python program to,

a. Demonstrates necessary methods of dictionary.


b. Create a dictionary that stores details of 5 students where student
name is key and sgpa is value.
c. Count frequency of each element of list and store in dictionary using zip().

Code: a. Demonstrates necessary methods of dictionary.


# Part a: Demonstrating necessary methods of dictionary
print("Part a: Demonstrating dictionary methods")
sample_dict = {'name': 'Om', 'age': 19, 'city': 'Surat'}

# Accessing values
print("Accessing value for key 'name':", sample_dict.get('name'))

# Adding a new key-value pair


sample_dict['profession'] = 'Engineer'
print("After adding a new key-value pair:", sample_dict)

# Updating a value
sample_dict['age'] = 20
print("After updating the value of 'age':", sample_dict)

# Removing a key-value pair


removed_value = sample_dict.pop('city')
print("After removing 'city':", sample_dict, "| Removed value:", removed_value)

# Checking if a key exists


print("Is 'name' a key in the dictionary?", 'name' in sample_dict)

# Iterating through keys and values


print("Iterating through dictionary:")
for key, value in sample_dict.items():
print(f"Key: {key}, Value: {value}")

Code: b. Create a dictionary that stores details of 5 students where


student name is key and sgpa is value.

# Part b: Creating a dictionary for 5 students print("\nPart


b: Dictionary of students and their SGPA") students = {

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

'Vraj': 8.5,
'Jeel': 9.0,
'Krish': 8.8,
'Kenil': 7.9,
'Meet': 9.2
}
print("Students dictionary:", students)

Code: c. Count frequency of each element of list and store in dictionary using zip().

# Part c: Counting frequency of each element in a list using zip()


print("\nPart c: Counting frequency of elements in a list")
sample_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
unique_elements = set(sample_list)
frequency_dict = dict(zip(unique_elements, [sample_list.count(item) for item in
unique_elements]))
print("Frequency dictionary:", frequency_dict)

Output:

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Practical 7

Aim: Write a python program to,

a. Find the maximum and minimum value from a dictionary and


displays its associated key respectively.
b. Sort the elements of dictionary based on its value.

Code: a. Find the maximum and minimum value from a dictionary


and displays its associated key respectively.
def find_max_min(dictionary):
max_key = max(dictionary,
key=dictionary.get)
min_key = min(dictionary,
key=dictionary.get)
return max_key, dictionary[max_key],
min_key, dictionary[min_key]max_key =
max(students, key=students.get) min_key =
min(students, key=students.get)

print("Student with highest SGPA:", max_key, "SGPA:", students[max_key])


print("Student with lowest SGPA:", min_key, "SGPA:", students[min_key])

Code: b. Sort the elements of dictionary based on its value.


def sort_dictionary_by_value(dictionary):
sorted_dict = dict(sorted(dictionary.items(), key=lambda item: item[1]))
return sorted_dict

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Output:

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Practical 8

Aim: Write a python program to,

a. Demonstrates necessary methods of string.


b. Count the number of characters (character frequency) in a string.
c. Get a single string from two given strings, separated by a space, and
swap the first two characters of each string.

Code: a. Demonstrates necessary methods of string.


def string_methods_demo():
sample = "Hello, World!"
print("Original String:", sample)
print("Lowercase:", sample.lower())
print("Uppercase:", sample.upper())
print("Title Case:", sample.title())
print("Reversed:", sample[::-1])
print("Is Alphanumeric:", sample.isalnum())
print("Replace 'World' with 'Python':", sample.replace("World", "Python"))
print("Split by comma:", sample.split(","))
print("Check if starts with 'Hello':", sample.startswith("Hello"))
print("Check if ends with '!':", sample.endswith("!"))

Code: b. Count the number of characters (character frequency) in a string.


def character_frequency(string):
frequency = {}
for char in string:
frequency[char] = frequency.get(char, 0) + 1
return frequency

Code: c. Get a single string from two given strings, separated by a space,
and swap the first two characters of each string.

def swap_and_combine_strings(string1, string2):


if len(string1) < 2 or len(string2) < 2:
return "Both strings must have at least two
characters." swapped_string1 = string2[:2] + string1[2:]
swapped_string2 = string1[:2] + string2[2:]
return swapped_string1 + " " + swapped_string2

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Output:

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Practical 9

Aim: Write a python program to,

a. Write a function that accepts a string and counts the number of upper
case and lower-case letters.
b. Write a python program to reverse a string.
c. Write a python program to find whether the string is palindrome or not.

Code: a. Write a function that accepts a string and counts the number of
upper case and lower-case letters.

def count_case(s):
upper_count = sum(1 for
char in s if char.isupper())
lower_count = sum(1 for
char in s if char.islower())
return upper_count,
lower_count

Code: b. Write a python program to reverse a string.


def reverse_string(s):
return s[::-1]

Code: c Write a python program to find whether the string is palindrome or not.

def is_palindrome(s):
s = s.lower().replace(" ", "") # Normalize the string
return s == s[::-1]

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Output:

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Practical 10

Aim: Write a python program to,

a. Write a function to find the maximum of three numbers.


b. Write a function to create Fibonacci sequence. The function accepts
the number as an argument.
c. Find the factorial of number using recursion.

Code: a. Write a function to find the maximum of three numbers.


def find_maximum(a, b, c):
return max(a, b, c)

Code: b. Write a function to create Fibonacci sequence. The function accepts


the number as an argument.

def fibonacci_sequence(n):
sequence = []
a, b = 0, 1
for _ in range(n):
sequence.append(a)
a, b = b, a + b
return sequence

Code: c. Find the factorial of number using recursion.

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Output:

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Practical 11

Aim: Write a python program to,

a.Using regular expression, write program that finds all Date of Birth that is
in dd-mm-yyyy format from a given list.
b.Write a program that reads a text file and display all valid email-ID
and 10-digit contact number using regular expression.

Code: a.Using regular expression, write program that finds all Date of Birth
that is in dd-mm-yyyy format from a given list.
import re
# Part a: Find all Date of Birth in dd-mm-yyyy format from a given list
def find_dobs(data):
dob_pattern = r'\b\d{2}-\d{2}-\d{4}\b'
return re.findall(dob_pattern, data)

# Example usage for part a


data_list = "John's DOB is 12-05-1990, and Alice's DOB is 23-11-1985."
dobs = find_dobs(data_list)
print("Dates of Birth found:", dobs)

Code: b. Write a program that reads a text file and display all valid email-ID
and 10-digit contact number using regular expression.

# Part b: Read a text file and display all valid email-IDs and 10-digit contact numbers
def extract_emails_and_contacts(file_path):
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
contact_pattern = r'\b\d{10}\b'

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


content = file.read()
emails = re.findall(email_pattern, content)
contacts = re.findall(contact_pattern, content)

return emails, contacts

# Example usage for part b


# Create a sample text file for demonstration
sample_file = 'sample.txt'
with open(sample_file, 'w') as f:
f.write("Contact us at [email protected] or call 9876543210. Another email:
[email protected], phone: 1234567890.")
CGPIT/IT/SEM-4/ Programming with Python
Enrollment. No.: 202303103510150

emails, contacts = extract_emails_and_contacts(sample_file)


print("Emails found:", emails)
print("Contact numbers found:", contacts)
Output:

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Practical 12

Aim: Write a python program to,

d. Write a function to find the maximum of three numbers.


e. Write a function to create Fibonacci sequence. The function accepts
the number as an argument.
f. Find the factorial of number using recursion.

Code:
import re

def is_valid_password(password):
# Regular expression for password validation
pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,12}$'

# Match the password with the pattern


if re.match(pattern, password):
return True
else:
return False

# Input from user


password = input("Enter your password: ")

# Check validity
if is_valid_password(password):
print("Password is valid.")
else:
print("Password is invalid.")

CGPIT/IT/SEM-4/ Programming with Python


Enrollment. No.: 202303103510150

Output:

CGPIT/IT/SEM-4/ Programming with Python

You might also like