1.
Write a program in Python programming and save it as
firstProgram.py to perform the following operations 2 + 3, 5*3, 7-2,
6/2, 6/4, 6%4, 6%2
# Addition
result1 = 2 + 3
print("2 + 3 =", result1)
# Multiplication
result2 = 5 * 3
print("5 * 3 =", result2)
# Subtraction
result3 = 7 - 2
print("7 - 2 =", result3)
# Division (floating-point)
result4 = 6 / 2
print("6 / 2 =", result4)
# Division (integer)
result5 = 6 // 4
print("6 // 4 =", result5)
# Modulus (remainder when divided by 4)
result6 = 6 % 4
print("6 % 4 =", result6)
# Modulus (remainder when divided by 2)
result7 = 6 % 2
print("6 % 2 =", result7)
2- 2.Write a program in Python programming and save it as
secondProgram.py to display the following messages:
• “Hello World, I am studying Data Science using Python”
• “ Guido Van Rossum invented the Python programming language
print("Hello World, I am studying Data Science using Python") # Display the second message
print("Guido Van Rossum invented the Python programming language.")
3- 3. Write a program to read five integers from user and find the
average
# Initialize a variable to store the sum of the integers
sum_of_integers = 0
# Read five integers from the user and add them to the sum
for i in range(5):
num = int(input(f"Enter integer {i + 1}: "))
sum_of_integers += num
# Calculate the average
average = sum_of_integers / 5
# Display the average
print(f"The average of the five integers is: {average}")
4. Write a program to read five real numbers from user and
find the average and standard deviation (use math
module)
# Initialize a variable to store the sum of the integers
sum_of_integers = 0
# Read five integers from the user and add them to the sum
for i in range(5):
num = int(input(f"Enter integer {i + 1}: "))
sum_of_integers += num
# Calculate the average
average = sum_of_integers / 5
# Display the average
print(f"The average of the five integers is: {average}")
5-Write a program to read an integer and use bitwise operators to
multiply it by 2 ( << operator ).
# Read an integer from the user
try:
num = int(input("Enter an integer: "))
# Multiply the integer by 2 using the left shift operator (<<)
result = num << 1
# Display the result
print(f"{num} multiplied by 2 is: {result}")
except ValueError:
print("Invalid input. Please enter a valid integer.")
6-Write a program to read an integer and use bitwise operators to
divide it by 4 (>> operator ).
# Read an integer from the user
try:
num = int(input("Enter an integer: "))
# Divide the integer by 4 using the right shift operator (>>)
result = num >> 2
# Display the result
print(f"{num} divided by 4 is: {result}")
except ValueError:
print("Invalid input. Please enter a valid integer.")
➢
7- Write a program to read the values of two integer variables and
use bitwise operators to exchange the values of the variables
(^ operator).
6# Read two integers from the user
try:
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
# Exchange the values of the variables using XOR (^) operator
num1 = num1 ^ num2
num2 = num1 ^ num2
num1 = num1 ^ num2
# Display the exchanged values
print(f"Exchanged values: First integer: {num1}, Second integer: {num2}")
except ValueError:
print("Invalid input. Please enter valid integers.")
8-Write a program to read an integer and use bitwise operators to check the
nature (even or odd) of the integer.
➢ Property:
➢ The binary representation of every odd integer consists of 1 at
the rightmost position.
➢ The binary representation of every even integer consists of 0 at
the rightmost position.
# Read an integer from the user
try:
num = int(input("Enter an integer: "))
# Use bitwise AND operator to check the rightmost bit
if num & 1 == 0:
print(f"{num} is an even integer.")
else:
print(f"{num} is an odd integer.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
9-Write a program to find the maximum of three numbers.
➢ If-elif-else statement
# Read three numbers from the user
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
# Compare the numbers to find the maximum
if num1 >= num2 and num1 >= num3:
max_num = num1
elif num2 >= num1 and num2 >= num3:
max_num = num2
else:
max_num = num3
# Display the maximum number
print(f"The maximum of {num1}, {num2}, and {num3} is {max_num}")
except ValueError:
print("Invalid input. Please enter valid numbers.")
10-Write a program to read the values of two points on x-y plane and find
out the distance between two points.
➢ Use math functions (sqrt, pow)
import math
# Read the coordinates of the two points from the user
try:
x1 = float(input("Enter the x-coordinate of the first point: "))
y1 = float(input("Enter the y-coordinate of the first point: "))
x2 = float(input("Enter the x-coordinate of the second point: "))
y2 = float(input("Enter the y-coordinate of the second point: "))
# Calculate the distance using the distance formula
distance = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2))
# Display the distance
print(f"The distance between ({x1}, {y1}) and ({x2}, {y2}) is {distance:.2f}")
except ValueError:
print("Invalid input. Please enter valid coordinates.")
11-Write a program to compute the factorial of an integer (use loop)
# Read an integer from the user
# Read an integer from the user
try:
n = int(input("Enter an integer: "))
# Initialize the factorial to 1
factorial = 1
# Compute the factorial using a loop
for i in range(1, n + 1):
factorial *= i
# Display the factorial
print(f"The factorial of {n} is {factorial}")
except ValueError:
print("Invalid input. Please enter a valid integer.")
try:
n = int(input("Enter an integer: "))
# Initialize the factorial to 1
factorial = 1
# Compute the factorial using a loop
for i in range(1, n + 1):
factorial *= i
# Display the factorial
print(f"The factorial of {n} is {factorial}")
except ValueError:
print("Invalid input. Please enter a valid integer.")
12-Write a program to check whether the integer is prime or find its first factor
# Read an integer from the user
try:
num = int(input("Enter an integer: "))
# Check if the number is less than 2
if num < 2:
print(f"{num} is not a prime number.")
else:
# Find the first factor (if any)
first_factor = None
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
first_factor = i
break
# Check if a factor was found
if first_factor is None:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number. Its first factor is {first_factor}.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
13-Write a program to find the GCD of two numbers.
➢ Use Euclid’s Algorithm
# Function to find the GCD using Euclid's Algorithm
def gcd(a, b):
while b:
a, b = b, a % b
return a
# Read two integers from the user
try:
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
# Calculate and display the GCD
result = gcd(num1, num2)
print(f"The GCD of {num1} and {num2} is: {result}")
except ValueError:
print("Invalid input. Please enter valid integers.")
14-Write a Python function to calculate the factorial of a number (a nonnegative integer).
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers."
elif n == 0:
return 1
else:
return n * factorial(n - 1)
# Read an integer from the user
try:
num = int(input("Enter a non-negative integer: "))
# Calculate and display the factorial
result = factorial(num)
print(f"The factorial of {num} is: {result}")
except ValueError:
print("Invalid input. Please enter a valid non-negative integer.")
15-Write a Python function to calculate the sum of digits of a given integer
def sum_of_digits(n):
# Initialize the sum
digit_sum = 0
# Ensure the number is positive
n = abs(n)
# Calculate the sum of digits
while n > 0:
digit = n % 10
digit_sum += digit
n //= 10
return digit_sum
# Read an integer from the user
try:
num = int(input("Enter an integer: "))
# Calculate and display the sum of digits
result = sum_of_digits(num)
print(f"The sum of digits of {num} is: {result}")
except ValueError:
print("Invalid input. Please enter a valid integer.")
16-Write a Python function to check whether a given number is a prime number or not
def is_prime(number):
if number <= 1:
return False
if number <= 3:
return True
if number % 2 == 0 or number % 3 == 0:
return False
i=5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6
return True
# Read an integer from the user
try:
num = int(input("Enter an integer: "))
# Check if the number is prime and display the result
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
17-Write a Python function that accepts a string and calculates the number of
upper case letters and lower case letters. (Use isupper(), islower(), upper(),
lower() functions)
def count_upper_lower(string):
upper_count = 0
lower_count = 0
for char in string:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
return upper_count, lower_count
# Read a string from the user
input_string = input("Enter a string: ")
# Calculate the counts of uppercase and lowercase letters
upper_count, lower_count = count_upper_lower(input_string)
# Display the results
print(f"Uppercase letters: {upper_count}")
print(f"Lowercase letters: {lower_count}")
18-Write a function to add arbitrary integers
def add_integers(*args):
result = 0
for num in args:
result += num
return result
# Example usage:
sum_result = add_integers(5, 10, 15, 20)
print(f"The sum is: {sum_result}")
18-Write a function to receive multiple strings and count total characters.
def count_total_characters(*args):
total_characters = 0
for string in args:
total_characters += len(string)
return total_characters
# Example usage:
strings = ["Hello", "World", "Python"]
total_chars = count_total_characters(*strings)
print(f"The total number of characters is: {total_chars}")
18-Write a function to receive multiple strings and count total characters.
def count_total_characters(*args):
total_characters = 0
for string in args:
total_characters += len(string)
return total_characters
# Example usage:
strings = ["Hello", "World", "Python"]
total_chars = count_total_characters(*strings)
print(f"The total number of characters is: {total_chars}")
19-Write a Python program that first accept a string and If the string length is less
than 2, return empty string. Then create a string made of the first 2 and the last
2 chars from the accepted string. Sample String : ‘Computer Science'
Expected Result : ‘Coce'
Sample String : ‘My'
Expected Result : ‘MyMy'
Sample String : ' w'
Expected Result : Empty String
def make_new_string(input_string):
if len(input_string) < 2:
return ""
new_string = input_string[:2] + input_string[-2:]
return new_string
# Read a string from the user
input_string = input("Enter a string: ")
# Call the function and display the result
result = make_new_string(input_string)
print(f"Expected Result: '{result}'")
20-Write a Python program to get a string from a given string where all occurrences of its first char
have been changed to ‘#', except the first char itself. Sample String : 'restart' Expected Result : 'resta#t
def replace_first_char_occurrences(input_string):
if len(input_string) < 2:
return input_string
first_char = input_string[0]
modified_string = first_char + input_string[1:].replace(first_char, '#')
return modified_string
# Read a string from the user
input_string = input("Enter a string: ")
# Call the function and display the result
result = replace_first_char_occurrences(input_string)
print(f"Expected Result: '{result}'")
21-Write a Python program to get a single string from two given strings, separated by a space and swap the
first two characters of each string. Sample String : 'abc', 'xyz' Expected Result : 'xyc abz
def make_new_string(input_string):
if len(input_string) < 2:
return ""
new_string = input_string[:2] + input_string[-2:]
return new_string
# Read a string from the user
input_string = input("Enter a string: ")
# Call the function and display the result
result = make_new_string(input_string)
print(f"Expected Result: '{result}'")
def swap_first_two_chars(str1, str2):
if len(str1) >= 2 and len(str2) >= 2:
new_str1 = str2[:2] + str1[2:]
new_str2 = str1[:2] + str2[2:]
return new_str1 + ' ' + new_str2
else:
return str1 + ' ' + str2
# Read two strings from the user
string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")
# Call the function and display the result
result = swap_first_two_chars(string1, string2)
print(f"Expected Result: '{result}'")
22-Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given
string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it
unchanged. Sample String : ‘Giv' Expected Result : ‘Giving' Sample String : 'string' Expected Result : 'stringly’ •
Sample String : 'st’ Expected Result : ‘st
def modify_string(input_string):
if len(input_string) < 3:
return input_string
elif input_string.endswith('ing'):
return input_string + 'ly'
else:
return input_string + 'ing'
# Read a string from the user
input_string = input("Enter a string: ")
# Call the function and display the result
result = modify_string(input_string)
print(f"Expected Result: '{result}'")
23-Given a list containing characters and numbers, the task is to add only numbers from a list (Use
isinstance() function ).
# Function to add only numbers from a list
def add_numbers(numbers_list):
result = 0
for item in numbers_list:
if isinstance(item, (int, float)):
result += item
return result
# Example list containing characters and numbers
mixed_list = [1, 'a', 2.5, 'b', 3, 'c']
# Call the function to add numbers and display the result
sum_of_numbers = add_numbers(mixed_list)
print(f"The sum of numbers in the list is: {sum_of_numbers}")
24-Given a list of numbers, write a Python program to check if the list
contains consecutive int
# Function to add only numbers from a list
def add_numbers(numbers_list):
result = 0
for item in numbers_list:
if isinstance(item, (int, float)):
result += item
return result
# Example list containing characters and numbers
mixed_list = [1, 'a', 2.5, 'b', 3, 'c']
# Call the function to add numbers and display the result
sum_of_numbers = add_numbers(mixed_list)
print(f"The sum of numbers in the list is: {sum_of_numbers}")
25-Given a list containing characters and numbers, the task is to add only numbers from a list (Use
isinstance() function ).
# Function to add only numbers from a list
def add_numbers(numbers_list):
result = 0
for item in numbers_list:
if isinstance(item, (int, float)):
result += item
return result
# Example list containing characters and numbers
mixed_list = [1, 'a', 2.5, 'b', 3, 'c']
# Call the function to add numbers and display the result
sum_of_numbers = add_numbers(mixed_list)
print(f"The sum of numbers in the list is: {sum_of_numbers}")
26-Python Program to Put Even and Odd elements in a List into Two Different Lists
# Function to separate even and odd elements into two lists
def separate_even_odd(input_list):
even_list = []
odd_list = []
for item in input_list:
if item % 2 == 0:
even_list.append(item)
else:
odd_list.append(item)
return even_list, odd_list
# Example list of numbers
numbers_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Call the function to separate even and odd elements
even_numbers, odd_numbers = separate_even_odd(numbers_list)
# Display the results
print("Even numbers:", even_numbers)
print("Odd numbers:", odd_numbers)
27-Python Program to Merge Two Lists and Sort it
# Function to merge and sort two lists
def merge_and_sort_lists(list1, list2):
merged_list = list1 + list2
merged_list.sort()
return merged_list
# Example lists
list1 = [3, 1, 4, 1, 5, 9]
list2 = [2, 6, 5, 3, 5, 8]
# Call the function to merge and sort the lists
result = merge_and_sort_lists(list1, list2)
# Display the sorted merged list
print("Merged and sorted list:", result)
28-Python Program to Find the Second Largest Number in a List Using Bubble Sort
# Function to find the second largest number using Bubble Sort
def find_second_largest(numbers):
n = len(numbers)
# Check if the list has at least two elements
if n < 2:
return "List should have at least two elements."
# Perform Bubble Sort
for i in range(n - 1):
for j in range(n - i - 1):
if numbers[j] > numbers[j + 1]:
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
# The second largest number will be at the second-to-last index
return numbers[-2]
# Example list of numbers
numbers_list = [12, 45, 67, 23, 41, 5, 89, 38]
# Call the function to find the second largest number
result = find_second_largest(numbers_list)
# Display the result
print("The second largest number is:", result)
29-program to Sort a List According to the Length of the Elements
# Function to sort a list according to the length of elements
def sort_by_length(input_list):
sorted_list = sorted(input_list, key=len)
return sorted_list
# Example list of strings
string_list = ["apple", "banana", "cherry", "date", "elderberry"]
# Call the function to sort by length
sorted_strings = sort_by_length(string_list)
# Display the sorted list
print("Sorted list by length:", sorted_strings)
30-Python Program to Find the Union of two Lists
# Function to find the union of two lists
def find_union(list1, list2):
# Convert the lists to sets to remove duplicates, then convert back to lists
union_list = list(set(list1) | set(list2))
return union_list
# Example lists
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
# Call the function to find the union
union_result = find_union(list1, list2)
# Display the union of the two lists
print("Union of the two lists:", union_result)
30-Python Program to Find the Intersection of Two Lists
# Function to find the intersection of two lists
def find_intersection(list1, list2):
# Convert the lists to sets to perform intersection
intersection_set = set(list1) & set(list2)
intersection_list = list(intersection_set)
return intersection_list
# Example lists
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
# Call the function to find the intersection
intersection_result = find_intersection(list1, list2)
# Display the intersection of the two lists
print("Intersection of the two lists:", intersection_result)
31-Python Program to Create a List of Tuples with the First Element as the Number and Second Element
as the Square of the Number
# Function to create a list of tuples with number and its square
def create_tuple_list(n):
tuple_list = [(x, x ** 2) for x in range(1, n + 1)]
return tuple_list
# Example: Create a list of tuples for numbers from 1 to 5
n=5
result = create_tuple_list(n)
# Display the list of tuples
print("List of tuples with number and its square:")
for item in result:
print(item)
32-You can create a Python program to find the cumulative sum of a list, where the ith element in the
result is the sum of the first i elements from the original list. Here's a program to do that:
# Function to calculate the cumulative sum of a list
def cumulative_sum(input_list):
cum_sum = []
current_sum = 0
for num in input_list:
current_sum += num
cum_sum.append(current_sum)
return cum_sum
# Example list of numbers
numbers_list = [1, 2, 3, 4, 5]
# Call the function to calculate the cumulative sum
cumulative_result = cumulative_sum(numbers_list)
# Display the cumulative sum
print("Cumulative sum of the list:")
print(cumulative_result)
33-Python Program to Generate Random integers from 1 to 20 and append them to
the List
import random
# Function to generate random integers and append them to a list
def generate_random_numbers(n):
random_numbers = [random.randint(1, 20) for _ in range(n)]
return random_numbers
# Example: Generate 5 random integers and append them to a list
n=5
random_numbers_list = generate_random_numbers(n)
# Display the list of random integers
print("Random integers from 1 to 20:")
print(random_numbers_list)
34-Python Program to Remove the Duplicate Items from a List
# Function to remove duplicate items from a list
def remove_duplicates(input_list):
# Convert the list to a set to remove duplicates, then convert back to a list
unique_list = list(set(input_list))
return unique_list
# Example list with duplicate items
original_list = [1, 2, 2, 3, 4, 4, 5, 6, 6]
# Call the function to remove duplicates
unique_items = remove_duplicates(original_list)
# Display the list with duplicate items removed
print("List with duplicate items removed:")
print(unique_items)
35-Python Program to Find Element Occurring Odd Number of Times in a List
# Function to find the element occurring odd number of times
def find_odd_occurrence(input_list):
element_count = {}
# Count the occurrences of each element in the list
for element in input_list:
if element in element_count:
element_count[element] += 1
else:
element_count[element] = 1
# Find the element with an odd count
for element, count in element_count.items():
if count % 2 != 0:
return element
return None # Return None if no such element is found
# Example list with an element occurring an odd number of times
input_list = [1, 2, 3, 2, 3, 1, 3]
# Call the function to find the element
odd_element = find_odd_occurrence(input_list)
# Display the element occurring odd number of times
if odd_element is not None:
print(f"Element occurring odd number of times: {odd_element}")
else:
print("No element occurring odd number of times found.")
36-Python Program to Read a List of Words and Return the Length of the Longest One
# Function to find the length of the longest word in a list
def find_longest_word_length(word_list):
if not word_list:
return 0 # Return 0 if the list is empty
max_length = len(word_list[0]) # Initialize with the length of the first word
for word in word_list:
if len(word) > max_length:
max_length = len(word)
return max_length
# Example list of words
word_list = ["apple", "banana", "cherry", "date", "elderberry"]
# Call the function to find the length of the longest word
longest_word_length = find_longest_word_length(word_list)
# Display the length of the longest word
print("Length of the longest word:", longest_word_length)
37-PythonProgram to solve Maximum Subarray Problem using Kadane’s
Algorithm
def max_subarray(arr):
if not arr:
return 0
max_sum = arr[0] # Initialize with the first element
current_sum = arr[0]
for num in arr[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
# Example list of numbers
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
# Call the function to find the maximum subarray sum
max_sum = max_subarray(nums)
# Display the maximum subarray sum
print("Maximum subarray sum:", max_sum)
38-Write a Python program to unpack a tuple in several variables.
# Define a tuple
my_tuple = (1, 2, 3, 4, 5)
# Unpack the tuple into separate variables
var1, var2, var3, var4, var5 = my_tuple
# Display the values of the variables
print("var1:", var1)
print("var2:", var2)
print("var3:", var3)
print("var4:", var4)
print("var5:", var5)
39- Write a Python program to find the repeated items of a tuple
# Function to find repeated items in a tuple
def find_repeated_items(input_tuple):
repeated_items = []
seen_items = set()
for item in input_tuple:
if item in seen_items:
if item not in repeated_items:
repeated_items.append(item)
else:
seen_items.add(item)
return repeated_items
# Example tuple with repeated items
my_tuple = (1, 2, 2, 3, 4, 4, 5, 5, 6)
# Call the function to find repeated items
repeated_items = find_repeated_items(my_tuple)
# Display the repeated items
print("Repeated items in the tuple:", repeated_items)
40-Write a Python program to find the index of an item in a tuple
# Function to find the index of an item in a tuple
def find_item_index(input_tuple, item):
try:
index = input_tuple.index(item)
return index
except ValueError:
return None
# Example tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7)
# Item to find the index of
item_to_find = 4
# Call the function to find the index
index = find_item_index(my_tuple, item_to_find)
if index is not None:
print(f"The index of {item_to_find} in the tuple is: {index}")
else:
print(f"{item_to_find} is not found in the tuple.")
41-Write a Python program to remove an empty tuple(s) from a list of
tuples.
# Function to find the index of an item in a tuple
def find_item_index(input_tuple, item):
try:
index = input_tuple.index(item)
return index
except ValueError:
return None
# Example tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7)
# Item to find the index of
item_to_find = 4
# Call the function to find the index
index = find_item_index(my_tuple, item_to_find)
if index is not None:
print(f"The index of {item_to_find} in the tuple is: {index}")
else:
print(f"{item_to_find} is not found in the tuple.")
42-Write a Python program to remove an empty tuple(s) from a list of tuple
# Function to remove empty tuples from a list of tuples
def remove_empty_tuples(tuple_list):
non_empty_tuples = [t for t in tuple_list if t]
return non_empty_tuples
# Example list of tuples
list_of_tuples = [(1, 2), (), (3, 4), (), (5, 6), ()]
# Call the function to remove empty tuples
result = remove_empty_tuples(list_of_tuples)
# Display the list without empty tuples
print("List of tuples without empty tuples:")
print(result)
43-Write a Python program to add and remove item(s) from set
# Create an empty set
my_set = set()
# Add items to the set using the add() method
my_set.add(1)
my_set.add(2)
my_set.add(3)
# Display the set
print("Set after adding items:", my_set)
# Remove an item from the set using the remove() method
my_set.remove(2)
# Display the set after removal
print("Set after removing an item:", my_set)
# Remove an item from the set using the discard() method (if it exists)
my_set.discard(4)
# Display the set after discard
print("Set after discarding an item:", my_set)
44-Write a Python program to remove an item from a set if it is present in the set.
# Create a set
my_set = {1, 2, 3, 4, 5}
# Item to remove (if it exists)
item_to_remove = 3
# Use the discard() method to remove the item if it's present
my_set.discard(item_to_remove)
# Display the set after removal (no error if the item is not present)
print("Set after removing item (if present):", my_set)
46-Write a Python program to create an intersection, union difference
and symmetric difference of two sets
# Create two sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# Intersection of two sets
intersection = set1.intersection(set2)
print("Intersection of set1 and set2:", intersection)
# Union of two sets
union = set1.union(set2)
print("Union of set1 and set2:", union)
# Difference between set1 and set2
difference = set1.difference(set2)
print("Difference between set1 and set2:", difference)
# Symmetric difference between set1 and set2
symmetric_difference = set1.symmetric_difference(set2)
print("Symmetric difference between set1 and set2:", symmetric_difference)
47-Write a Python program to create a shallow copy of sets.
# Create a set
original_set = {1, 2, 3, 4, 5}
# Create a shallow copy of the set using the copy() method
shallow_copy_method = original_set.copy()
# Create a shallow copy of the set using the set() constructor
shallow_copy_constructor = set(original_set)
# Add an element to the original set to see the difference
original_set.add(6)
# Display the original set and its shallow copies
print("Original Set:", original_set)
print("Shallow Copy (copy() method):", shallow_copy_method)
print("Shallow Copy (set() constructor):", shallow_copy_constructor)
48-Write a Python program to create a shallow copy of sets.
# Create a set
original_set = {1, 2, 3, 4, 5}
# Create a shallow copy of the set using the copy() method
shallow_copy_method = original_set.copy()
# Create a shallow copy of the set using the set() constructor
shallow_copy_constructor = set(original_set)
# Add an element to the original set to see the difference
original_set.add(6)
# Display the original set and its shallow copies
print("Original Set:", original_set)
print("Shallow Copy (copy() method):", shallow_copy_method)
print("Shallow Copy (set() constructor):", shallow_copy_constructor)
49-Write a Python program to create a deepcopy of set
import copy
# Create a dictionary containing sets
original_dict = {
'set1': {1, 2, 3},
'set2': {4, 5, 6}
# Create a deep copy of the dictionary
deep_copy_dict = copy.deepcopy(original_dict)
# Add an element to one of the sets in the original dictionary
original_dict['set1'].add(4)
# Display the original dictionary and its deep copy
print("Original Dictionary:", original_dict)
print("Deep Copy Dictionary:", deep_copy_dict)
50-Write a Python script to sort (ascending and descending) a dictionary by value
# Sample dictionary
sample_dict = {'apple': 3, 'banana': 1, 'cherry': 2, 'date': 4}
# Sorting the dictionary by values in ascending order
ascending_sorted_dict = dict(sorted(sample_dict.items(), key=lambda item: item[1]))
# Sorting the dictionary by values in descending order
descending_sorted_dict = dict(sorted(sample_dict.items(), key=lambda item: item[1],
reverse=True))
# Printing the sorted dictionaries
print("Ascending Sorted Dictionary:")
for key, value in ascending_sorted_dict.items():
print(f"{key}: {value}")
print("\nDescending Sorted Dictionary:")
for key, value in descending_sorted_dict.items():
print(f"{key}: {value}")
51-Write a Python script to concatenate three dictionaries to create a new one
# Define three dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'e': 5, 'f': 6}
# Method 1: Using the update method
concatenated_dict1 = dict1.copy()
concatenated_dict1.update(dict2)
concatenated_dict1.update(dict3)
# Method 2: Using the {**d1, **d2, **d3} syntax
concatenated_dict2 = {**dict1, **dict2, **dict3}
# Printing the concatenated dictionaries
print("Concatenated Dictionary (Method 1):")
print(concatenated_dict1)
print("\nConcatenated Dictionary (Method 2):")
print(concatenated_dict2)
52-Write a Python script to merge two Python dictionaries
# Define two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Method 1: Using the `update` method
merged_dict1 = dict1.copy()
merged_dict1.update(dict2)
# Method 2: Using dictionary unpacking (Python 3.5 and later)
merged_dict2 = {**dict1, **dict2}
# Printing the merged dictionaries
print("Merged Dictionary (Method 1):")
print(merged_dict1)
print("\nMerged Dictionary (Method 2):")
print(merged_dict2)
53-Write a Python script to create a dictionary where the keys are numbers between 1 and 15 (both included) and
the values are square of keys.
# Create an empty dictionary
square_dict = {}
# Populate the dictionary with keys and their squares
for num in range(1, 16):
square_dict[num] = num ** 2
# Printing the resulting dictionary
print(square_dict)
53-Write a Python program to remove duplicates values from Dictionary
# Function to remove duplicate values from a dictionary
def remove_duplicate_values(input_dict):
# Create an empty dictionary to store unique values
unique_dict = {}
# Iterate through the original dictionary
for key, value in input_dict.items():
# Check if the value is not already in the unique_dict
if value not in unique_dict.values():
# Add the key-value pair to the unique_dict
unique_dict[key] = value
return unique_dict
# Example dictionary with duplicate values
original_dict = {'a': 1, 'b': 2, 'c': 1, 'd': 3, 'e': 2}
# Remove duplicates from the dictionary
result_dict = remove_duplicate_values(original_dict)
# Print the result
print("Original Dictionary:")
print(original_dict)
print("\nDictionary after Removing Duplicates:")
print(result_dict)
54-Write a python program to maintain information about each student of Bsc-II.
# Initialize an empty list to store student information
student_records = []
# Function to add a new student's information
def add_student_info():
student_info = {}
student_info['roll_number'] = input("Enter Roll Number: ")
student_info['name'] = input("Enter Name: ")
student_info['age'] = input("Enter Age: ")
student_info['course'] = "BSc-II"
student_info['marks'] = {} # You can maintain more information here like marks for various
subjects
student_records.append(student_info)
print("Student information added successfully!")
# Function to display student information
def display_student_info():
if not student_records:
print("No student information available.")
else:
print("\nStudent Information (BSc-II):")
for idx, student in enumerate(student_records, start=1):
print(f"Student {idx}:")
print(f"Roll Number: {student['roll_number']}")
print(f"Name: {student['name']}")
print(f"Age: {student['age']}")
print(f"Course: {student['course']}")
print(f"Marks: {student['marks']}")
print()
# Main program loop
while True:
print("\nOptions:")
print("1. Add Student Information")
print("2. Display Student Information")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_student_info()
elif choice == '2':
display_student_info()
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice. Please select a valid option.")
55-Write a Python program to replace dictionary values with their
sum
# Define a dictionary with numeric values
original_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
# Calculate the sum of values in the dictionary
total_sum = sum(original_dict.values())
# Replace dictionary values with their sum
for key in original_dict:
original_dict[key] = total_sum
# Printing the updated dictionary
print("Updated Dictionary:")
print(original_dict)
56-Write a Python program to combine two dictionary adding values for common keys.
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})
from collections import Counter
# Define two dictionaries
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
# Method 1: Using a for loop
combined_dict = {}
for key in d1.keys() | d2.keys():
combined_dict[key] = d1.get(key, 0) + d2.get(key, 0)
# Method 2: Using collections.Counter
combined_counter = Counter(d1) + Counter(d2)
# Print the combined dictionaries
print("Combined Dictionary (Method 1):", combined_dict)
print("Combined Dictionary (Method 2):", dict(combined_counter))
57-Write a Python program to create a dictionary from a string. Sample string : 'w3resource' Expected output: {'3': 1, 's': 1, 'r': 2,
'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
# Sample string
sample_string = 'w3resource'
# Create an empty dictionary to store character counts
char_count_dict = {}
# Iterate through the characters in the string
for char in sample_string:
# Use the get() method to update the count or initialize it to 0
char_count_dict[char] = char_count_dict.get(char, 0) + 1
# Printing the resulting dictionary
print(char_count_dict)
58-Write a Python program to create a dictionary from two lists without losing duplicate values.
# Two lists with keys and values
keys_list = ['a', 'b', 'c', 'a', 'd']
values_list = [1, 2, 3, 4, 5]
# Create a dictionary using zip
result_dict = {}
for key, value in zip(keys_list, values_list):
if key in result_dict:
if isinstance(result_dict[key], list):
result_dict[key].append(value)
else:
result_dict[key] = [result_dict[key], value]
else:
result_dict[key] = value
# Printing the resulting dictionary
print(result_dict)
59-Write a Python program to replace dictionary values (integers) with their sum.
# Sample dictionary with integer values
sample_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
# Calculate the sum of all values in the dictionary
total_sum = sum(sample_dict.values())
# Replace dictionary values with their sum
for key in sample_dict:
sample_dict[key] = total_sum
# Printing the updated dictionary
print("Updated Dictionary:")
print(sample_dict)
60-Write a Python program to read the first n lines of a file.
def read_first_n_lines(file_name, n):
try:
with open(file_name, 'r') as file:
for i in range(n):
line = file.readline()
if not line:
break # Break if there are fewer than n lines in the file
print(line.strip()) # Print and strip newline characters
except FileNotFoundError:
print(f"File '{file_name}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
# Specify the file name and the number of lines to read
file_name = 'sample.txt' # Replace with the actual file name
n = 5 # Number of lines to read
# Call the function to read the first n lines
read_first_n_lines(file_name, n)
61- Write a Python program to append text to a file and display the text.
# Function to append text to a file
def append_to_file(file_name, text_to_append):
try:
with open(file_name, 'a') as file:
file.write(text_to_append)
print("Text appended to the file successfully.")
except Exception as e:
print(f"An error occurred: {str(e)}")
# Function to display the contents of a file
def display_file_contents(file_name):
try:
with open(file_name, 'r') as file:
file_contents = file.read()
print("File Contents:")
print(file_contents)
except FileNotFoundError:
print(f"File '{file_name}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
# Specify the file name and text to append
file_name = 'sample.txt' # Replace with the actual file name
text_to_append = "\nThis is the appended text."
# Append text to the file
append_to_file(file_name, text_to_append)
# Display the updated file contents
display_file_contents(file_name)
62-Write a Python program to read the last n lines of a file.
def read_last_n_lines(file_name, n):
try:
with open(file_name, 'r') as file:
lines = file.readlines()
last_n_lines = lines[-n:]
for line in last_n_lines:
print(line.strip()) # Print and strip newline characters
except FileNotFoundError:
print(f"File '{file_name}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
# Specify the file name and the number of lines to read
file_name = 'sample.txt' # Replace with the actual file name
n = 5 # Number of lines to read from the end
# Call the function to read the last n lines
read_last_n_lines(file_name, n)
63-Write a Python program to read a file line by line and store it in a list
def read_file_lines_to_list(file_name):
try:
with open(file_name, 'r') as file:
lines_list = file.readlines()
return lines_list
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return []
except Exception as e:
print(f"An error occurred: {str(e)}")
return []
# Specify the file name you want to read
file_name = 'sample.txt' # Replace with the actual file name
# Call the function to read the file lines and store them in a list
lines_list = read_file_lines_to_list(file_name)
# Display the list of lines
if lines_list:
print("Lines from the file:")
for line in lines_list:
print(line.strip()) # Print and strip newline characters
64-Write a Python program to read a file line by line and store it into a
Variable
def read_file_to_variable(file_name):
try:
with open(file_name, 'r') as file:
file_contents = ""
for line in file:
file_contents += line
return file_contents
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return ""
except Exception as e:
print(f"An error occurred: {str(e)}")
return ""
# Specify the file name you want to read
file_name = 'sample.txt' # Replace with the actual file name
# Call the function to read the file and store its contents in a variable
file_contents = read_file_to_variable(file_name)
# Display the contents of the variable
if file_contents:
print("File Contents:")
print(file_contents)
65-Write a python program to find the longest words.
def find_longest_words(text):
# Split the text into words
words = text.split()
# Initialize variables to store the longest words
longest_words = []
max_length = 0
# Iterate through the words to find the longest ones
for word in words:
word = word.strip(".,!?()[]{}:;") # Remove common punctuation
if len(word) > max_length:
max_length = len(word)
longest_words = [word]
elif len(word) == max_length:
longest_words.append(word)
return longest_words, max_length
# Example text
text = "This is a sample sentence. The longest words in this sentence are example
and sentence!"
# Find the longest words in the text
result, max_length = find_longest_words(text)
# Print the longest words
print("Longest Words:")
for word in result:
print(word)
print("Length of Longest Words:", max_length)
66-Write a Python program to count the number of lines in a
text file.
def find_longest_words(text):
# Split the text into words
words = text.split()
# Initialize variables to store the longest words
longest_words = []
max_length = 0
# Iterate through the words to find the longest ones
for word in words:
word = word.strip(".,!?()[]{}:;") # Remove common
punctuation
if len(word) > max_length:
max_length = len(word)
longest_words = [word]
elif len(word) == max_length:
longest_words.append(word)
return longest_words, max_length
# Example text
text = "This is a sample sentence. The longest words in this
sentence are example and sentence!"
# Find the longest words in the text
result, max_length = find_longest_words(text)
# Print the longest words
print("Longest Words:")
for word in result:
print(word)
print("Length of Longest Words:", max_length)
67-Write a Python program to count the frequency of words in a file.
import string
def count_word_frequency(file_name):
try:
with open(file_name, 'r') as file:
word_frequency = {}
for line in file:
# Remove punctuation and convert to lowercase
line = line.translate(str.maketrans('', '',
string.punctuation)).lower()
words = line.split()
for word in words:
if word in word_frequency:
word_frequency[word] += 1
else:
word_frequency[word] = 1
return word_frequency
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return {}
except Exception as e:
print(f"An error occurred: {str(e)}")
return {}
# Specify the file name you want to read
file_name = 'sample.txt' # Replace with the actual file name
# Call the function to count word frequency
word_frequency = count_word_frequency(file_name)
# Display word frequency
if word_frequency:
print("Word Frequency:")
for word, count in word_frequency.items():
print(f"{word}: {count}")
67-Write a Python program to count the frequency of
characters in a file.
def count_character_frequency(file_name):
try:
with open(file_name, 'r') as file:
character_frequency = {}
for line in file:
for char in line:
if char.isalnum(): # Check if the character is alphanumeric
char = char.lower() # Convert to lowercase for case-
insensitive counting
if char in character_frequency:
character_frequency[char] += 1
else:
character_frequency[char] = 1
return character_frequency
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return {}
except Exception as e:
print(f"An error occurred: {str(e)}")
return {}
# Specify the file name you want to read
file_name = 'sample.txt' # Replace with the actual file name
# Call the function to count character frequency
character_frequency = count_character_frequency(file_name)
# Display character frequency
if character_frequency:
print("Character Frequency:")
for char, count in character_frequency.items():
print(f"{char}: {count}")
68-Write a Python program to copy the contents of a file to
another file
def copy_file(source_file, destination_file):
try:
with open(source_file, 'r') as source, open(destination_file, 'w') as
destination:
# Read and copy the contents from the source file to the
destination file
for line in source:
destination.write(line)
print(f"Contents copied from '{source_file}' to '{destination_file}'
successfully.")
except FileNotFoundError:
print(f"File '{source_file}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
# Specify the source file and destination file names
source_file = 'source.txt' # Replace with the actual source file name
destination_file = 'destination.txt' # Replace with the actual destination
file name
# Call the function to copy the contents of the source file to the
destination file
copy_file(source_file, destination_file)
69-Write a Python program to combine each line from the first
file with
the corresponding line in the second file
def combine_files(file1, file2, output_file):
try:
with open(file1, 'r') as f1, open(file2, 'r') as f2,
open(output_file, 'w') as output:
for line1, line2 in zip(f1, f2):
combined_line = f"{line1.strip()} {line2.strip()}\n"
output.write(combined_line)
print(f"Lines from '{file1}' and '{file2}' combined and written
to '{output_file}' successfully.")
except FileNotFoundError as e:
print(f"File not found: {str(e)}")
except Exception as e:
print(f"An error occurred: {str(e)}")
# Specify the names of the two source files and the output file
file1 = 'file1.txt' # Replace with the actual name of the first file
file2 = 'file2.txt' # Replace with the actual name of the second file
output_file = 'combined.txt' # Specify the name of the output file
# Call the function to combine lines from both files and write to
the output file
combine_files(file1, file2, output_file)
70-Write a program to read a text file and compute the frequency of each word, character, alphabet, and integer.
import string
def compute_frequencies(file_name):
try:
with open(file_name, 'r') as file:
word_frequency = {}
char_frequency = {}
alphabet_frequency = {}
integer_frequency = {}
for line in file:
# Remove common punctuation and split into words
line = line.translate(str.maketrans('', '', string.punctuation))
words = line.split()
for word in words:
# Count word frequency
if word in word_frequency:
word_frequency[word] += 1
else:
word_frequency[word] = 1
# Count character frequency
for char in word:
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1
# Check if the character is an alphabet or integer
if char.isalpha():
if char in alphabet_frequency:
alphabet_frequency[char] += 1
else:
alphabet_frequency[char] = 1
elif char.isdigit():
if char in integer_frequency:
integer_frequency[char] += 1
else:
integer_frequency[char] = 1
return word_frequency, char_frequency, alphabet_frequency,
integer_frequency
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return {}, {}, {}, {}
except Exception as e:
print(f"An error occurred: {str(e)}")
return {}, {}, {}, {}
# Specify the file name you want to analyze
file_name = 'sample.txt' # Replace with the actual file name
# Call the function to compute frequencies
word_frequency, char_frequency, alphabet_frequency, integer_frequency =
compute_frequencies(file_name)
# Display frequencies
if word_frequency:
print("Word Frequency:")
for word, count in word_frequency.items():
print(f"{word}: {count}")
if char_frequency:
print("Character Frequency:")
for char, count in char_frequency.items():
print(f"{char}: {count}")
if alphabet_frequency:
print("Alphabet Frequency:")
for char, count in alphabet_frequency.items():
print(f"{char}: {count}")
if integer_frequency:
print("Integer Frequency:")
for char, count in integer_frequency.items():
print(f"{char}: {count}")