0% found this document useful (0 votes)
2 views

pyhton

The document outlines a Python programming lab for MCA II Semester students at Bharati Vidyapeeth's Institute of Computer Applications & Management. It includes a series of programming tasks and exercises, such as generating natural numbers, calculating Fibonacci sums, and implementing various algorithms and data structures. Each task is accompanied by example code and instructions for implementation.

Uploaded by

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

pyhton

The document outlines a Python programming lab for MCA II Semester students at Bharati Vidyapeeth's Institute of Computer Applications & Management. It includes a series of programming tasks and exercises, such as generating natural numbers, calculating Fibonacci sums, and implementing various algorithms and data structures. Each task is accompanied by example code and instructions for implementation.

Uploaded by

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

BHARATI VIDYAPEETH’S

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

Submitted To: Submitted By:


Dr. Saumya Bansal Kanan
(Assistant Professor, 03511604424
BVICAM, New Delhi) MCA 2nd Sem, Sec A
INDEX
S.No TOPICS PAGE NO. SIGN
P1 Implement Python Script to generate first N natural
numbers.
P2 By considering the terms in the Fibonacci sequence
whose values do not exceed 1000, find the sum of the
even-valued terms.
P3 Write a program which makes use of function to
display all such numbers which are divisible by 7 but
are not a multiple of 5, between 1000 and 2000.
P4 Write a function cumulative_product to compute
cumulative product of a list of numbers.
P5 Write a function reverse to reverse a list. Without using
the reverse function.
P6 Define a function which generates Fibonacci series up to n
numbers using RECURSION.
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.
P8 Write a program to count the numbers of characters in the
string and store them in a dictionary data structure.
P9 Remove spaces from a string using recursion.
P10 Write a program to compute the number of characters, words
and lines in a file
P11 Write a Python class which has two methods get_String and
print_String. get_String accept a string from the user and
print_String print the string in upper case.
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.
P13 Write a Python class to reverse a string word by word : Input
string : 'hello Python' Expected Output : 'Python hello'.
P14 Write a program to compare two files and display total number
of lines in a file.
P15 Write a program to determine whether a given string has
balanced parenthesis or not.
P16 Implement a python script to check the element is in the list or
not by using Linear search & Binary search.
P17 Implement a python script to arrange the elements in sorted
order using Bubble, Selection, Insertion and Merge sorting
techniques.
P18 Create a menu driven program to perform various matrices
operations.
P19 Draw different graphs and plots in Python using Matplotlib
Library.
P20 Write a python program to perform various database operations
(create, insert, delete, update)
AQ1 Write a function that takes a number as an input parameter and
returns the corresponding number name in words. For example:
if input is 452, the function should return “Four Five Two”. Use
a dictionary for mapping digits to their string representation.
AQ2 Given a list of integers with duplicate elements in it. Create a
new list that contains the elements which appear more than one.
AQ3 Write a function that reads a file and copies only alternative
lines to another file. Alternative lines copied should be the odd
numbers lines. Handle all exceptions that can be raised.
AQ4 Write a Python program that accepts a space separated
sequence of words as input and prints the words in a hyphen-
separated sequence after sorting them alphabetically.
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]
P1. Implement Python Script to generate first N natural numbers.

N = int(input("Enter the value of N: "))


if N < 1:
print("Please enter a number greater than 0.")
else:
print("First", N, "natural numbers:")
for i in range(1, N + 1):
print(i, end=" ")

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

while b <= 1000:


if b % 2 == 0:
sum_even += b
a, b = b, a + b

print("Sum of even-valued Fibonacci terms not exceeding 1000:", sum_even)


P3. Write a program which makes use of function to display all such numbers which are
divisible by 7 but are not a multiple of 5, between 1000 and 2000.

results = []
for num in range(1000, 2001):
if num % 7 == 0 and num % 5 != 0:
results.append(num)

print("Numbers divisible by 7 but not a multiple of 5 between 1000 and 2000:")


print(results)

