Computer Science Programs
Database Connectivity
1. Connect to a MySQL Database and Create a Table
import [Link]
def create_table():
conn = [Link](
host="localhost",
user="root",
password="your_password",
database="test_db"
)
cursor = [Link]()
[Link]('''CREATE TABLE IF NOT EXISTS users
(id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT)''')
[Link]()
[Link]()
create_table()
print("Table created successfully!")
2. Insert Data into a MySQL Database
import [Link]
def insert_data(name, age):
conn = [Link](
host="localhost",
user="root",
password="your_password",
database="test_db"
)
cursor = [Link]()
[Link]('''INSERT INTO users (name, age) VALUES (%s, %s)''', (name, age))
[Link]()
[Link]()
insert_data("John Doe", 30)
insert_data("Jane Smith", 25)
print("Data inserted successfully!")
3. Query Data from a MySQL Database
import [Link]
def query_data():
conn = [Link](
host="localhost",
user="root",
password="your_password",
database="test_db"
)
cursor = [Link]()
[Link]('''SELECT * FROM users''')
rows = [Link]()
for row in rows:
print(row)
[Link]()
query_data()
Sorting and Binary Search
1. Bubble Sort to Sort a List of Numbers in Ascending Order
def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
return lst
# Example usage
numbers = [4, 1, 9, 2, 5]
print("Sorted list (Bubble Sort):", bubble_sort(numbers))
2. Selection Sort to Sort a List of Numbers in Ascending Order
def selection_sort(lst):
n = len(lst)
for i in range(n):
min_index = i
for j in range(i+1, n):
if lst[j] < lst[min_index]:
min_index = j
lst[i], lst[min_index] = lst[min_index], lst[i]
return lst
# Example usage
numbers = [4, 1, 9, 2, 5]
print("Sorted list (Selection Sort):", selection_sort(numbers))
3. Implement Binary Search to Find an Element in a Sorted List
def binary_search(lst, target):
left, right = 0, len(lst) - 1
while left <= right:
mid = (left + right) // 2
if lst[mid] == target:
return mid
elif lst[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Target not found
# Example usage
sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 5
result = binary_search(sorted_list, target)
print(f"Element {target} found at index:", result)
Dictionaries
1. Count the Frequency of Characters in a String
def count_characters(s):
frequency = {}
for char in s:
frequency[char] = [Link](char, 0) + 1
return frequency
# Example usage
string = "hello world"
print("Character frequency:", count_characters(string))
2. Find Common Keys Between Two Dictionaries
def common_keys(dict1, dict2):
return list([Link]() & [Link]())
# Example usage
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 4, 'c': 5, 'd': 6}
print("Common keys:", common_keys(dict1, dict2))
3. Find the Key with the Maximum Value
def max_value_key(d):
return max(d, key=[Link])
# Example usage
data = {'apple': 50, 'banana': 20, 'cherry': 75}
print("Key with maximum value:", max_value_key(data))
4. Invert a Dictionary (Swap Keys and Values)
def invert_dictionary(d):
return {v: k for k, v in [Link]()}
# Example usage
original_dict = {'a': 1, 'b': 2, 'c': 3}
print("Inverted dictionary:", invert_dictionary(original_dict))
5. Group Elements by Their Frequency
def group_by_frequency(lst):
frequency = {}
for item in lst:
frequency[item] = [Link](item, 0) + 1
grouped = {}
for key, value in [Link]():
[Link](value, []).append(key)
return grouped
# Example usage
lst = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
print("Grouped by frequency:", group_by_frequency(lst))
Functions
1 Function to Calculate Factorial of a Number
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Example usage
num = 5
print(f"The factorial of {num} is {factorial(num)}")
2 Function to Check if a Number is Prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Example usage
number = 17
print(f"Is {number} a prime number? {'Yes' if is_prime(number) else 'No'}")
3 Function to Find the GCD of Two Numbers
def gcd(a, b):
while b:
a, b = b, a % b
return a
# Example usage
num1, num2 = 56, 98
print(f"The GCD of {num1} and {num2} is {gcd(num1, num2)}")
4 Function to Generate Fibonacci Sequence
def fibonacci(n):
fib_sequence = [0, 1]
for i in range(2, n):
fib_sequence.append(fib_sequence[i - 1] + fib_sequence[i - 2])
return fib_sequence[:n]
# Example usage
terms = 10
print(f"The first {terms} terms of the Fibonacci sequence are: {fibonacci(terms)}")
5 Function to Check if a String is a Palindrome
def is_palindrome(s):
s = [Link]().replace(" ", "") # Normalize the string
return s == s[::-1]
# Example usage
string = "A man a plan a canal Panama"
print(f"Is the string '{string}' a palindrome? {'Yes' if is_palindrome(string) else 'No'}")
SQL Queries
1. Create a Table for Student Performance Details
CREATE TABLE StudentPerformance (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
MathMarks INT,
ScienceMarks INT,
EnglishMarks INT);
2. Insert Data into the StudentPerformance Table
INSERT INTO StudentPerformance (StudentID, Name, MathMarks, ScienceMarks,
EnglishMarks) VALUES
(1, 'Alice', 85, 90, 88),
(2, 'Bob', 78, 88, 80),
(3, 'Charlie', 92, 95, 85),
(4, 'David', 70, 65, 72);
3. Retrieve Students with Average Marks Above 80
SELECT Name, (MathMarks + ScienceMarks + EnglishMarks) / 3 AS AverageMarks
FROM StudentPerformance
WHERE (MathMarks + ScienceMarks + EnglishMarks) / 3 > 80;
4. Find the Top Scorer in Science
SELECT Name, ScienceMarks
FROM StudentPerformance
ORDER BY ScienceMarks DESC
LIMIT 1;
5. Update Marks for a Student Who Improved Performance
UPDATE StudentPerformance
SET MathMarks = 88, ScienceMarks = 89, EnglishMarks = 90
WHERE Name = 'David';
Stack operations
1. Reverse a List Using a Stack
def reverse_list(lst):
stack = []
for item in lst:
[Link](item)
reversed_list = []
while stack:
reversed_list.append([Link]())
return reversed_list
# Example usage
original_list = [1, 2, 3, 4, 5]
print("Original List:", original_list)
print("Reversed List:", reverse_list(original_list))
2. Convert Infix Expression to Postfix Using a Stack
def precedence(op):
if op in {'+', '-'}:
return 1
if op in {'*', '/'}:
return 2
return 0
def infix_to_postfix(expression):
stack = []
postfix = []
for char in expression:
if [Link]():
[Link](char)
elif char == '(':
[Link](char)
elif char == ')':
while stack and stack[-1] != '(':
[Link]([Link]())
[Link]()
else:
while stack and precedence(stack[-1]) >= precedence(char):
[Link]([Link]())
[Link](char)
while stack:
[Link]([Link]())
return ''.join(postfix)
# Example usage
expression = "a+b*(c^d-e)^(f+g*h)-i"
print(f"Infix: {expression}")
print(f"Postfix: {infix_to_postfix(expression)}")
3. Implement a Stack with Push, Pop, and Display Operations
class Stack:
def __init__(self):
[Link] = []
def push(self, item):
[Link](item)
def pop(self):
if self.is_empty():
return "Stack is empty!"
return [Link]()
def display(self):
return [Link] if not self.is_empty() else "Stack is empty!"
def is_empty(self):
return len([Link]) == 0
# Example usage
s = Stack()
[Link](10)
[Link](20)
[Link](30)
print("Stack after pushes:", [Link]())
print("Popped item:", [Link]())
print("Stack after pop:", [Link]())
4 Find the Maximum Element in a Stack Without Using Built-in Functions
def find_max(stack):
if not stack:
return "Stack is empty!"
max_value = stack[0]
for item in stack:
if item > max_value:
max_value = item
return max_value
# Example usage
stack = [3, 1, 4, 1, 5, 9]
print("Maximum element in the stack:", find_max(stack))
5 Evaluate a Postfix Expression Using a Stack
def evaluate_postfix(expression):
stack = []
for char in expression:
if [Link]():
[Link](int(char))
else:
operand2 = [Link]()
operand1 = [Link]()
if char == '+':
[Link](operand1 + operand2)
elif char == '-':
[Link](operand1 - operand2)
elif char == '*':
[Link](operand1 * operand2)
elif char == '/':
[Link](operand1 // operand2) # Integer division
return stack[0]
# Example usage
postfix_expression = "231*+9-"
print(f"Postfix Expression: {postfix_expression}")
print(f"Evaluation Result: {evaluate_postfix(postfix_expression)}")