0% found this document useful (0 votes)
177 views13 pages

Python Experiment List for B.Tech

dr babasaheb ambedkar technologucal university (DBATU) 4th sem cse python practical experiments

Uploaded by

coderoletech
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)
177 views13 pages

Python Experiment List for B.Tech

dr babasaheb ambedkar technologucal university (DBATU) 4th sem cse python practical experiments

Uploaded by

coderoletech
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

TPCT’s

College of Engineering, Dharashiv


List Of Experiment
Class:[Link] Sub:-Python

Sr. Title of Experiment


No

1 Program to calculate area of triangle , rectangle, circle

2 Program to find the union of two lists.


3 Program to find intersection of two files.
4 Program to remove the -ith occurrence of the given word in a list where
words repeat.
5 Program to count the occurrences of each word in a given string
sentence.
6 Program to check if a substring is present in a given string.
7 Program to map two lists into a dictionary.
8 Program to count the frequency of words appearing in a string using a
dictionary.
9 Program to create a dictionary with key as first character and value as
words starting with that character.
10 Program to find the length of a list using recursion.
11 compute the diameter, circumference, and volume of a sphere using
class.
12 Program to read a file and capitalize the first letter of every word in the
file.

Prof: [Link] Prof: [Link]


Subject Incharge HOD CSE
EXPERIMENT NO. 01

 Program:

# Function to calculate the area of a triangle


def calculate_area(base, height):
return 0.5 * base * height

# Test the function


base = 10
height = 5
area = calculate_area(base, height)
print(f"The area of the triangle with base {base} and height {height} is {area}")

 Output:

The area of the triangle with base 10 and height 5 is 25.0

 Program:

# Function to calculate the area of a rectangle


def calculate_area(length, width):
return length * width

# Test the function


length = 10
width = 5
area = calculate_area(length, width)
print(f"The area of the rectangle with length {length} and width {width} is {area}")

 Output
The area of the rectangle with length 10 and width 5 is 50

 Program:

# Function to calculate the area of a circle


import math
def calculate_area(radius):
return [Link] * radius ** 2

# Test the function


radius = 5
area = calculate_area(radius)
print(f"The area of the circle with radius {radius} is {area}")

 Output:

The area of the circle with radius 5 is 78.53981633974483


EXPERIMENT NO. 02

 Program :

# Function to find the union of two lists


def union_lists(list1, list2):
return list(set(list1) | set(list2))

# Test the function


list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
union = union_lists(list1, list2)
print(f"The union of {list1} and {list2} is {union}")

 Output:

The union of [1, 2, 3, 4, 5] and [4, 5, 6, 7, 8] is [1, 2, 3, 4, 5, 6, 7, 8]


EXPERIMENT NO. 03

 Program:

# Function to find the intersection of two lists

def intersection_lists(list1, list2):

return list(set(list1) & set(list2))

# Test the function

list1 = [1, 2, 3, 4, 5]

list2 = [4, 5, 6, 7, 8]

intersection = intersection_lists(list1, list2)

print(f"The intersection of {list1} and {list2} is {intersection}")

 Output:

The intersection of [1, 2, 3, 4, 5] and [4, 5, 6, 7, 8] is [4, 5]


EXPERIMENT NO . 04

 Program:

def remove_nth_occurrence(lst, word, N):

new_lst = []

count = 0

for i in lst:

if i == word:

count += 1

if count != N:

new_lst.append(i)

else:

new_lst.append(i)

if count == 0:

print("Item not found")

else:

print("Updated list:", new_lst)

return new_lst

my_list = ["geeks", "for", "geeks"]

my_word = "geeks"

N=2

remove_nth_occurrence(my_list, my_word, N)

 Output:

Updated list: ['geeks', 'for']


EXPERIMENT NO . 05

 Program:

# Function to count the occurrence of each word in a sentence

def count_words(sentence):

word_counts = {}

