0% found this document useful (0 votes)
6 views19 pages

Area Calculation Methods in Python

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)
6 views19 pages

Area Calculation Methods in Python

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

Practical-1

Method 1: Using If-Else Statements:


import math

def calculate_area():
print("Choose a shape to calculate the area:")
print("1. Triangle")
print("2. Rectangle")
print("3. Circle")
choice = int(input("Enter your choice (1/2/3): "))

if choice == 1:
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height
print(f"The area of the triangle is {area}")
elif choice == 2:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
print(f"The area of the rectangle is {area}")
elif choice == 3:
radius = float(input("Enter the radius of the circle: "))
area = [Link] * (radius ** 2)
print(f"The area of the circle is {area}")
else:
print("Invalid choice!")

calculate_area()
Method 2: Using Separate Functions for Each Shape:
import math

def triangle_area():
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
return 0.5 * base * height

def rectangle_area():
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
return length * width

def circle_area():
radius = float(input("Enter the radius of the circle: "))
return [Link] * (radius ** 2)

def main():
print("Choose a shape to calculate the area:")
print("1. Triangle")
print("2. Rectangle")
print("3. Circle")
choice = int(input("Enter your choice (1/2/3): "))

if choice == 1:
print(f"The area of the triangle is {triangle_area()}")
elif choice == 2:
print(f"The area of the rectangle is {rectangle_area()}")
elif choice == 3:
print(f"The area of the circle is {circle_area()}")
else:
print("Invalid choice!")

main()

Method 3: Using Object-Oriented Programming (OOP):


import math

class Shape:
def area(self):
pass

class Triangle(Shape):
def area(self):
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
return 0.5 * base * height

class Rectangle(Shape):
def area(self):
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
return length * width

class Circle(Shape):
def area(self):
radius = float(input("Enter the radius of the circle: "))
return [Link] * (radius ** 2)

def main():
print("Choose a shape to calculate the area:")
print("1. Triangle")
print("2. Rectangle")
print("3. Circle")
choice = int(input("Enter your choice (1/2/3): "))

if choice == 1:
triangle = Triangle()
print(f"The area of the triangle is {[Link]()}")
elif choice == 2:
rectangle = Rectangle()
print(f"The area of the rectangle is {[Link]()}")
elif choice == 3:
circle = Circle()
print(f"The area of the circle is {[Link]()}")
else:
print("Invalid choice!")

main()
Practical-2
Method 1: Using Sets:
def union_using_sets(list1, list2):
return list(set(list1) | set(list2))

# Example usage
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print("Union (using sets):", union_using_sets(list1, list2))

Method 2: Using Loops and Conditions:


def union_using_loops(list1, list2):
union_list = list1[:] # Create a copy of list1
for item in list2:
if item not in union_list:
union_list.append(item)
return union_list

# Example usage
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print("Union (using loops):", union_using_loops(list1, list2))

Method 3: Using List Comprehension:


def union_using_comprehension(list1, list2):
return list(set([x for x in list1 + list2]))
# Example usage
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print("Union (using comprehension):", union_using_comprehension(list1, list2))
Practical-3
Method 1: Using Sets:
def intersection_using_sets(list1, list2):
return list(set(list1) & set(list2))

# Example usage
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
result = intersection_using_sets(list1, list2)
print("Intersection (using sets):", result)

Method 2: Using Loops and Conditions:


def intersection_using_loops(list1, list2):
intersection_list = []
for item in list1:
if item in list2 and item not in intersection_list: # Check for common elements and
uniqueness
intersection_list.append(item)
return intersection_list

# Example usage
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
result = intersection_using_loops(list1, list2)
print("Intersection (using loops):", result)

Method 3: Using List Comprehension:


def intersection_using_comprehension(list1, list2):
return [x for x in list1 if x in list2 and [Link](x) == 1]

