Python Internal-2
Python Internal-2
Design a flowchart and write a Python program to calculate the Least Common Multiple (LCM) of two
integers.
PROGRAM:
import math
def calculate_lcm(a,b):
gcd=math.gcd(a,b)
lcm=abs(a*b)//gcd
return lcm
num1=int(input("Enter the first integer:"))
num2=int(input("Enter the second integer:"))
result=calculate_lcm(num1,num2)
print(f"The Least Common Multiple(LCM) of {num1} and {num2} is:{result}")
2. Design a flowchart and write a Python program to compute the HCF of two integers.
PROGRAM:
def compute_hcf(x, y):
while(y):
x, y = y, x % y
return x
# Example usage
num1 = int(input("enter the first number"))
num2 = int(input("enter the second number"))
print("The HCF of", num1, "and", num2, "is", compute_hcf(num1, num2))
3. Develop a program to demonstrate how to store and retrieve data using Python data structures:
tuples, lists, sets, and dictionaries. Implement examples for:
• Adding and removing elements in lists.
• Accessing elements in a tuple.
• Performing set operations like union, intersection, and difference.
• Using a dictionary to store key-value pairs. Compare the advantages and limitations of each data
structure.
PROGRAM:
print("1. Working with Lists") # 1. Working with Lists
fruits = ["apple", "banana", "cherry"] # Create a list
print("Initial list:", fruits)
fruits.append("orange") # Add elements to a list
print("After adding an element:", fruits)
fruits.remove("banana") # Remove elements from a list
print("After removing an element:", fruits)
print("\n")
print("2. Accessing Elements in a Tuple") # 2. Accessing Elements in a Tuple
coordinates = (10, 20, 30) # Create a tuple
print("Tuple:", coordinates)
print("First element:", coordinates[0]) # Access elements in a tuple
print("Second element:", coordinates[1])
print("Third element:", coordinates[2])
print("\n")
print("3. Performing Set Operations") # 3. Performing Set Operations
set_a = {1, 2, 3, 4} # Create two sets
set_b = {3, 4, 5, 6}
print("Set A:", set_a)
print("Set B:", set_b)
union_set = set_a | set_b # Union
print("Union of A and B:", union_set)
intersection_set = set_a & set_b # Intersection
print("Intersection of A and B:", intersection_set)
difference_set = set_a - set_b # Difference
print("Difference of A and B (A - B):", difference_set)
print("\n")
print("4. Using a Dictionary") # 4. Using a Dictionary to Store Key-Value Pairs
student_info = {"name": "Alice", "age": 22, "major": "Computer Science"} # Create a dictionary
print("Initial Dictionary:", student_info)
print("Name:", student_info["name"]) # Access a value
student_info["GPA"] = 3.8 # Add a new key-value pair
print("After adding a new key-value pair:", student_info)
del student_info["age"] # Remove a key-value pair
print("After removing a key-value pair:", student_info)
print("\n")
print("Advantages and Limitations of Each Data Structure") # Advantages and Limitations of Each Data
Structure
print("Lists:") # Lists
print("Advantages: Ordered, allows duplicates, dynamic sizing, and supports indexing and slicing.")
print("Limitations: Less efficient for membership checks, and no enforced uniqueness of elements.\n")
print("Tuples:") # Tuples
print("Advantages: Immutable (useful for fixed data), ordered, and supports indexing.")
print("Limitations: Cannot add or remove elements after creation, less flexible than lists.\n")
print("Sets:") # Sets
print("Advantages: Unordered, no duplicates, fast membership checks, and supports set operations
(union,intersection, etc.).")
print("Limitations: Unordered (no indexing or slicing), and elements must be hashable.\n")
print("Dictionaries:") # Dictionaries
print("Advantages: Key-value storage, fast lookup by key, and flexible for a variety of data types.")
print("Limitations: Unordered (prior to Python 3.7), keys must be unique and hashable.\n")
5.Write a program using list comprehensions to generate lists based on certain conditions, such as:
• Generating a list of squares of even numbers between 1 and 20.
• Filtering a list of strings based on whether they start with a specific letter.
PROGRAM:
# 1. Generating a list of squares of even numbers between 1 and 20
squares_of_even_numbers = [x**2 for x in range(1, 21) if x % 2 == 0]
print("Squares of even numbers between 1 and 20:", squares_of_even_numbers)
# 2. Filtering a list of strings based on whether they start with a specific letter
# Example list of strings
words = ["apple", "banana", "avocado", "cherry", "apricot", "blueberry", "almond"]
# Filter words that start with 'a'
filtered_words = [word for word in words if word.startswith("a")]
print("Words starting with 'a':", filtered_words)
filtered_words1 = [word for word in words if word.startswith("b")]
print("Words starting with 'b':", filtered_words1)
7. Develop a program using lambda functions to: Sort a list of tuples based on specific criteria. Filter a list
of numbers to retain only those greater than a certain value.
PROGRAM:
# Program using lambda functions for sorting and filtering
# 1. Sort a list of tuples based on the second element in each tuple
tuples_list = [(1, 3), (4, 1), (2, 5), (3, 2)]
print("Original list of tuples:", tuples_list)
# Sorting tuples by the second element in each tuple
sorted_tuples = sorted(tuples_list, key=lambda x: x[1])
print("Tuples sorted by the second element:", sorted_tuples)
# 2. Filter a list of numbers to retain only those greater than a certain value
numbers_list = [10, 25, 37, 2, 89, 5, 12]
threshold = 20
print("\nOriginal list of numbers:", numbers_list)
# Filtering numbers greater than the threshold
filtered_numbers = list(filter(lambda x: x > threshold, numbers_list))
print(f"Numbers greater than {threshold}:", filtered_numbers)
8. Write a program that demonstrates variable lifetime by defining local and global variables within and
outside of functions. Show how global variables retain their values across function calls.
PROGRAM:
# Global variable to demonstrate global scope and lifetime
global_count = 0 # This variable will retain its value across function calls
# Function to demonstrate a local variable's lifetime
def increment_local():
# Local variable
local_count = 0 # This variable is recreated each time the function is called
local_count += 1
print(f"Local count inside increment_local function: {local_count}")
# Function to demonstrate a global variable's lifetime
def increment_global():
global global_count # Referencing the global variable
global_count += 1
print(f"Global count inside increment_global function: {global_count}")
# Main program
print("Demonstrating Variable Lifetime\n")
# Calling the function with local variable multiple times
print("Calling increment_local multiple times:")
increment_local()
increment_local()
increment_local()
print("Notice that the local variable does not retain its value across calls.\n")
# Calling the function with global variable multiple times
print("Calling increment_global multiple times:")
increment_global()
increment_global()
increment_global()
print("Notice that the global variable retains its value across calls.\n")
# Checking the global variable value outside of functions
print(f"Global count outside functions: {global_count}")
9. Develop a function for a math app that calculates the factorial of a number. Additionally, implement a
recursive function to generate the nth Fibonacci number.
PROGRAM:
# Function to calculate the factorial of a number
def factorial(n):
"""Return the factorial of n."""
if n < 0:
return "Factorial is not defined for negative numbers."
elif n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
# Recursive function to calculate the nth Fibonacci number
def fibonacci(n):
"""Return the nth Fibonacci number using recursion."""
if n <= 0:
return "Fibonacci number is not defined for negative or zero index."
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
# Main Program to test the functions
number = 5
print(f"Factorial of {number}: {factorial(number)}")
n = 10
print(f"{n}th Fibonacci number: {fibonacci(n)}")
10. Implement a binary search algorithm to find a specific product in a sorted list of prices for a shopping
app. Discuss the efficiency of this approach for large datasets.
def binary_search(prices, target):
"""Return the index of target in prices list if found, otherwise return -1."""
left, right = 0, len(prices) - 1
while left <= right:
mid = (left + right) // 2 # Calculate the middle index
mid_value = prices[mid]
# Check if the mid value is equal to the target
if mid_value == target:
return mid
# If target is smaller, ignore the right half
elif mid_value > target:
right = mid - 1
# If target is larger, ignore the left half
else:
left = mid + 1
return -1 # Target not found
# Main Program
prices = [5, 12, 18, 24, 32, 45, 56, 67, 78, 89, 99] # Sorted list of product prices
target_price = 45
# Perform binary search
index = binary_search(prices, target_price)
# Display result
if index != -1:
print(f"Price {target_price} found at index {index}.")
else:
print(f"Price {target_price} not found in the list.")