Programming and Problem Solving Through Python (M3-
R5)
Programming and Problem Solving Through Python (M3-R5.1)
i. Write a program to print all Armstrong numbers in a given range. Note: An
Armstrong
number is a number whose sum of cubes of digits is equal to the number
itself. E.g.
370=33+73+03
ii. Write a function to obtain sum n terms of the following series for any
positive integer value of X
X +X3 /3! +X5 /5! ! +X7 /7! + …
iii. Write a function to obtain sum n terms of the following series for any
positive integer value of X
1+x/1!+x2/2!+x3/3!+…
iv. Write a program to multiply two numbers by repeated addition e.g.
6*7 = 6+6+6+6+6+6+6
v. Write a program to compute the wages of a daily laborer as per the
following rules: -
Hours Worked Rate Applicable Upto first 8 hrs Rs100/-
a) For next 4 hrs Rs30/- per hr extra
b) For next 4 hrs Rs40/- per hr extra
c) For next 4 hrs Rs50/- per hr extra
d) For rest Rs60/- per hr extra
vi. Accept the name of the labourer and no. of hours worked. Calculate and
display the wages.The program should run for N number of labourers as
specified by the user.
vii. Write a function that takes a string as parameter and returns a string
with every successive repetitive character replaced by? e.g. school may
become scho?l.
viii. Write a program that takes in a sentence as input and displays the
number of words, number of capital letters, no. of small letters and number
of special symbols.
ix. Write a Python program that takes list of numbers as input from the user
and produces a
cumulative list where each element in the list at any position n is sum of all
elements at
positions upto n-1.
x. Write a program which takes list of numbers as input and finds:
a) The largest number in the list
b) The smallest number in the list
c) Product of all the items in the list
xi. Write a Python function that takes two lists and returns True if they have
at least one common item.
xii. 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})
xiii. Write a program that takes sentence as input from the user and
computes the frequency of each letter. Use a variable of dictionary type to
maintain and show the frequency of each
letter.
xiv. Apply recursive call to do the following:
a) Product of two numbers using repetitive addition
b) Print Fibonacci series up to term n
xv. Write a program to input two numbers as input and compute the
greatest common divisor
xvi. Write a function that takes two filenames f1 and f2 as input. The
function should read the contents of f1 line by line and write them onto f2.
xvii. Write a function that reads the contents of the file f3.txt and counts the
number of alphabets, blank spaces, lowercase letters, number of words
starting with a vowel and number of occurrences of a work “hello”.
xviii. Write a program to replace ‘a’ with ‘b’, ‘b’ with ‘c’,….,’z’ with ‘a’ and
similarly for ‘A’
with ‘B’,’B’ with ‘C’, …., ‘Z’ with ‘A’ in a file. The other characters should
remain
unchanged.
xix. Write a NumPy program to find the most frequent value in an array.
xx. Take two NumPy arrays having two dimensions. Concatenate the arrays
on axis 1.
XXI. Create a numpy array having two dimensions and shape(3,3) and
perform the following operations on array elements:
a) Calculate sum of all the columns of the array
b) Calculate product of all the rows of the array.
c) Retrieve only the last two columns and last two rows form the array.
d) Create another two dimensional array having same shape and carry out
element wise addition of two arrays and display the result.
Create a new array by multiplying every element of original array with value
2 and display the new array.
XXII. Write a program to find the intersection of two arrays
i. Write a program to print all Armstrong numbers in a given range. Note: An
Armstrong
number is a number whose sum of cubes of digits is equal to the number
itself. E.g.
370=33+73+03
# Define a function to check if a number is an Armstrong number
def is_armstrong(number):
# Convert the number to a string to iterate through its digits
num_str = str(number)
# Find the number of digits
num_digits = len(num_str)
# Initialize a variable to store the sum of the cubes of digits
armstrong_sum = 0
# Iterate through each digit and calculate the sum of cubes
for digit in num_str:
armstrong_sum += int(digit) ** num_digits
# Check if the sum equals the original number
return armstrong_sum == number
# Define a function to print Armstrong numbers within a given range
def print_armstrong_numbers(start, end):
print(f"Armstrong numbers between {start} and {end}:")
# Iterate through the range
for num in range(start, end + 1):
# Check if the current number is an Armstrong number
if is_armstrong(num):
print(num)
# Get the range from the user
start_range = int(input("Enter the starting range: "))
end_range = int(input("Enter the ending range: "))
# Call the function to print Armstrong numbers within the range
print_armstrong_numbers(start_range, end_range)
ii. Write a function to obtain sum n terms of the following series for any
positive integer
value of X
X +X3 /3! +X5 /5! ! +X7 /7! + …
Solution
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def series_sum(X, n):
total_sum = 0
for i in range(n):
# Compute the power of X for each term
term_power = 2 * i + 1
term = (X ** term_power) / factorial(term_power)
total_sum += term
return total_sum
# Example usage:
X = int(input("Enter the value of X: "))
n = int(input("Enter the number of terms: "))
result = series_sum(X, n)
print("Sum of the series:", result)
iii. Write a function to obtain sum n terms of the following series for any
positive integer
value of X
1+x/1!+x2/2!+x3/3!+…
Solution
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def series_sum(x, n):
total_sum = 0
for i in range(n):
term = (x ** i) / factorial(i)
total_sum += term
return total_sum
# Example usage:
x = int(input("Enter the value of x: "))
n = int(input("Enter the number of terms: "))
result = series_sum(x, n)
print("Sum of the series:", result)
iv. Write a program to multiply two numbers by repeated addition e.g.
6*7 = 6+6+6+6+6+6+6
def multiply(x, y):
result = 0
for _ in range(y): # Repeats y times
result += x # Add x to the result y times
return result
# Example usage:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
product = multiply(num1, num2)
print("The product is:", product)
v. Write a program to compute the wages of a daily laborer as per the
following rules :-
Hours Worked Rate Applicable Upto first 8 hrs Rs100/-
a) For next 4 hrs Rs30/- per hr extra
b) For next 4 hrs Rs40/- per hr extra
c) For next 4 hrs Rs50/- per hr extra
d) For rest Rs60/- per hr extra
def calculate_wages(hours_worked):
# Base rate for the first 8 hours
base_rate = 100
# Additional rates for extra hours
rate_extra_1 = 30
rate_extra_2 = 40
rate_extra_3 = 50
rate_extra_4 = 60
# Calculate wages based on hours worked
if hours_worked <= 8:
total_wages = base_rate
elif hours_worked <= 12:
total_wages = base_rate + (hours_worked - 8) * rate_extra_1
elif hours_worked <= 16:
total_wages = base_rate + 4 * rate_extra_1 + (hours_worked - 12) * rate_extra_2
elif hours_worked <= 20:
total_wages = base_rate + 4 * rate_extra_1 + 4 * rate_extra_2 + (hours_worked -
16) * rate_extra_3
else:
total_wages = base_rate + 4 * rate_extra_1 + 4 * rate_extra_2 + 4 * rate_extra_3
+ (hours_worked - 20) * rate_extra_4
return total_wages
# Example usage:
hours_worked = float(input("Enter the number of hours worked: "))
wages = calculate_wages(hours_worked)
print(f"The wages for {hours_worked} hours of work is Rs{wages}/-")
vi. Accept the name of the labourer and no. of hours worked. Calculate and
display the
wages. The program should run for N number of labourers as specified by
the user.
num_labourers = int(input("Enter the number of labourers: "))
# List to store labourer details
labourers = []
HOURLY_WAGE_RATE=100
# Collect details and calculate wages for each labourer
for i in range(num_labourers):
name = input(f"Enter name of labourer {i+1}: ")
hours_worked = float(input(f"Enter number of hours worked by {name}: "))
wages = hours_worked * HOURLY_WAGE_RATE
labourers.append((name, hours_worked, wages))
# Display the results
print("\nLabourer Wages Report")
print("-----------------------")
for name, hours, wages in labourers:
print(f"Name: {name}, Hours Worked: {hours}, Wages: {wages}")
vii. Write a function that takes a string as parameter and returns a string
with every
successive repetitive character replaced by ?e.g. school may become scho?l.
def replace_repetitive_characters(input_string):
# If the string is empty or has only one character, return it as is
if len(input_string) <= 1:
return input_string
# Initialize an empty string to store the modified output
modified_string = input_string[0] # Start with the first character
# Iterate through the characters of the input string starting from the second
character
for i in range(1, len(input_string)):
# If the current character is the same as the previous one, replace it with '?'
if input_string[i] == input_string[i - 1]:
modified_string += '?' # Append '?' to the modified string
else:
modified_string += input_string[i] # Append the character as is
return modified_string
# Test the function
input_string = input("Enter a string: ")
modified_string = replace_repetitive_characters(input_string)
print("Modified string:", modified_string)
viii. Write a program that takes in a sentence as input and displays the
number of words,
number of capital letters, no. of small letters and number of special
symbols.
def analyze_sentence(sentence):
# Initialize counts
word_count = len(sentence.split())
capital_count = 0
small_count = 0
special_count = 0
# Analyze each character in the sentence
for char in sentence:
if char.isupper():
capital_count += 1
elif char.islower():
small_count += 1
elif char in [' ', '\t', '\n']:
continue # Skip whitespace characters
else:
special_count += 1
return word_count, capital_count, small_count, special_count
# Get input sentence from the user
sentence = input("Enter a sentence: ")
# Analyze the sentence
word_count, capital_count, small_count, special_count = analyze_sentence(sentence)
# Display the analysis results
print("Number of words:", word_count)
print("Number of capital letters:", capital_count)
print("Number of small letters:", small_count)
print("Number of special symbols:", special_count)
ix. Write a Python program that takes list of numbers as input from the user
and produces
a cumulative list where each element in the list at any position n is sum of
all elements
at positions upto n-1.
the cumulative list series for the sequence 1,2,3,4,5,…1,2,3,4,5,… would be
1,3,6,10,15,… Each term in the cumulative list series represents the sum of all the
terms up to that point in the original sequence.
# Step 1: Get a list of numbers as input from the user
num_list = input("Enter a list of numbers separated by spaces: ").split()
# Convert input numbers from string to int
num_list = [int(num) for num in num_list]
# Step 2: Create a new list to store the cumulative sum
cumulative_list = []
# Step 3 and 4: Iterate through the input list and compute the cumulative sum
cumulative_sum = 0
for num in num_list:
cumulative_sum += num # Update the cumulative sum
cumulative_list.append(cumulative_sum) # Append the cumulative sum to the new
list
# Step 5: Display the cumulative list
print("Cumulative list:", cumulative_list)
x. Write a program which takes list of numbers as input and finds:
a) The largest number in the list
b) The smallest number in the list
c) Product of all the items in the list
# Step 1: Get a list of numbers as input from the user
num_list = input("Enter a list of numbers separated by spaces: ").split()
# Convert input numbers from string to float
num_list = [float(num) for num in num_list]
# Check if the list is not empty
if not num_list:
print("The list is empty.")
else:
# a) Find the largest number in the list
largest_number = max(num_list)
# b) Find the smallest number in the list
smallest_number = min(num_list)
# c) Calculate the product of all the items in the list
product = 1
for num in num_list:
product *= num
# Display the results
print("Largest number:", largest_number)
print("Smallest number:", smallest_number)
print("Product of all items:", product)
xi. Write a Python function that takes two lists and returns True if they have
at least one
common item.
def have_common_item(list1, list2):
# Convert lists to sets for efficient membership testing
set1 = set(list1)
set2 = set(list2)
# Check if there is any intersection between the two sets
if set1.intersection(set2):
return True
else:
return False
# Test the function
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
print(have_common_item(list1, list2)) # Output: True
list3 = [10, 11, 12]
list4 = [13, 14, 15]
print(have_common_item(list3, list4)) # Output: False
xii. 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})
# Given dictionaries
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
# Initialize an empty dictionary for the result
result = {}
# Iterate through keys of d1
for key in d1:
if key in d2: # If key exists in both dictionaries, sum values
result[key] = d1[key] + d2[key]
else: # If key exists only in d1, keep its value
result[key] = d1[key]
# Iterate through keys of d2 (to add keys that are only in d2)
for key in d2:
if key not in d1: # Add keys that exist only in d2
result[key] = d2[key]
# Print the final combined dictionary
print(result)
xiii. Write a program that takes sentence as input from the user and
computes the frequency
of each letter. Use a variable of dictionary type to maintain and show the
frequency of
each letter.
def calculate_letter_frequency(sentence):
# Initialize an empty dictionary to store letter frequencies
letter_frequency = {}
# Iterate through each character in the sentence
for char in sentence:
# Consider only alphabetic characters
if char.isalpha():
char_lower = char.lower() # Convert to lowercase to treat uppercase and
lowercase as same
# Update the letter frequency in the dictionary
letter_frequency[char_lower] = letter_frequency.get(char_lower, 0) + 1
return letter_frequency
# Get input sentence from the user
sentence = input("Enter a sentence: ")
# Calculate letter frequency
frequency_dict = calculate_letter_frequency(sentence)
# Display the frequency of each letter
print("Letter frequency:")
for letter, frequency in frequency_dict.items():
print(f"{letter}: {frequency}")
xiv. Apply recursive call to do the following:
a) Product of two numbers using repetitive addition
b) Print Fibonacci series upto term n
Solution a)
def product_recursive(a, b):
# Base case: if one of the numbers is 0, return 0
if a == 0 or b == 0:
return 0
# Base case: if b is 1, return a
elif b == 1:
return a
# Recursive case: subtract 1 from b and add a to the result recursively
else:
return a + product_recursive(a, b - 1)
# Test the function
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Product:", product_recursive(num1, num2))
Solution b)
def fibonacci_recursive(n):
# Base case: if n is 0 or 1, return n
if n <= 1:
return n
# Recursive case: return the sum of the previous two terms
else:
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
# Test the function
terms = int(input("Enter the number of terms for Fibonacci series: "))
print("Fibonacci series:")
for i in range(terms):
print(fibonacci_recursive(i), end=" ")
xv. Write a program to input two numbers as input and compute the
greatest common
divisor
def gcd(a, b):
# Ensure a is greater than or equal to b
if b == 0:
return a
else:
return gcd(b, a % b)
# Get input two numbers from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
# Ensure num1 is greater than or equal to num2
if num1 < num2:
num1, num2 = num2, num1
# Compute the GCD
result = gcd(num1, num2)
# Print the result
print("The greatest common divisor (GCD) of", num1, "and", num2, "is", result)
xvi. Write a function that takes two filenames f1 and f2 as input. The
function should read
the contents of f1 line by line and write them onto f2.
def copy_file_contents(f1, f2):
try:
# Open the first file for reading
with open(f1, 'r') as file1:
# Read the contents of the first file line by line
lines = file1.readlines()
# Open the second file for writing
with open(f2, 'w') as file2:
# Write the contents of the first file into the second file
file2.writelines(lines)
print(f"Contents of '{f1}' have been copied to '{f2}' successfully.")
except FileNotFoundError:
print("One of the files does not exist.")
# Test the function
filename1 = input("Enter the name of the source file: ")
filename2 = input("Enter the name of the destination file: ")
copy_file_contents(filename1, filename2)
xvii. Write a function that reads the contents of the file f3.txt and counts the
number of
alphabets, blank spaces, lowercase letters, number of words starting with a
vowel and
number of occurrences of a work “hello”.
def analyze_file(filename):
try:
# Open the file for reading
with open(filename, 'r') as file:
# Read the contents of the file
content = file.read()
# Initialize counters
num_alphabets = 0
num_spaces = 0
num_lowercase = 0
num_vowel_words = 0
num_hello_occurrences = content.count("hello")
# Define vowels
vowels = {'a', 'e', 'i', 'o', 'u'}
# Analyze the content
for char in content:
if char.isalpha():
num_alphabets += 1
if char.islower():
num_lowercase += 1
if char.lower() in vowels:
num_vowel_words += 1
elif char.isspace():
num_spaces += 1
# Count words starting with a vowel
words = content.split()
num_vowel_words = sum(1 for word in words if word.lower()[0] in vowels)
print("Number of alphabets:", num_alphabets)
print("Number of spaces:", num_spaces)
print("Number of lowercase letters:", num_lowercase)
print("Number of words starting with a vowel:", num_vowel_words)
print("Number of occurrences of 'hello':", num_hello_occurrences)
except FileNotFoundError:
print("File not found.")
# Test the function
analyze_file("f3.txt")
xviii. Write a program to replace ‘a’ with ‘b’, ‘b’ with ‘c’,….,’z’ with ‘a’ and
similarly for
‘A’ with ‘B’,’B’ with ‘C’, …., ‘Z’ with ‘A’ in a file. The other characters should
remain
unchanged.
def replace_chars(input_filename, output_filename):
try:
# Open the input file for reading
with open(input_filename, 'r') as input_file:
# Read the contents of the file
content = input_file.read()
# Perform character replacements
modified_content = ""
for char in content:
if 'a' <= char <= 'z':
modified_content += chr((ord(char) - ord('a') + 1) % 26 + ord('a'))
elif 'A' <= char <= 'Z':
modified_content += chr((ord(char) - ord('A') + 1) % 26 + ord('A'))
else:
modified_content += char
# Open the output file for writing
with open(output_filename, 'w') as output_file:
# Write the modified content to the file
output_file.write(modified_content)
print(f"Character replacements completed. Modified content written to
{output_filename}.")
except FileNotFoundError:
print("File not found.")
# Test the function
input_filename = "input_file.txt"
output_filename = "output_file.txt"
replace_chars(input_filename, output_filename)
xix. Write a NumPy program to find the most frequent value in an array.
import numpy as np
def most_frequent_value(arr):
unique_values, counts = np.unique(arr, return_counts=True)
max_count_index = np.argmax(counts)
most_frequent_value = unique_values[max_count_index]
return most_frequent_value
# Example usage:
arr = np.array([1, 2, 3, 1, 2, 2, 2, 3, 3, 3, 3, 3])
most_frequent = most_frequent_value(arr)
print("Most frequent value:", most_frequent)
xx. Take two NumPy arrays having two dimensions. Concatenate the arrays
on axis 1.
import numpy as np
# Example arrays
array1 = np.array([[1, 2, 3],
[4, 5, 6]])
array2 = np.array([[7, 8, 9],
[10, 11, 12]])
# Concatenate along axis 1
concatenated_array = np.concatenate((array1, array2), axis=1)
print("Array 1:")
print(array1)
print("Array 2:")
print(array2)
print("Concatenated array along axis 1:")
print(concatenated_array)
XXI. Create a numpy array having two dimensions and shape(3,3) and
perform the following operations on array elements:
a) Calculate sum of all the columns of the array
b) Calculate product of all the rows of the array.
c) Retrieve only the last two columns and last two rows form the array.
d) Create another two dimensional array having same shape and carry out
element wise addition of two arrays and display the result.
Create a new array by multiplying every element of original array with value
2 and display the new array.
import numpy as np
arr=np.array([[3,4,9],[3,4,2],[1,2,3]])
print("Array is : \n",arr)
print("Sum of All Column ",np.sum(arr, axis=0))
print("Product of All Column ",np.prod(arr, axis=0))
print("Last Two Column \n",arr[:, -2:])
print("Last Two Rows \n",arr[-2:, :])
arr1=np.array([[4,5,6],[7,8,3],[2,2,1]])
print("Second Array is : \n",arr1)
print("Addition of 2 Array is : \n",(arr+arr1))
arr3=arr * 2
print("Third Array (Muliply by 2) : \n",arr3)
XXII. Write a program to find the intersection of two arrays
# Define two arrays
array1 = [1, 2, 3, 4, 5]
array2 = [3, 4, 5, 6, 7]
# Initialize an empty list to store the intersection
intersection = []
# Iterate through the first array
for element in array1:
# Check if the element is present in the second array
if element in array2:
# Add the element to the intersection list if it's not already there
if element not in intersection:
intersection.append(element)
# Print the intersection of the two arrays
print("The intersection of the two arrays is:", intersection)