0% found this document useful (0 votes)
19 views6 pages

Python Internal-2

Uploaded by

balupersonal224
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views6 pages

Python Internal-2

Uploaded by

balupersonal224
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

1.

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")

4. Develop a program that uses set operations to demonstrate:


• Union (combining two sets of data).
• Intersection (finding common elements between sets).
• Difference (elements unique to one set). Include functionality for dynamically adding and removing
items from the sets.
PROGRAM:
set_A = {1, 2, 3, 4, 5} # Initialize two sets
set_B = {4, 5, 6, 7, 8}
def display_sets(): # Function to display sets
print("Set A:", set_A)
print("Set B:", set_B)
print("\n")
def add_item(target_set, item): # Function to add items to a set
target_set.add(item)
print(f"Item '{item}' added to the set.")
display_sets()
def remove_item(target_set, item): # Function to remove items from a set
if item in target_set:
target_set.remove(item)
print(f"Item '{item}' removed from the set.")
else:
print(f"Item '{item}' not found in the set.")
display_sets()
def perform_union(): # Function to perform union
result = set_A | set_B
print("Union of Set A and Set B:", result)
print("\n")
def perform_intersection(): # Function to perform intersection
result = set_A & set_B
print("Intersection of Set A and Set B:", result)
print("\n")
def perform_difference(): # Function to perform difference (Set A - Set B and Set B - Set A)
diff_A_B = set_A - set_B
diff_B_A = set_B - set_A
print("Difference (Set A - Set B):", diff_A_B)
print("Difference (Set B - Set A):", diff_B_A)
print("\n")
print("Initial Sets:") # Main program
display_sets()
print("Adding items to sets:") # Adding items to sets
add_item(set_A, 9)
add_item(set_B, 10)
print("Removing items from sets:") # Removing items from sets
remove_item(set_A, 3)
remove_item(set_B, 7)
print("Performing Set Operations:") # Performing set operations
perform_union()
perform_intersection()
perform_difference()

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)

6. Create a program that defines several functions to perform tasks like:


• Calculating the area of a rectangle.
• Finding the maximum of a list of numbers.
• Printing personalized greetings. Demonstrate variable scope by modifying variables inside and outside
functions.
PROGRAM:
global_greeting = "Hello from the global scope!" # Global variable to demonstrate scope
def calculate_area(length, width): # Function to calculate the area of a rectangle
area = length * width # Local variable inside the function
print(f"Inside calculate_area - Area: {area}")
return area
def find_max(numbers): # Function to find the maximum in a list of numbers
max_value = max(numbers) # Local variable inside the function
print(f"Inside find_max - Max Value: {max_value}")
return max_value
def print_greeting(name): # Function to print a personalized greeting
global global_greeting # Accessing a global variable inside a function
print(global_greeting) # Uses the global variable
local_greeting = f"Hello, {name}!" # Local variable
print(f"Inside print_greeting - Local Greeting: {local_greeting}")
global_greeting = f"Hello, {name}! (updated globally)" # Modify the global variable
print(f"Inside print_greeting - Global Greeting Updated: {global_greeting}")
# Main Program
# Outside any function, in global scope
print("Demonstration of Variable Scope\n")
# 1. Calculate the area of a rectangle
length = 5
width = 3
area_result = calculate_area(length, width)
print(f"Outside calculate_area - Area Result: {area_result}\n")
# 2. Find the maximum in a list of numbers
numbers = [10, 25, 37, 2, 89]
max_result = find_max(numbers)
print(f"Outside find_max - Max Result: {max_result}\n")
# 3. Print personalized greetings and modify global variable
name = "Siddhartha"
print_greeting(name)
print(f"Outside print_greeting - Global Greeting After Update: {global_greeting}\n")

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.")

You might also like