Nothing Special   »   [go: up one dir, main page]

Computerscience

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 15

1.

Functions (5 to 6 programs)

Program 1: Calculate Factorial


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

print(factorial(5)) # Output: 120

*Output:*

120

Program 2: Check Prime Number


python
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

print(is_prime(11)) # Output: True


print(is_prime(4)) # Output: False

*Output:*

True
False

Program 3: Fibonacci Series


python
def fibonacci(n):
fib_series = [0, 1]
while len(fib_series) < n:
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series

print(fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

*Output:*

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Program 4: Sum of List Elements


python
def sum_of_list(lst):
return sum(lst)

print(sum_of_list([1, 2, 3, 4, 5])) # Output: 15

*Output:*
15

Program 5: Reverse a String


python
def reverse_string(s):
return s[::-1]

print(reverse_string("Hello")) # Output: "olleH"

*Output:*

olleH

Program 6: Find Maximum Number in a List


python
def find_max(lst):
return max(lst)

print(find_max([1, 2, 3, 4, 5])) # Output: 5

*Output:*

2. File Handling (10 programs)

Program 1: Write to a File


python
def write_to_file(filename, content):
with open(filename, 'w') as file:
file.write(content)

write_to_file('example.txt', 'Hello, World!')

*Output:*

Content written to example.txt (Check the file "example.txt")

Program 2: Read from a File


python
def read_from_file(filename):
with open(filename, 'r') as file:
return file.read()

print(read_from_file('example.txt')) # Output: "Hello, World!"

*Output:*

Hello, World!

Program 3: Append to a File


python
def append_to_file(filename, content):
with open(filename, 'a') as file:
file.write(content)

append_to_file('example.txt', '\nAppend this text.')

*Output:*

Content appended to example.txt (Check the file "example.txt")

Program 4: Count Words in a File


python
def count_words(filename):
with open(filename, 'r') as file:
content = file.read()
words = content.split()
return len(words)

print(count_words('example.txt')) # Output will vary based on the file content

*Output:*

Output will vary (Count of words in "example.txt")

Program 5: Copy File Content


python
def copy_file(source, destination):
with open(source, 'r') as src:
content = src.read()
with open(destination, 'w') as dest:
dest.write(content)

copy_file('example.txt', 'example_copy.txt')

*Output:*

Content copied to example_copy.txt (Check the file "example_copy.txt")

Program 6: Count Lines in a File


python
def count_lines(filename):
with open(filename, 'r') as file:
return len(file.readlines())

print(count_lines('example.txt')) # Output will vary based on the file content

*Output:*

Output will vary (Count of lines in "example.txt")

Program 7: Read File Line by Line


python
def read_file_line_by_line(filename):
with open(filename, 'r') as file:
for line in file:
print(line.strip())
read_file_line_by_line('example.txt')

*Output:*

Hello, World!
Append this text.

Program 8: Write List to File


python
def write_list_to_file(filename, lst):
with open(filename, 'w') as file:
for item in lst:
file.write(f"{item}\n")

write_list_to_file('list.txt', [1, 2, 3, 4, 5])

*Output:*

List written to list.txt (Check the file "list.txt")

Program 9: Read List from File


python
def read_list_from_file(filename):
with open(filename, 'r') as file:
return [line.strip() for line in file]

print(read_list_from_file('list.txt')) # Output: [1, 2, 3, 4, 5]

*Output:*

['1', '2', '3', '4', '5']

Program 10: Find Longest Line in a File


python
def find_longest_line(filename):
with open(filename, 'r') as file:
longest = ''
for line in file:
if len(line) > len(longest):
longest = line
return longest.strip()

print(find_longest_line('example.txt')) # Output will vary based on the file


content

*Output:*

Append this text.

3. Data Structures (9 to 15 programs)

Program 1: Stack Implementation


python
class Stack:
def __init__(self):
self.items = []

def push(self, item):


self.items.append(item)

def pop(self):
if not self.is_empty():
return self.items.pop()

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

def peek(self):
if not self.is_empty():
return self.items[-1]

def size(self):
return len(self.items)

stack = Stack()
stack.push(1)
stack.push(2)
print(stack.pop()) # Output: 2
print(stack.peek()) # Output: 1
print(stack.size()) # Output: 1

*Output:*

2
1
1

Program 2: Queue Implementation


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

def enqueue(self, item):


self.items.insert(0, item)

def dequeue(self):
if not self.is_empty():
return self.items.pop()

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

def size(self):
return len(self.items)

queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
print(queue.dequeue()) # Output: 1
print(queue.size()) # Output: 1

*Output:*
1
1

Program 3: Linked List Implementation


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

class LinkedList:
def __init__(self):
self.head = None

def insert(self, data):


new_node = Node(data)
new_node.next = self.head
self.head = new_node

def print_list(self):
current = self.head
while current:
print(current.data, end=' ')
current = current.next

ll = LinkedList()
ll.insert(1)
ll.insert(2)
ll.insert(3)
ll.print_list() # Output: 3 2 1

*Output:*

3 2 1

Program 4: Binary Search Tree Implementation


python
class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key

def insert(root, key):


if root is None:
return TreeNode(key)
else:
if root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root

def inorder(root):
if root:
inorder(root.left)
print(root.val, end=' ')
inorder(root.right)

root = TreeNode(50)
root = insert(root, 30)
root = insert(root, 20)
root = insert(root, 40)
root = insert(root, 70)
root = insert(root, 60)
root = insert(root, 80)

inorder(root) # Output: 20 30 40 50 60 70 80

*Output:*

20 30 40 50 60 70 80

Program 5: Hash Table Implementation

python
class HashTable:
def __init__(self):
self.size = 10
self.table = [[] for _ in range(self.size)]

def hash_function(self, key):


return key % self.size

def insert(self, key, value):


hash_key = self.hash_function(key)
key_exists = False
bucket = self.table[hash_key]
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
bucket[i] = (key, value)
else:
bucket.append((key, value))

def search(self, key):


hash_key = self.hash_function(key)
bucket = self.table[hash_key]
for k, v in bucket:
if key == k:
return v
return None

hash_table = HashTable()
hash_table.insert(1, 'One')
hash_table.insert(2, 'Two')
hash_table.insert(12, 'Twelve')
print(hash_table.search(1)) # Output: One
print(hash_table.search(12)) # Output: Twelve
print(hash_table.search(5)) # Output: None
*Output:*

One
Twelve
None

Program 6: Graph Representation (Adjacency List)

python
class Graph:
def __init__(self):
self.graph = {}

def add_edge(self, node, neighbor):


if node not in self.graph:
self.graph[node] = []
self.graph[node].append(neighbor)

def display(self):
for node in self.graph:
print(node, '->', ' -> '.join([str(neighbor) for neighbor in
self.graph[node]]))

graph = Graph()
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(2, 0)
graph.add_edge(2, 3)
graph.add_edge(3, 3)
graph.display()

*Output:*

0 -> 1 -> 2
1 -> 2
2 -> 0 -> 3
3 -> 3

Program 7: Breadth-First Search (BFS)

python
from collections import deque

def bfs(graph, start):


visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
print(vertex, end=' ')
visited.add(vertex)
queue.extend(set(graph[vertex]) - visited)

graph = {
0: [1, 2],
1: [2],
2: [0, 3],
3: [3]
}
bfs(graph, 2) # Output: 2 0 3 1

*Output:*

2 0 3 1

Program 8: Depth-First Search (DFS)

python
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=' ')
for next in set(graph[start]) - visited:
dfs(graph, next, visited)

