Python Practical question
Python Practical question
R5)
Programming and Problem Solving Through Python (M3-R5.1)
370=33+73+03
ii. Write a function to obtain sum n terms of the following series for any
positive integer value of X
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!+…
6*7 = 6+6+6+6+6+6+6
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
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.
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.
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:
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.
370=33+73+03
ii. Write a function to obtain sum n terms of the following series for any
positive integer
value of X
Solution
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
total_sum = 0
for i in range(n):
term_power = 2 * i + 1
total_sum += term
return total_sum
# Example usage:
result = series_sum(X, n)
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)
total_sum = 0
for i in range(n):
term = (x ** i) / factorial(i)
total_sum += term
return total_sum
# Example usage:
result = series_sum(x, n)
6*7 = 6+6+6+6+6+6+6
result = 0
return result
# Example usage:
def calculate_wages(hours_worked):
base_rate = 100
rate_extra_1 = 30
rate_extra_2 = 40
rate_extra_3 = 50
rate_extra_4 = 60
if hours_worked <= 8:
total_wages = base_rate
return total_wages
# Example usage:
wages = calculate_wages(hours_worked)
vi. Accept the name of the labourer and no. of hours worked. Calculate and
display the
labourers = []
HOURLY_WAGE_RATE=100
for i in range(num_labourers):
print("-----------------------")
vii. Write a function that takes a string as parameter and returns a string
with every
def replace_repetitive_characters(input_string):
if len(input_string) <= 1:
return input_string
# Iterate through the characters of the input string starting from the second
character
# If the current character is the same as the previous one, replace it with '?'
else:
return modified_string
modified_string = replace_repetitive_characters(input_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
# 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
# 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]
return letter_frequency
except FileNotFoundError:
print("One of the files does not exist.")
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'}
except FileNotFoundError:
print("File not found.")
except FileNotFoundError:
print("File not found.")
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]])
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:
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)
arr1=np.array([[4,5,6],[7,8,3],[2,2,1]])
arr3=arr * 2