words = [Link]()

for word in words:

if word in word_counts:

word_counts[word] += 1

else:

word_counts[word] = 1

return word_counts

# Test the function

sentence = "the quick brown fox jumps over the lazy dog"

word_counts = count_words(sentence)

print(f"The word counts in the sentence '{sentence}' are {word_counts}")

 Output:

The word counts in the sentence 'the quick brown fox jumps over the lazy dog' are {'the': 2, 'quick': 1,
'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}
EXPERIMENT NO . 06

 Program:

# Function to check if a

substring is present in a string

def

is_substring_present(string,

substring):

return substring in string

# Test the function

string = "Hello, world!"

substring = "world"

is_present =

is_substring_present(string,

substring)

print(f"Is '{substring}' present

in '{string}'? {is_present}")

 Output:

Is 'world' present in 'Hello,

world!'? True
EXPERIMENT NO . 07

 Program:

# Function to map two lists into a dictionary

def map_lists_to_dict(keys, values):

return dict(zip(keys, values))

# Test the function

keys = ['name', 'age', 'job']

values = ['John', 30, 'Engineer']

dictionary = map_lists_to_dict(keys, values)

print(f"The dictionary mapped from the lists is {dictionary}")

 Output:

The dictionary mapped from the lists is {'name': 'John', 'age': 30, 'job': 'Engineer'}
EXPERIMENT NO . 08

 Program:
# Function to count the frequency of words in a string
def count_word_frequency(sentence):
word_counts = {}
words = [Link]()
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
return word_counts

# Test the function


sentence = "the quick brown fox jumps over the lazy dog"
word_counts = count_word_frequency(sentence)
print(f"The word counts in the sentence '{sentence}' are {word_counts}")

 Output:

The word counts in the sentence 'the quick brown fox jumps over the lazy dog' are {'the': 2,
'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}
EXPERIMENT NO . 09

 Program:

#Program to create a dictionary with key as first character and value as words starting with that character.

string_input = '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well
thought and well explained computer science and programming articles, quizzes etc.'''
words = string_input.split()
dictionary = {}

for word in words:


first_char = word[0].lower() # Make it case-insensitive
if first_char not in dictionary:
dictionary[first_char] = []
if word not in dictionary[first_char]:
dictionary[first_char].append(word)

print(dictionary)

 Output:

{'g': ['GeeksforGeeks', 'geeks.'], 'i': ['is', 'It'], 'a': ['a', 'and', 'articles,'], 'c': ['Computer', 'contains', 'computer'],
's': ['Science', 'science'], 'p': ['portal', 'programming'], 'f': ['for'], 'w': ['well', 'written,'], 't': ['thought'], 'e':
['explained', 'etc.'], 'q': ['quizzes']}
EXPERIMENT NO. 10

 Program:

#length of list using recusion


def length(lst):
if not lst:
return 0
else:
return 1 + length(lst[1:])

# Test the function


print(length([1, 2, 3, 4, 5])) # Output: 5

 Output:
5
EXPERIMENT NO. 11

 Program:

import math

class Sphere:

def __init__(self, radius):

[Link] = radius

def diameter(self):

return 2 * [Link]

def circumference(self):

return 2 * [Link] * [Link]

def volume(self):

return 4/3 * [Link] * [Link]**3

# Create a sphere with radius 5

s = Sphere(5)

print("Diameter:", [Link]()) # Output: 10

print("Circumference:", [Link]()) # Output: 31.41592653589793

print("Volume:", [Link]()) # Output: 523.5987755982989

 Output:

Diameter: 10
Circumference: 31.41592653589793
Volume: 523.5987755982989
EXPERIMENT NO. 12
 Program:

def capitalize_words(filename):

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

lines = [Link]()

capitalized_lines = []

for line in lines:

words = [Link]()

capitalized_words = [[Link]() for word in words]

capitalized_line = ' '.join(capitalized_words)

capitalized_lines.append(capitalized_line)

return '\n'.join(capitalized_lines)

# Test the function

print(capitalize_words('[Link]'))

 Output:

Traceback (most recent call last):


File "/home/[Link]", line 15, in <module>
print(capitalize_words('[Link]'))
File "/home/[Link]", line 2, in capitalize_words
with open(filename, 'r') as file:
FileNotFoundError: [Errno 2] No such file or directory: '[Link]'

Common questions

Powered by AI

Mapping two lists into a dictionary involves using one list as keys and another as values. The `zip` function pairs elements from both lists and `dict` converts these pairs into dictionary entries. This technique is beneficial for creating dictionaries dynamically from list data, such as turning user inputs into parameter-value pairs or translating variable data into configurations. Use cases include data processing tasks where structured representation from flat data is required .

List comprehension can be used in conjunction with dictionary creation by iterating over each word in a split string, extracting the first character as the key, and appending the word to a list associated with that key. This involves checking if a key exists in the dictionary and using conditionals to append the word if certain criteria are met. The use of list comprehension streamlines the process by allowing operations to be performed in a more compact, comprehendible syntax .

Counting word occurrences in a sentence using dictionaries provides an efficient and straightforward method for text analysis by utilizing a dictionary's key-value store that maps words to their frequency. This allows quick lookups and updates due to the average time complexity of O(1) for insertions and retrievals. This method is particularly useful in applications such as natural language processing where word frequency analysis is crucial .

Challenges in implementing a file capitalization program include handling file not found errors, dealing with file permissions, and ensuring the file format supports text processing. Solutions involve using exception handling to manage `FileNotFoundError`, verifying file existence and permissions before opening, and testing with various file types to ensure compatibility. Using `try...except` blocks can prevent the program from crashing when the file cannot be accessed .

Recursive programming calculates the length of a list by repeatedly calling a function with a smaller segment of the list until it terminates with an empty list case, while iterative approaches use loops to count elements until the list end is reached. Recursion can be more intuitive for problems naturally described by divided parts, such as tree traversal, and it often results in clearer, more succinct code compared to iterative methods. However, it is less efficient in terms of space and stack depth usage compared to loops .

Using the `math` module for sphere-related calculations ensures precision due to reliable functions for pi and arithmetic operations on floats. The module handles edge cases and mathematical constants, reducing errors compared to manual arithmetic manipulation. However, performance can be affected by the need for floating-point operations and increased complexity if operations scale. Despite this, the benefits of accuracy typically outweigh the minor performance costs in typical applications .

The implementation of object-oriented principles is central to computing sphere properties by encapsulating these calculations within a Sphere class. This class defines methods for calculating diameter, circumference, and volume, encapsulating the logic and allowing for easy reuse and maintenance. The class design promotes modularity and clear abstraction, which enhances readability and robustness of the code handling geometrical computations .

The removal of the ith occurrence of a word involves iterating through a list using loops, conditionals, and maintaining counters to track occurrences, demonstrating control flow structures. Control structures like `for` loops manage list traversal, `if` statements decide whether to retain or remove an element, and a counter is incremented to keep track of how many times a word appears. This approach shows how Python's control flow can be leveraged for precise list manipulations .

Using sets for list operations such as union and intersection is advantageous due to sets' inherent properties of containing only unique elements and enabling operations based on mathematical set theory. This improves the accuracy by eliminating duplicates and enhances performance because set operations are generally faster for union and intersection due to Python's efficient implementation of hash tables for sets .

Recursion can be used to find the length of a list by defining a function that calls itself, removing the first element of the list on each call, and adding one to the result of the recursive call. This continues until the list is empty, at which point zero is returned, indicating that the end of the list has been reached. This recursive approach is elegant and compact but not the most efficient in terms of time complexity due to the overhead of repeated function calls and Python’s maximum recursion depth limitation .

You might also like