graph = {
0: [1, 2],
1: [2],
2: [0, 3],
3: [3]
}
dfs(graph, 2) # Output: 2 0 1 3

*Output:*

2 0 1 3

Program 9: Insertion Sort

python
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

print(insertion_sort([12, 11, 13, 5, 6])) # Output: [5, 6, 11, 12, 13]

*Output:*

[5, 6, 11, 12, 13]

4. Python-MySQL Connectivity (Airlines Context)

Program 1: Connect to MySQL Database

python
import mysql.connector
def connect_db():
return mysql.connector.connect(
host='localhost',
user='yourusername',
password='yourpassword',
database='yourdatabase'
)

db = connect_db()
if db.is_connected():
print('Connected to MySQL database')

*Output:*

Connected to MySQL database

Program 2: Create Tables

python
def create_tables():
db = connect_db()
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS Staff (
staff_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
position VARCHAR(255) NOT NULL,
salary DECIMAL(10, 2)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS Flights (
flight_id INT AUTO_INCREMENT PRIMARY KEY,
airline VARCHAR(255) NOT NULL,
destination VARCHAR(255) NOT NULL,
departure_time TIME NOT NULL
)
''')
db.close()

create_tables()

*Output:*

No output (Tables are created in the database)

Program 3: Insert Data into Tables

python
def insert_staff(name, position, salary):
db = connect_db()
cursor = db.cursor()
sql = 'INSERT INTO Staff (name, position, salary) VALUES (%s, %s, %s)'
val = (name, position, salary)
cursor.execute(sql, val)
db.commit()
db.close()

def insert_flight(airline, destination, departure_time):


db = connect_db()
cursor = db.cursor()
sql = 'INSERT INTO Flights (airline, destination, departure_time) VALUES (%s,
%s, %s)'
val = (airline, destination, departure_time)
cursor.execute(sql, val)
db.commit()
db.close()

insert_staff('Alice Brown', 'Pilot', 95000)


insert_staff('Bob Smith', 'Flight Attendant', 45000)
insert_flight('Air India', 'New York', '10:30:00')
insert_flight('Lufthansa', 'Berlin', '14:00:00')

*Output:*

No output (Data is inserted into the database)

Program 4: Fetch Data from Tables

python
def fetch_staff():
db = connect_db()
cursor = db.cursor()
cursor.execute('SELECT * FROM Staff')
result = cursor.fetchall()
for row in result:
print(row)
db.close()

def fetch_flights():
db = connect_db()
cursor = db.cursor()
cursor.execute('SELECT * FROM Flights')
result = cursor.fetchall()
for row in result:
print(row)
db.close()

fetch_staff()
fetch_flights()

*Output:*

(1, 'Alice Brown', 'Pilot', 95000.00)


(2, 'Bob Smith', 'Flight Attendant', 45000.00)
(1, 'Air India', 'New York', '10:30:00')
(2, 'Lufthansa', 'Berlin', '14:00:00')

Program 5: Update Data in Tables

python
def update_staff_salary(name, new_salary):
db = connect_db()
cursor = db.cursor()
sql = 'UPDATE Staff SET salary = %s WHERE name = %s'
val = (new_salary, name)
cursor.execute(sql, val)
db.commit()
db.close()

def update_flight_time(flight_id, new_time):


db = connect_db()
cursor = db.cursor()
sql = 'UPDATE Flights SET departure_time = %s WHERE flight_id = %s'
val = (new_time, flight_id)
cursor.execute(sql, val)
db.commit()
db.close()

update_staff_salary('Alice Brown', 100000)


update_flight_time(1, '11:00:00')

*Output:*

No output (Data is updated in the database)

Program 6: Delete Data from Tables

python
def delete_staff(name):
db = connect_db()
cursor = db.cursor()
sql = 'DELETE FROM Staff WHERE name = %s'
val = (name,)
cursor.execute(sql, val)
db.commit()
db.close()

def delete_flight(flight_id):
db = connect_db()
cursor = db.cursor()
sql = 'DELETE FROM Flights WHERE flight_id = %s'
val = (flight_id,)
cursor.execute(sql, val)
db.commit()
db.close()

delete_staff('Bob Smith')
delete_flight(2)

*Output:*

No output (Data is deleted from the database)

5. SQL Queries (Airlines Context)

Table 1: Staff

sql
CREATE TABLE Staff (
staff_id INT PRIMARY KEY,
name VARCHAR(255),
position VARCHAR(255),
salary DECIMAL(10, 2)
);

INSERT INTO Staff (staff_id, name, position, salary) VALUES


(1, 'Alice Brown', 'Pilot', 95000.00),
(2, 'Bob Smith', 'Flight Attendant', 45000.00),
(3, 'Charlie Davis', 'Co-pilot', 70000.00);

##### Queries

1. *Select all staff members:*


sql
SELECT * FROM Staff;

*Output:*

+----------+--------------+------------------+----------+
| staff_id | name | position | salary |
+----------+--------------+------------------+----------+
| 1 | Alice Brown | Pilot | 95000.00 |
| 2 | Bob Smith | Flight Attendant | 45000.00 |
| 3 | Charlie Davis| Co-pilot | 70000.00 |
+----------+--------------+------------------+----------+

2. *Find staff with salary greater than 60,000:*


sql
SELECT * FROM Staff WHERE salary > 60000;

*Output:*

+----------+--------------+------------------+----------+
| staff_id | name | position | salary |
+----------+--------------+------------------+----------+
| 1 | Alice Brown | Pilot | 95000.00 |
| 3 | Charlie Davis| Co-pilot | 70000.00 |
+----------+--------------+------------------+----------+

3. *Count total number of staff:*


sql
SELECT COUNT(*) FROM Staff;

*Output:*

+----------+
| COUNT(*) |
+----------+
| 3 |
+----------+

4. *Find the average salary of staff:*


sql
SELECT AVG(salary) FROM Staff;
*Output:*

+-------------+
| AVG(salary) |
+-------------+
| 70000.0000 |
+-------------+

5. *Find staff by position:*


sql
SELECT * FROM Staff WHERE position = 'Pilot';

*Output:*

+----------+--------------+----------+----------+
| staff_id | name | position | salary |
+----------+--------------+----------+----------+
| 1 | Alice Brown | Pilot | 95000.00 |
+----------+--------------+----------+----------+

Table 2: Flights

sql
CREATE TABLE Flights (
flight_id INT PRIMARY KEY,
airline VARCHAR(255),
destination VARCHAR(255),
departure_time TIME
);

INSERT INTO Flights (flight_id, airline, destination, departure_time) VALUES


(1, 'Air India', 'New York', '10:30:00'),
(2, 'Lufthansa', 'Berlin', '14:00:00'),
(3, 'Emirates', 'Dubai', '09:00:00');

##### Queries

1. *Select all flights:*


sql
SELECT * FROM Flights;

*Output:*

+----------+-----------+-------------+----------------+
| flight_id| airline | destination | departure_time |
+----------+-----------+-------------+----------------+
| 1 | Air India | New York | 10:30:00 |
| 2 | Lufthansa | Berlin | 14:00:00 |
| 3 | Emirates | Dubai | 09:00:00 |
+----------+-----------+-------------+----------------+

2. *Find flights to a specific destination:*


sql
SELECT * FROM Flights WHERE destination = 'Berlin';
*Output:*

+----------+-----------+-------------+----------------+
| flight_id| airline | destination | departure_time |
+----------+-----------+-------------+----------------+
| 2 | Lufthansa | Berlin | 14:00:00 |
+----------+-----------+-------------+----------------+

3. *Count total number of flights:*


sql
SELECT COUNT(*) FROM Flights;

*Output:*

+----------+
| COUNT(*) |
+----------+
| 3 |
+----------+

4. *Find the earliest departure time:*


sql
SELECT MIN(departure_time) FROM Flights;

*Output:*

+--------------------+
| MIN(departure_time)|
+--------------------+
| 09:00:00 |
+--------------------+

5. *Find flights by airline:*


sql
SELECT * FROM Flights WHERE airline = 'Emirates';

*Output:*

+----------+-----------+-------------+----------------+
| flight_id| airline | destination | departure_time |
+----------+-----------+-------------+----------------+
| 3 | Emirates | Dubai | 09:00:00 |
+----------+-----------+-------------+----------------+

You might also like