0% found this document useful (0 votes)
14 views8 pages

3MCA For Coding Question Bank

Uploaded by

Nanda S Reddy
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)
14 views8 pages

3MCA For Coding Question Bank

Uploaded by

Nanda S Reddy
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/ 8

3MCA for Coding Question Bank

#1. Write a Python program to find the second largest element in an array.
def second_largest(arr):
unique_arr = list(set(arr))
unique_arr.sort(reverse=True)
return unique_arr[1] if len(unique_arr) > 1 else None

# 2. Write a Python program to implement a stack using a list.


class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop() if not self.is_empty() else "Stack is empty"
def peek(self):
return self.stack[-1] if not self.is_empty() else "Stack is empty"

def is_empty(self):
return len(self.stack) == 0

# 3. Write a Python program to check for balanced parentheses using a stack.


def is_balanced_parentheses(expression):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in expression:
if char in mapping.values():
stack.append(char)
elif char in mapping.keys():
if stack and stack[-1] == mapping[char]:
stack.pop()
else:
return False
return not stack

# Topic: Data Structures - Queues

# 4. Write a Python program to implement a queue using a list.


class Queue:
def __init__(self):
self.queue = []

def enqueue(self, item):


self.queue.append(item)
def dequeue(self):
return self.queue.pop(0) if not self.is_empty() else "Queue is empty"

def is_empty(self):
return len(self.queue) == 0

# 5. Write a Python program to implement a circular queue.


class CircularQueue:
def __init__(self, capacity):
self.queue = [None] * capacity
self.capacity = capacity
self.front = self.rear = -1

def enqueue(self, item):


if (self.rear + 1) % self.capacity == self.front:
return "Queue is full"
elif self.is_empty():
self.front = self.rear = 0
else:
self.rear = (self.rear + 1) % self.capacity
self.queue[self.rear] = item

def dequeue(self):
if self.is_empty():
return "Queue is empty"
item = self.queue[self.front]
if self.front == self.rear:
self.front = self.rear = -1
else:
self.front = (self.front + 1) % self.capacity
return item

def is_empty(self):
return self.front == -1

# Topic: Data Structures - Linked Lists

# 6. Write a Python program to implement a singly linked list.


class Node:
def __init__(self, data):
self.data = data
self.next = None

class SinglyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node

def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")

# 7. Write a Python program to reverse a linked list.


def reverse_linked_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev

# Topic: Functions and Recursion

# 8. Write a Python function to compute the factorial of a number using recursion.


def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

# 9. Write a Python program to implement the Fibonacci sequence using recursion.


def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

# 10. Write a Python program to solve the Tower of Hanoi problem.


def tower_of_hanoi(n, source, target, auxiliary):
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
tower_of_hanoi(n - 1, source, auxiliary, target)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n - 1, auxiliary, target, source)

# Topic: Basic Concepts of Object-Oriented Programming

# 11. Write a Python program to implement a simple class for a Bank Account.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance

def deposit(self, amount):


self.balance += amount

def withdraw(self, amount):


if amount > self.balance:
return "Insufficient funds"
self.balance -= amount

# 12. Write a Python program to demonstrate inheritance with a base class Animal and derived class Dog.
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
pass

class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"

# 13. Write a Python program to demonstrate polymorphism with a base class Shape and derived classes.
class Shape:
def area(self):
pass

class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height

def area(self):
return self.width * self.height

class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius

# 14. Write a Python program to demonstrate encapsulation by implementing a private attribute.


class Student:
def __init__(self, name, age):
self.__age = age # Private attribute
self.name = name

def get_age(self):
return self.__age

def set_age(self, age):


if age > 0:
self.__age = age

# 15. Write a Python program to demonstrate method overriding in inheritance.


class Parent:
def show_message(self):
return "Message from Parent"

class Child(Parent):
def show_message(self):
return "Message from Child"

# 16. Write a Python program to implement operator overloading for addition.


class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag

def __add__(self, other):


return ComplexNumber(self.real + other.real, self.imag + other.imag)

# 17. Write a Python program to demonstrate multiple inheritance.


class ClassA:
def method_a(self):
return "Method A"

class ClassB:
def method_b(self):
return "Method B"

class ClassC(ClassA, ClassB):


pass

# 18. Write a Python program to implement class-level attributes and methods.


class Employee:
company_name = "TechCorp" # Class-level attribute

@classmethod
def get_company_name(cls):
return cls.company_name

# 19. Write a Python program to perform inorder traversal of a binary tree.

class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None

def inorder_traversal(root):
if root:
inorder_traversal(root.left)
print(root.value, end=" ")
inorder_traversal(root.right)

#20. Write a Python program to check if a binary tree is a binary search tree.
def is_bst(root, min_val=float('-inf'), max_val=float('inf')):
if not root:
return True
if not (min_val < root.value < max_val):
return False
return is_bst(root.left, min_val, root.value) and is_bst(root.right, root.value, max_val)

#21.Write a Python program to implement Depth First Search (DFS) for a graph.

def dfs(graph, start, visited=None):


if visited is None:
visited = set()
visited.add(start)
print(start, end=" ")
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)

#22.Write a Python program to implement Breadth First Search (BFS) for a graph.
from collections import deque

def bfs(graph, start):


visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
print(vertex, end=" ")
queue.extend(neighbor for neighbor in graph[vertex] if neighbor not in visited)
#23.Write a Python program to implement binary search.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1

#24.Write a Python program to implement bubble sort.

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]

#25. Write a Python program to implement merge sort.


def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]

merge_sort(left)
merge_sort(right)

i=j=k=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1

while i < len(left):


arr[k] = left[i]
i += 1
k += 1

while j < len(right):


arr[k] = right[j]
j += 1
k += 1

# 26. Write a Python program to solve the 0/1 Knapsack problem using dynamic programming.
def knapsack(values, weights, capacity):
n = len(values)
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]

for i in range(1, n + 1):


for w in range(1, capacity + 1):
if weights[i - 1] <= w:
dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1])
else:
dp[i][w] = dp[i - 1][w]

return dp[n][capacity]

#27.Write a Python program to find the longest common subsequence using dynamic programming.
def lcs(x, y):
m, n = len(x), len(y)
dp = [[0] * (n + 1) for _ in range(m + 1)]

for i in range(1, m + 1):


for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

return dp[m][n]

You might also like