P4. Write a function cumulative_product to compute cumulative product of a list of


numbers.

numbers = [1, 2, 3, 4, 5]

cumulative_product = []

product = 1

for num in numbers:


product *= num
cumulative_product.append(product)

print("Original list:", numbers)


print("Cumulative product:", cumulative_product)
P5. Write a function reverse to reverse a list. Without using the reverse function.

def reverse(lst):
reversed_list = []
for i in range(len(lst) - 1, -1, -1):
reversed_list.append(lst[i])
return reversed_list

original_list = [10, 12, 13, 14, 15]


reversed_result = reverse(original_list)

print("Original list:", original_list)


print("Reversed list:", reversed_result)

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)

P9. Remove spaces from a string using recursion.

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.

file = open("sample.txt", "r")

char_count = 0
word_count = 0
line_count = 0

for line in file:


line_count += 1
char_count += len(line)
word_count += len(line.split())
file.close()

print("Number of lines:", line_count)


print("Number of words:", word_count)
print("Number of characters:", char_count)
P11. Write a Python class which has two methods get_String and print_String. get_String
accept a string from the user and print_String print the string in upper case.

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)

obj = StringReverser('hello Python')


obj.reverse_words()

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)

obj = StringReverser('hello Python')


obj.reverse_words()
P15. Write a program to determine whether a given string has balanced parenthesis or not.

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

test_string = "(a + b) * (c - d)"


if is_balanced(test_string):
print("Balanced")
else:
print("Not Balanced")

P16. Implement a python script to check the element is in the list or not by using Linear
search & Binary search.

def linear_search(arr, target):


for index, element in enumerate(arr):
if element == target:
return index
return -1

def binary_search(arr, target):


low = 0
high = len(arr) - 1

while low <= high:


mid = (low + high) // 2

if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

data = [12, 34, 56, 78, 90, 123, 145]


target = 78

index_linear = linear_search(data, target)


if index_linear != -1:
print(f"Linear Search: Element {target} found at index {index_linear}")
else:
print(f"Linear Search: Element {target} not found")

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:])

return merge(left_half, right_half)

def merge(left, right):


result = []
i=j=0

while i < len(left) and j < len(right):


if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1

result.extend(left[i:])
result.extend(right[j:])
return result

data = [64, 25, 12, 22, 11]


print("Original List:", data)
print("Bubble Sort: ", bubble_sort(data.copy()))
print("Selection Sort:", selection_sort(data.copy()))
print("Insertion Sort:", insertion_sort(data.copy()))
print("Merge Sort: ", merge_sort(data.copy()))
P18. Create a menu driven program to perform various matrices operations.

def input_matrix(rows, cols):


print(f"Enter elements row-wise ({rows}x{cols}):")
return [[int(input(f"Element [{i}][{j}]: ")) for j in range(cols)] for i in range(rows)]

def print_matrix(matrix):
for row in matrix:
print(" ".join(map(str, row)))

def add_matrices(A, B):


return [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]

def subtract_matrices(A, B):


return [[A[i][j] - B[i][j] for j in range(len(A[0]))] for i in range(len(A))]

def multiply_matrices(A, B):


result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
return result

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' or choice == '2':


rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
print("Enter first matrix:")
A = input_matrix(rows, cols)
print("Enter second matrix:")
B = input_matrix(rows, cols)

if choice == '1':
print("\nResult of Addition:")
print_matrix(add_matrices(A, B))
else:
print("\nResult of Subtraction:")
print_matrix(subtract_matrices(A, B))

elif choice == '3':


rows_A = int(input("Enter rows for Matrix A: "))
cols_A = int(input("Enter columns for Matrix A: "))
A = input_matrix(rows_A, cols_A)

rows_B = int(input("Enter rows for Matrix B: "))


cols_B = int(input("Enter columns for Matrix B: "))
B = input_matrix(rows_B, cols_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))

elif choice == '4':


rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
print("Enter matrix:")
A = input_matrix(rows, cols)
print("\nTranspose of the matrix:")
print_matrix(transpose_matrix(A))

