pyhton
pyhton
INSTITUTE OF COMPUTER
APPLICATIONS & MANAGEMENT
(Affiliated to Guru Gobind Singh Indraprastha University, Approved by AICTE, New Delhi)
PYTHON PROGRAMMING-LAB
(MCA-166)
MCA - II Semester
P2. By considering the terms in the Fibonacci sequence whose values do not exceed 1000,
find the sum of the even-valued terms.
a=1
b=2
sum_even = 0
results = []
for num in range(1000, 2001):
if num % 7 == 0 and num % 5 != 0:
results.append(num)
numbers = [1, 2, 3, 4, 5]
cumulative_product = []
product = 1
def reverse(lst):
reversed_list = []
for i in range(len(lst) - 1, -1, -1):
reversed_list.append(lst[i])
return reversed_list
P6. Define a function which generates Fibonacci series up to n numbers using RECURSION.
def fibonacci_recursive(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
series = fibonacci_recursive(n - 1)
series.append(series[-1] + series[-2])
return series
n=8
print(f"Fibonacci series up to {n} terms:")
print(fibonacci_recursive(n))
P7. With a given tuple (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), write a program to print the first half
values in one line and the last half values in one line.
t = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
mid = len(t) // 2
print("First half:", t[:mid])
print("Last half:", t[mid:])
P8. Write a program to count the numbers of characters in the string and store them in a
dictionary data structure.
s = "hello world"
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
print("Character count:")
print(char_count)
s = "r e m o v e s p a c e s"
def remove_spaces_recursively(s):
if not s:
return ""
if s[0] == " ":
return remove_spaces_recursively(s[1:])
else:
return s[0] + remove_spaces_recursively(s[1:])
result = remove_spaces_recursively(s)
print("String after removing spaces:")
print(result)
P10. Write a program to compute the number of characters, words and lines in a file.
char_count = 0
word_count = 0
line_count = 0
class StringManipulator:
def __init__(self):
self.user_string = ""
def get_String(self):
self.user_string = input("Enter a string: ")
def print_String(self):
print("String in uppercase:")
print(self.user_string.upper())
obj = StringManipulator()
obj.get_String()
obj.print_String()
P12. Write a Python class named Circle constructed by a radius and two methods which will
compute the area and the perimeter of a circle.
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
c = Circle(7)
print("Radius:", c.radius)
print("Area of the circle:", c.area())
print("Perimeter of the circle:", c.perimeter())
P13. Write a Python class to reverse a string word by word : Input string : 'hello Python'
Expected Output : 'Python hello'
class StringReverser:
def __init__(self, input_string):
self.input_string = input_string
def reverse_words(self):
reversed_string = ' '.join(self.input_string.split()[::-1])
print("Reversed string word by word:")
print(reversed_string)
P14. Write a program to compare two files and display total number of lines in a file.
class StringReverser:
def __init__(self, input_string):
self.input_string = input_string
def reverse_words(self):
reversed_string = ' '.join(self.input_string.split()[::-1])
print("Reversed string word by word:")
print(reversed_string)
def is_balanced(s):
stack = []
matching = {')': '(', '}': '{', ']': '['}
for char in s:
if char in "({[":
stack.append(char)
elif char in ")}]":
if not stack or stack[-1] != matching[char]:
return False
stack.pop()
return len(stack) == 0
P16. Implement a python script to check the element is in the list or not by using Linear
search & Binary search.
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
data.sort()
index_binary = binary_search(data, target)
if index_binary != -1:
print(f"Binary Search: Element {target} found at index {index_binary}")
else:
print(f"Binary Search: Element {target} not found")
P17. Implement a python script to arrange the elements in sorted order using Bubble,
Selection, Insertion and Merge sorting techniques.
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
result.extend(left[i:])
result.extend(right[j:])
return result
def print_matrix(matrix):
for row in matrix:
print(" ".join(map(str, row)))
def transpose_matrix(A):
return [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]
def menu():
while True:
print("\n--- Matrix Operations Menu ---")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Transpose")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
print("\nResult of Addition:")
print_matrix(add_matrices(A, B))
else:
print("\nResult of Subtraction:")
print_matrix(subtract_matrices(A, B))
if cols_A != rows_B:
print("Error: Columns of A must match rows of B for multiplication.")
else:
print("\nResult of Multiplication:")
print_matrix(multiply_matrices(A, B))
Line Plot
import sys
import matplotlib
matplotlib.use('Agg')
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Scatter Plot
import sys
import matplotlib
matplotlib.use('Agg')
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Histogram Plot
import sys
import matplotlib
matplotlib.use('Agg')
plt.hist(x)
plt.show()
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Piechart Plot
import sys
import matplotlib
matplotlib.use('Agg')
plt.pie(y)
plt.show()
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
P20. Write a python program to perform various database operations (create, insert,
delete, update).
import sqlite3
# Fetch and display all users (to see the results of operations)
def display_users():
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
print("\nCurrent users in the database:")
for user in users:
print(f"ID: {user[0]}, Name: {user[1]}, Age: {user[2]}")
print("\n")
create_table()
digit_map = {
'0': 'Zero',
'1': 'One',
'2': 'Two',
'3': 'Three',
'4': 'Four',
'5': 'Five',
'6': 'Six',
'7': 'Seven',
'8': 'Eight',
'9': 'Nine'
}
number_str = str(number)
number = 452
result = number_to_words(number)
print(f"The number {number} in words is: {result}")
AQ2. Given a list of integers with duplicate elements in it. Create a new list that contains the
elements which appear more than one.
words = words_input.split()
words.sort()
hyphen_separated = '-'.join(words)
return hyphen_separated
AQ5. Write a python program to merge two list into one sorted in ascending order. Eg L1=
[1,5,9] L2 = [2,4,6], Output = [1,2,4,5,6,9].
def merge_and_sort_lists(list1, list2):
return merged_list
L1 = [1, 5, 9]
L2 = [2, 4, 6]