# Example usage
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
result = intersection_using_comprehension(list1, list2)
print
("Intersection (using comprehension):", result)
Practical-4
Method 1: Using a Loop and a Counter:
# Function to remove the i-th occurrence of a word using a loop and a counter
def remove_ith_occurrence_loop(lst, word, i):
print("Original List:", lst)
count = 0 # Initialize a counter
for idx in range(len(lst)):
if lst[idx] == word: # Check if the current element is the target word
count += 1
if count == i: # Check if this is the i-th occurrence
del lst[idx] # Remove the element
print(f"After Removing {i}-th occurrence of '{word}':", lst)
return lst # Return the modified list
print(f"The word '{word}' does not occur {i} times in the list.")
return lst # Return the original list if no changes were made

# Input
words_list = ["apple", "banana", "apple", "cherry", "apple", "date"]
word_to_remove = "apple"
occurrence_to_remove = 3

# Function call
remove_ith_occurrence_loop(words_list, word_to_remove, occurrence_to_remove)

Method 2: Using Enumerate with List Comprehension:


def remove_ith_occurrence_comprehension(lst, word, i):
print("Original List:", lst)
count = 0 # Initialize a counter
new_list = [
item for index, item in enumerate(lst)
if not (item == word and (count := count + 1) == i)
]
if len(new_list) == len(lst):
print(f"The word '{word}' does not occur {i} times in the list.")
else:
print(f"After Removing {i}-th occurrence of '{word}':", new_list)
return new_list

# Input
words_list = ["cat", "dog", "cat", "bird", "cat", "dog"]
word_to_remove = "cat"
occurrence_to_remove = 2

# Function call
remove_ith_occurrence_comprehension(words_list, word_to_remove,
occurrence_to_remove)

Method 3: Using Index and Slicing:


# Function to remove the i-th occurrence of a word using index and slicing
def remove_ith_occurrence_slicing(lst, word, i):
print("Original List:", lst)
count = 0 # Initialize a counter
for idx, item in enumerate(lst):
if item == word: # Check if the current element is the target word
count += 1
if count == i: # Check if this is the i-th occurrence
# Use slicing to create a new list without the target element
new_list = lst[:idx] + lst[idx+1:]
print(f"After Removing {i}-th occurrence of '{word}':", new_list)
return new_list # Return the modified list
print(f"The word '{word}' does not occur {i} times in the list.")
return lst # Return the original list if no changes were made

# Input
words_list = ["pen", "pencil", "pen", "eraser", "pen", "sharpener"]
word_to_remove = "pen"
occurrence_to_remove = 1

# Function call
remove_ith_occurrence_slicing(words_list, word_to_remove, occurrence_to_remove)
Practical-5
Method 1: Using a Dictionary and a Loop.
def count_word_occurrences_loop(sentence):
# Convert the sentence to lowercase for case insensitivity
sentence = [Link]()
# Split the sentence into words
words = [Link]()
# Initialize an empty dictionary to store word counts
word_count = {}

# Iterate through each word in the list


for word in words:
if word in word_count:
word_count[word] += 1 # Increment count if word is already in the dictionary
else:
word_count[word] = 1 # Add the word to the dictionary with a count of 1

# Print the result


print("Word Counts:", word_count)
return word_count

# Example usage
sentence = "Python is great and Python is easy to learn and great to use"
count_word_occurrences_loop(sentence)

Method 2: Using [Link].


from collections import Counter

def count_word_occurrences_counter(sentence):
# Convert the sentence to lowercase for case insensitivity
sentence = [Link]()
# Split the sentence into words
words = [Link]()
# Use Counter to count word frequencies
word_count = Counter(words)

# Print the result


print("Word Counts:", word_count)
return word_count

# Example usage
sentence = "Data science and Python are fascinating and Python is powerful"
count_word_occurrences_counter(sentence)

Method 3: Using a Dictionary with get() Method.


def count_word_occurrences_get(sentence):
# Convert the sentence to lowercase for case insensitivity
sentence = [Link]()
# Split the sentence into words
words = [Link]()
# Initialize an empty dictionary to store word counts
word_count = {}

# Iterate through each word in the list


for word in words:
# Use the get() method to retrieve the current count, defaulting to 0 if not found
word_count[word] = word_count.get(word, 0) + 1

# Print the result


print("Word Counts:", word_count)
return word_count

