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

computer science programs

The document provides a comprehensive overview of various computer science programming concepts, including database connectivity with MySQL, sorting algorithms, and dictionary operations. It includes code snippets for creating tables, inserting and querying data, as well as sorting lists and implementing binary search. Additionally, it covers functions for mathematical calculations, SQL queries for student performance, and stack operations such as reversing a list and evaluating postfix expressions.

Uploaded by

mishraadya0407
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)
9 views

computer science programs

The document provides a comprehensive overview of various computer science programming concepts, including database connectivity with MySQL, sorting algorithms, and dictionary operations. It includes code snippets for creating tables, inserting and querying data, as well as sorting lists and implementing binary search. Additionally, it covers functions for mathematical calculations, SQL queries for student performance, and stack operations such as reversing a list and evaluating postfix expressions.

Uploaded by

mishraadya0407
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/ 13

Computer Science Programs

Database Connectivity

1. Connect to a MySQL Database and Create a Table


import mysql.connector
def create_table():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="test_db"
)
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT)''')
conn.commit()
conn.close()

create_table()
print("Table created successfully!")

2. Insert Data into a MySQL Database


import mysql.connector

def insert_data(name, age):


conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="test_db"
)
cursor = conn.cursor()
cursor.execute('''INSERT INTO users (name, age) VALUES (%s, %s)''', (name, age))
conn.commit()
conn.close()

insert_data("John Doe", 30)


insert_data("Jane Smith", 25)
print("Data inserted successfully!")

3. Query Data from a MySQL Database


import mysql.connector
def query_data():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="test_db"
)
cursor = conn.cursor()
cursor.execute('''SELECT * FROM users''')
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()

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] = frequency.get(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(dict1.keys() & dict2.keys())

# 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=d.get)

# 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 d.items()}

# 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] = frequency.get(item, 0) + 1
grouped = {}
for key, value in frequency.items():
grouped.setdefault(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 = s.lower().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:
stack.append(item)
reversed_list = []
while stack:
reversed_list.append(stack.pop())
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 char.isalnum():
postfix.append(char)
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
postfix.append(stack.pop())
stack.pop()
else:
while stack and precedence(stack[-1]) >= precedence(char):
postfix.append(stack.pop())
stack.append(char)
while stack:
postfix.append(stack.pop())
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):
self.stack = []

def push(self, item):


self.stack.append(item)

def pop(self):
if self.is_empty():
return "Stack is empty!"
return self.stack.pop()

def display(self):
return self.stack if not self.is_empty() else "Stack is empty!"
def is_empty(self):
return len(self.stack) == 0

# Example usage
s = Stack()
s.push(10)
s.push(20)
s.push(30)
print("Stack after pushes:", s.display())
print("Popped item:", s.pop())
print("Stack after pop:", s.display())

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 char.isdigit():
stack.append(int(char))
else:
operand2 = stack.pop()
operand1 = stack.pop()
if char == '+':
stack.append(operand1 + operand2)
elif char == '-':
stack.append(operand1 - operand2)
elif char == '*':
stack.append(operand1 * operand2)
elif char == '/':
stack.append(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)}")

You might also like