elif choice == '5':


print("Exiting program.")
break
else:
print("Invalid choice. Try again.")
menu()
P19. Draw different graphs and plots in Python using Matplotlib Library.

Line Plot
import sys
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt


import numpy as np

ypoints = np.array([3, 8, 1, 10])


plt.plot(ypoints, linestyle = 'dashed')
plt.show()

plt.savefig(sys.stdout.buffer)
sys.stdout.flush()

Scatter Plot
import sys
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt


import numpy as np

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

import matplotlib.pyplot as plt


import numpy as np

x = np.random.normal(170, 10, 250)

plt.hist(x)
plt.show()
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()

Piechart Plot
import sys
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])

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

# Connect to SQLite database (or create it if it doesn't exist)


conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# Create a table (CREATE operation)


def create_table():
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
''')
conn.commit()
print("Table created successfully.")

# Insert data into the table (INSERT operation)


def insert_user(name, age):
cursor.execute('''
INSERT INTO users (name, age)
VALUES (?, ?)
''', (name, age))
conn.commit()
print(f"User '{name}' with age {age} inserted successfully.")

# Update data in the table (UPDATE operation)


def update_user(id, name, age):
cursor.execute('''
UPDATE users
SET name = ?, age = ?
WHERE id = ?
''', (name, age, id))
conn.commit()
print(f"User with ID {id} updated to name '{name}' and age {age}.")
def delete_user(id):
cursor.execute('''
DELETE FROM users
WHERE id = ?
''', (id,))
conn.commit()
print(f"User with ID {id} deleted successfully.")

# 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()

# Insert new users


insert_user('Alice', 30)
insert_user('Bob', 25)
display_users()
update_user(1, 'Alice Updated', 31)
display_users()
delete_user(2)
display_users()
conn.close()
AQ1. Write a function that takes a number as an input parameter and returns the
corresponding number name in words. For example: if input is 452, the function should
return “Four Five Two”. Use a dictionary for mapping digits to their string representation.
def number_to_words(number):

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)

word_list = [digit_map[digit] for digit in number_str if digit in digit_map]


return " ".join(word_list)

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.

from collections import Counter


def find_duplicates(input_list):
count = Counter(input_list)
duplicates = [item for item, freq in count.items() if freq > 1]
return duplicates
input_list = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 2, 3]
duplicates = find_duplicates(input_list)
print(f"The elements that appear more than once are: {duplicates}")
AQ3. Write a function that reads a file and copies only alternative lines to another file.
Alternative lines copied should be the odd numbers lines. Handle all exceptions that can be
raised.
def copy_alternate_lines(input_filename, output_filename):
try:
with open(input_filename, 'r') as infile:
# Open the output file for writing
with open(output_filename, 'w') as outfile:

for line_number, line in enumerate(infile, start=1):


if line_number % 2 != 0:
outfile.write(line)
print(f"Successfully copied alternative (odd-numbered) lines to {output_filename}.")
except FileNotFoundError:
print(f"Error: The file '{input_filename}' was not found.")
except IOError as e:
print(f"IO Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
input_filename = "input.txt" # Specify your input file
output_filename = "output.txt" # Specify your output file
copy_alternate_lines(input_filename, output_filename)
AQ4. Write a Python program that accepts a space separated sequence of words as input
and prints the words in a hyphen-separated sequence after sorting them alphabetically.
def sort_words_and_convert_to_hyphen(words_input):

words = words_input.split()
words.sort()

hyphen_separated = '-'.join(words)

return hyphen_separated

words_input = input("Enter a space-separated sequence of words: ")


result = sort_words_and_convert_to_hyphen(words_input)
print("Sorted words in hyphen-separated sequence:", result)

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

merged_list = list1 + list2


merged_list.sort()

return merged_list

L1 = [1, 5, 9]
L2 = [2, 4, 6]

result = merge_and_sort_lists(L1, L2)


print("Merged and sorted list:", result)

You might also like