# Example usage
sentence = "Learning Python is fun and learning new skills is exciting"
count_word_occurrences_get(sentence)
Practical-6
# Importing the regular expressions module
import re

# Method 1: Using 'in' keyword


def check_using_in(main_string, substring):
"""
This method checks if the substring is present using the 'in' keyword.
It returns True if found, otherwise False.
"""
return substring in main_string

# Method 2: Using 'find()' method


def check_using_find(main_string, substring):
"""
This method checks if the substring is present using the 'find()' method.
It returns the index if found, otherwise -1.
"""
return main_string.find(substring)

# Method 3: Using Regular Expressions


def check_using_regex(main_string, substring):
"""
This method checks for substring presence using regular expressions.
It returns True if found, otherwise False.
"""
return bool([Link](substring, main_string))

# Main execution flow


def main():
"""
This function demonstrates all methods in a simple way.
The user provides a main string and a substring to search.
"""
# User input
main_string = input("Enter the main string: ")
substring = input("Enter the substring to search: ")

# Applying methods
in_result = check_using_in(main_string, substring)
find_result = check_using_find(main_string, substring)
regex_result = check_using_regex(main_string, substring)

# Displaying results
print("\nResults:")
print(f"- Using 'in' keyword: {'Present' if in_result else 'Not Present'}")
print(f"- Using 'find()' method: {'Found at index ' + str(find_result) if find_result != -1 else
'Not Present'}")
print(f"- Using regular expressions: {'Present' if regex_result else 'Not Present'}")

# Running the main function


if name == " main ":
main()
Practical-7
# Method 1: Using zip() function
def map_using_zip(keys, values):
"""
This method pairs elements of two lists using zip()
and converts them into a dictionary.
"""
return dict(zip(keys, values))

# Method 2: Using dictionary comprehension


def map_using_dict_comprehension(keys, values):
"""
This method uses dictionary comprehension to iterate
over the indexes of the two lists and map them.
"""
return {keys[i]: values[i] for i in range(len(keys))}

# Method 3: Using a loop-based approach


def map_using_loop(keys, values):
"""
This method creates an empty dictionary and adds
key-value pairs using a loop.
"""
mapped_dict = {}
for i in range(len(keys)):
mapped_dict[keys[i]] = values[i]
return mapped_dict

# Sample lists
keys = ["apple", "banana", "cherry"]
values = [100, 50, 75]

# Applying different methods


dict_zip = map_using_zip(keys, values)
dict_comprehension = map_using_dict_comprehension(keys, values)
dict_loop = map_using_loop(keys, values)

# Display results
print("Using zip():", dict_zip)
print("Using dictionary comprehension:", dict_comprehension)
print("Using loop:", dict_loop)
Practical-8
# Method 1: Using a loop and dictionary
def count_words_loop(text):
"""
This method counts word frequency using a manual loop and dictionary.
"""
word_freq = {} # Initialize an empty dictionary
words = [Link]() # Split text into words

for word in words:


word = [Link]().strip(",.?!") # Convert to lowercase and remove punctuation
word_freq[word] = word_freq.get(word, 0) + 1 # Update count

return word_freq

# Method 2: Using [Link]


from collections import Counter

def count_words_counter(text):
"""
This method uses the Counter module to count word occurrences efficiently.
"""
words = [Link]() # Split text into words
words = [[Link]().strip(",.?!") for word in words] # Preprocess words
return Counter(words)

# Method 3: Using dictionary comprehension


def count_words_dict_comprehension(text):
"""
This method counts words using dictionary comprehension.
"""
words = [Link]() # Split text into words
words = [[Link]().strip(",.?!") for word in words] # Preprocess words
return {word: [Link](word) for word in set(words)}

# Sample text
text = "Hello world! Hello Python world. Python is great, and Python is fun."

# Applying different methods


freq_loop = count_words_loop(text)
freq_counter = count_words_counter(text)
freq_dict_comprehension = count_words_dict_comprehension(text)

# Displaying results
print("Using Loop:", freq_loop)
print("Using Counter:", freq_counter)
print("Using Dictionary Comprehension:", freq_dict_comprehension)

You might also like