Cs Practicals
Cs Practicals
1 ''' A program to calculate the n-th term of Fibonacci series using function.
2 '''
3
4
5 def fibo(n: int, memo: dict = {}) -> int:
6 ''' The name 'Fibonacci' is due to a 13th-century Italian mathematician
7 Leonardo of Pisa, who later came to be known as Fibonacci.
8 However, what we popularly call 'Fibonacci numbers' find their earliest
mention in the 2nd century BCE work of Acharya Pingala.
9
10 By definition,the 0-th term of the series is zero, and the 1-st term is
1.
11 Any other term is the sum of previous two terms.
12
13 This function uses the concept of memoization to decrease time
complexity
14 and increase speed.
15
16 Returns the n-th term of fibbonaci series. Returns -1 for invalid input.
17
18 Args:
19 n (int): the term
20
21 Returns:
22 int: the nth fibonacci number
23 '''
24 if n in memo:
25 return memo[n]
26
27 if n < 0:
28 print(f'Invalid Input \n{fibo.__doc__}')
29 raise ValueError('You cannot calculate fibonacci number for n < 0')
30
31 if n <= 2:
32 return 1
33
34 memo[n] = fibo(n-1, memo) + fibo(n-2, memo)
35
36 return memo[n]
37
38
39 if __name__ == "__main__":
40 # Testing whether the function works correctly
41
42 assert fibo(1) == 1
43 assert fibo(2) == 1
44 assert fibo(10) == 55
45 assert fibo(20) == 6765
46 print(f'The 50th fibonacci number is {fibo(50)}')
47 print(f'The 100th fibonacci number is {fibo(100)}')
48
Output
1
2 > python -i q01_fibo.py
3 The 50th fibonacci number is 12586269025
4 The 100th fibonacci number is 354224848179261915075
5 >>> fibo(1)
6 1
7 >>> fibo(20)
8 6765
9 >>> fibo(34)
10 5702887
11 >>> fibo(69)
12 117669030460994
13 >>> fibo(475)
14 8310824599087029352939557847011209937043690282006516138599728300807399805410
65544674812034151699525
15 >>>
16
ii. Program to search any word in given string/sentence
using function.
Code
Output
1
2 > python -i q02_wordSearch.py
3 >>> search('I love Computer Science','love')
4 [2]
5 >>> search('FAANG rules the world','India')
6 []
7 >>> search('Aeio u aeio aieo','a')
8 [7, 12]
9 >>>
10
iii. Read a text file line by line and display each word
separated by a # .
Code
1 ''' Read a text file line by line and display each word separated by a # .
2 '''
3
4
5 path = input('Enter path of the file to read \n >>> ')
6
7 try:
8 with open(path, 'r') as file:
9 while True:
10 line = file.readline()
11 if line == '':
12 break
13 for word in line.split():
14 print(word, end='#')
15
16 except FileNotFoundError:
17 print("Sorry ! File does not exist")
18
19 finally:
20 print("Done")
21
Output
1
2 > python q03_textRead.py
3 Enter path of the file to read
4 >>> data/text.txt
5 RSA#algorithm#From#Simple#English#Wikipedia,
6 kfksf#kjkfjsjflksjk#fkjsdlif#jk#kjjfkljslkfjjklj#ksdfkjskl#l#lkjijfiijkkdflij
grofkjporglrj#kljrjiodngl#pkjgjlj#kjglkjf#jlgkmflj#iodjglkjg#jgldjgljglmtioj5
o9m#okptg#;jgojg#oglg;od;
iv. Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters and
digits in the file.
Code
Output
1 ''' Read a text file and display the largest word and maximum number of
characters
2 present in a line from text file.
3 '''
4
5
6 def analyse(path: str) -> None:
7 ''' Analyses a text file and display the largest word and maximum number
of characters present in a line from text file.
8
9 Args:
10 path (str): path of the file to analyse
11 '''
12
13 with open(path, 'r') as file:
14 content = file.read()
15
16 for line_no, line in enumerate(content.splitlines(), start=1):
17
18 if len(line) != 0:
19 print(
20 f'''Line:{line_no} Character Count : {len(line)}''',
end='\t')
21 words = line.split()
22 if words:
23 print(f'Largest Word: {max(words)}')
24 else:
25 print('This line has no words')
26
27 else:
28 print(f'Line:{line_no} Empty Line')
29
30
31 if __name__ == "__main__":
32 # Run the function
33 analyse(input('Enter file path\n>>> '))
34
Output
1
2 Enter file path
3 >>> data/text.txt
4 Line:1 Empty Line
5 Line:2 Character Count : 13 Largest Word: algorithm
6 Line:3 Character Count : 52 Largest Word: the
7 Line:4 Character Count : 32 Largest Word: to
8 Line:5 Empty Line
9 Line:6 Character Count : 197 Largest Word: write
10 Line:7 Character Count : 566 Largest Word: when
11 Line:8 Empty Line
12 Line:9 Character Count : 263 Largest Word: with
13 Line:10 Empty Line
14
vi. Write a program using Dictionary and Text file to store
roman numbers and find their equivalent.
Code
1 ''' Write a program using Dictionary and Text file to store roman numbers
and find their equivalent.
2 '''
3
4
5 # base roman numbers and their integer equivalents
6 ROMAN = {
7 'I': 1,
8 'V': 5,
9 'X': 10,
10 'L': 50,
11 'C': 100,
12 'D': 500,
13 'M': 1000,
14 }
15
16
17 def parse_roman(roman_num: str) -> int:
18 ''' Parses a string which is roman numeral and returns equivalent
integer.
19
20 Args:
21 roman_num (str): Roman numeral to parse
22
23 Raises:
24 ValueError: Invalid character in roman numeral
25 ValueError: Character occured more than 3 times consecutivel
26 ValueError: Invalid roman numeral, incorrect subtractive notation
27
28 Returns:
29 int: Integer equivalent
30 '''
31
32 # stripping any space
33 roman_num = roman_num.strip()
34
35 # convert string to uppercase
36 roman_num = roman_num.upper()
37
38 # list of parsed characters
39 prev = []
40
41 # total is the value to be returned
42 total = 0
43
44 # checker for valid roman string
45 largest = 0
46
47 # iterating the roman numeral from right to left
48 for chr in roman_num[::-1]:
49
50 # get the integer value of the character, None if not in ROMAN
51 curr_num = ROMAN.get(chr)
52
53 # if current character does not exist in ROMAN dictionary
54 if not curr_num:
55 raise ValueError(f'Invalid character "{chr}" in roman numeral')
56
57 # list of last 3 characters parsed
58 last3 = prev[-3:]
59
60 # if last 3 characters exist
61 if len(last3) == 3:
62 # if all of the last 3 characters are same as current one
63 if all(chr == last for last in last3):
64 raise ValueError(
65 f'Invalid roman numeral, "{chr}" occured more than 3
times consecutively')
66
67 # if atleast one character have been already parsed
68 if prev:
69 # numeric value of last character parsed
70 last_num = ROMAN.get(prev[-1])
71
72 # if last character is numerically smaller or equal to current
one
73 if last_num <= curr_num:
74 total += curr_num
75
76 # checking validity of roman string
77 if curr_num > largest:
78 largest = curr_num
79 elif curr_num < largest:
80 raise ValueError(
81 'Invalid roman numeral, incorrect subtractive
notation')
82 else:
83 total -= curr_num
84
85 # parsing the first character, ie the last character of the roman
string
86 else:
87 total += curr_num
88 largest = curr_num
89
90 prev.append(chr)
91 return total
92
93
94 if __name__ == "__main__":
95 # Checking whether our algorithm passes all test cases
96
97 with open('data/romans.txt') as file:
98 for line in file:
99 roman, decimal = line.split(',')
100 print(f'\nTesting if "{roman}" is same as {decimal.strip()}')
101 try:
102 assert parse_roman(roman) == int(decimal)
103 print('True')
104 except ValueError as err:
105 print(err)
106 except AssertionError:
107 print(f'False. The correct decimal is
{parse_roman(roman)}')
108
Output
1
2 > cat data/romans.txt
3 xii,12
4 v,5
5 c,100
6 cii,102
7 iiv,3
8 xv,12
9
10 > py -i q06_roman.py
11
12 Testing if "xii" is same as 12
13 True
14
15 Testing if "v" is same as 5
16 True
17
18 Testing if "c" is same as 100
19 True
20
21 Testing if "cii" is same as 102
22 True
23
24 Testing if "iiv" is same as 3
25 Invalid roman numeral, incorrect subtractive notation
26
27 Testing if "xv" is same as 12
28 False. The correct decimal is 15
29 >>>
30 >>> parse_roman('xvii')
31 17
32 >>> parse_roman('ii')
33 2
34 >>> parse_roman('iiii')
35 Traceback (most recent call last):
36 File "<stdin>", line 1, in <module>
37 File "/home/aahnik/Projects/cbse-xii-cs-
proj/practicals/python/q06_roman.py", line 64, in parse_roman
38 raise ValueError(
39 ValueError: Invalid roman numeral, "I" occured more than 3 times
consecutively
40 >>> parse_roman('c')
41 100
42 >>> parse_roman('cxvii')
43 117
44 >>>
45
vii. Write a menu driven program to perform read and write
operations using a text file called “student.txt” counting
student roll_no, name and address.
Code
1 ''' Write a menu driven program to perform read and write operations using
a text file
2 called “student.txt” counting student roll_no, name and address.
3 '''
4
5
6 import os
7 from utils import drive_menu
8
9 filename = ''
10
11
12 def init(path: str) -> None:
13 ''' Creates an file `student.txt` in desired directory, if not exists.
14
15 Args:
16 path (str): Directory path
17 '''
18
19 try:
20 os.makedirs(path)
21 print("directory created")
22 except FileExistsError:
23 print("directory exists")
24
25 global filename
26 filename = os.path.join(path, 'student.txt')
27
28 if not os.path.isfile(filename):
29 # create file if does not exist
30 with open(filename, 'w+') as file:
31 file.write('Roll,Name,Address')
32 # writing the headers in first line ( line no = 0)
33 print("file `student.txt` created")
34 return
35
36 print("file `student.txt` exists in desired directory")
37
38
39 def search_student(roll: int) -> list:
40 ''' Searches the roll no. in the text file.
41
42 Args:
43 roll (int): The roll number of student
44
45 Returns:
46 list: The record list which looks like [roll,name,address]
47 None if student's record is absent
48 '''
49
50 with open(filename, 'r') as file:
51 content = file.read()
52
53 lines = content.splitlines()
54
55 def record(line): return line.split(',')
56
57 for line in lines:
58 if record(line)[0] == str(roll):
59 return record(line)
60
61 return None
62
63
64 def record_student() -> None:
65 ''' Records a new student in the text file.
66 - Roll numbers must be unique.
67 - If roll number already exists, returns False
68 '''
69 try:
70 roll = int(input("Enter Student's roll number\n>>> "))
71 except ValueError:
72 print("Roll number must be an Integer")
73 return
74 name = input("Enter name\n>>> ")
75 address = input("Enter address\n>>> ").replace('\n', ';')
76 # new line in address is not allowed
77
78 if roll <= 0:
79 print('Invalid roll no')
80 return
81 if search_student(roll):
82 print('Student already exists')
83 return
84
85 with open(filename, 'a') as file:
86 file.write(f'\n{roll},{name},{address}')
87 # multi line address is converted to single line
88 print('Successfully Recorded')
89
90
91 def read_data() -> None:
92 ''' Displays the details of the student searhced
93 '''
94 roll = input("Enter roll no. to search\n>>> ")
95 record = search_student(roll)
96 if not record:
97 print("Record not found")
98 else:
99 print(f'''
100 Name : {record[1]}
101 -------------------
102 Roll no. : {record[0]}
103
104 Address: {record[2]}
105 ''')
106
107
108 def display_all() -> None:
109 ''' Display all records.
110 '''
111 with open(filename, 'r') as file:
112 print(file.read())
113
114
115 def main():
116 ''' Drive the application.
117 '''
118
119 path = input('Enter directory path to store/retrieve data\n>>> ')
120 init(path)
121
122 menus = {}
123 menus['1'] = {'desc': 'Add new student',
124 'func': record_student}
125 menus['2'] = {'desc': 'Display details of all students',
126 'func': display_all}
127 menus['3'] = {'desc': 'Search student by roll no',
128 'func': read_data}
129 drive_menu('Student Management Portal', menus)
130
131
132 if __name__ == "__main__":
133 main()
134
Output
1
2 > python q07_student.py
3 Enter directory path to store/retrieve data
4 >>> data/students.txt
5 directory created
6 file `student.txt` created
7
8 Press [ENTER] to continue or CTRL+C to quit
9
1 >>> 1
2 Enter Student's roll number
3 >>> 45
4 Enter name
5 >>> Horrible Haru
6 Enter address
7 >>> Mars
8 Successfully Recorded
9
10 Press [ENTER] to continue or CTRL+C to quit
1 >>> 3
2 Enter roll no. to search
3 >>> 2
4 Record not found
5
6 Press [ENTER] to continue or CTRL+C to quit
1 >>> 2
2 Roll,Name,Address
3 45,Horrible Haru,Mars
4 23,Asdff,jklls
1 >>> 3
2 Enter roll no. to search
3 >>> 45
4
5 Name : Horrible Haru
6 -------------------
7 Roll no. : 45
8
9 Address: Mars
10
11
12 Press [ENTER] to continue or CTRL+C to quit
viii. Create a binary file with name and roll number. Search
for a given roll number and display the name, if not found
display appropriate message.
Code
1 ''' Create a binary file with name and roll number. Search for a given roll
2 number and display the name, if not found display appropriate message.
3 '''
4
5
6 import pickle
7 import os
8 from utils import drive_menu
9
10 students = {}
11 filename = ''
12
13
14 def init(path: str) -> None:
15 ''' Load the file. If file does not exist, creates it.
16
17 Args:
18 path (str): file path
19 '''
20
21 global students
22 if not os.path.isdir(path):
23 os.makedirs(path)
24 global filename
25 filename = os.path.join(path, 'student.bin')
26 if not os.path.isfile(filename):
27 with open(filename, 'wb') as file:
28 pickle.dump(students, file)
29 else:
30 with open(filename, 'rb') as file:
31 students = pickle.load(file)
32
33
34 def record() -> None:
35 ''' Record a new student.
36 '''
37 roll = input('Enter roll: ')
38 name = input('Enter name: ')
39 student = {roll: name}
40 try:
41 students.update(student)
42 with open(filename, 'wb') as file:
43 pickle.dump(students, file)
44 print('Successfully recorded student')
45 except Exception as e:
46 print(f'Failed to record student due to error \n {e}')
47
48
49 def search() -> None:
50 ''' Search for an existing student.
51 '''
52 roll = input('Enter roll to search student: ')
53 try:
54 print(f'Student found : {students[roll]}')
55 except KeyError:
56 print('Student not found in records')
57
58
59 def main():
60 ''' Driving the app.
61 '''
62
63 path = input('Enter directory path to store/retrieve data\n >>> ')
64 init(path)
65
66 menus = {}
67
68 menus['1'] = {'desc': 'Record new student',
69 'func': record}
70 menus['2'] = {'desc': 'Search student by roll',
71 'func': search}
72
73 drive_menu('Student Management', menus)
74
75
76 if __name__ == "__main__":
77 main()
78
Output
1
2 MENU for Student Management
3
4 ╒══════════╤════════════════════════╕
5 │ Choice │ Description │
6 ╞══════════╪════════════════════════╡
7 │ 1 │ Record new student │
8 ├──────────┼────────────────────────┤
9 │ 2 │ Search student by roll │
10 ╘══════════╧════════════════════════╛
11 Enter your choice or X to quit
12
13 >>>
1 >>> 2
2 Enter roll to search student: 12
3 Student found : Jack Dorsey
4
5 Press [ENTER] to continue or CTRL+C to quit
ix. Create a binary file with roll number, name and marks.
Input a roll number and update the marks.
Code
1 ''' Create a binary file with roll number, name and marks. Input a roll
2 number and update the marks.
3 '''
4
5
6 import pickle
7 from utils import drive_menu
8 from tabulate import tabulate
9 import os
10
11 # in data folder of current directory
12 filename = os.path.join('data', 'marks.bin')
13
14 students = {} # dictionary containing students
15
16
17 def load_file() -> None:
18 with open(filename, 'rb') as file:
19 global students
20 students = pickle.load(file)
21
22
23 def write_to_file() -> None:
24 with open(filename, 'wb') as file:
25 pickle.dump(students, file)
26
27
28 def record_student() -> None:
29 global students
30 roll, name, marks = input(
31 'Enter roll, name and marks seperated by comma\n> ').split(',')
32 students[roll] = [name, marks]
33 write_to_file()
34 print('Sucessfully recorded')
35
36
37 def update_marks() -> None:
38 roll, marks = input(
39 'Enter roll, and new marks seperated by comma\n ').split(',')
40 if roll in students.keys():
41 students[roll][1] = marks
42 write_to_file()
43 print('Sucessfully updated')
44 else:
45 print('Student does not exist in records')
46
47
48 def display() -> None:
49 table = []
50 for key, value in students.items():
51 table.append([key, value[0], value[1]])
52 print(tabulate(table, tablefmt='fancy_grid',
53 headers=['Roll', 'Name', 'Marks']))
54
55
56 def main():
57 ''' Driving the app.
58 '''
59 if not os.path.isfile(filename):
60 write_to_file()
61 else:
62 load_file()
63
64 menus = {}
65
66 menus['1'] = {'desc': 'Record new student',
67 'func': record_student}
68 menus['2'] = {'desc': 'Update marks of existing student',
69 'func': update_marks}
70 menus['3'] = {'desc': 'Display all records',
71 'func': display}
72
73 drive_menu('Marks Manager', menus)
74
75
76 if __name__ == "__main__":
77 main()
78
Output
1
2 MENU for Marks Manager
3
4 ╒══════════╤══════════════════════════════════╕
5 │ Choice │ Description │
6 ╞══════════╪══════════════════════════════════╡
7 │ 1 │ Record new student │
8 ├──────────┼──────────────────────────────────┤
9 │ 2 │ Update marks of existing student │
10 ├──────────┼──────────────────────────────────┤
11 │ 3 │ Display all records │
12 ╘══════════╧══════════════════════════════════╛
13 Enter your choice or X to quit
14
15 >>>
1 >>> 2
2 Enter roll, and new marks seperated by comma
3 13,90
4 Sucessfully updated
( the screen gets cleared at this point and menu is re-displayed, and now the user tries an invalid
update )
1 >>> 2
2 Enter roll, and new marks seperated by comma
3 100,90
4 Student does not exist in records
1
2
3 >>> 3
4 ╒════════╤═══════════╤═════════╕
5 │ Roll │ Name │ Marks │
6 ╞════════╪═══════════╪═════════╡
7 │ 1 │ Hitesham │ 90 │
8 ├────────┼───────────┼─────────┤
9 │ 34 │ Ramesha │ 89 │
10 ├────────┼───────────┼─────────┤
11 │ 13 │ Jay Bhatt │ 90 │
12 ╘════════╧═══════════╧═════════╛
13
14 Press [ENTER] to continue or CTRL+C to quit
15
x. Remove all the lines that contain the character `a' in a file
and write it to another file.
Code
1 ''' Remove all the lines that contain the character `a' in a file and write
it
2 to another file.
3 '''
4
5
6 def move(old: str, new: str):
7 ''' The function that does the job
8
9 Args:
10 old (str): file path of original file
11 new (str): file path of new file
12 '''
13
14 with open(old, 'r') as old_file:
15 lines = old_file.readlines()
16 a_lines = [line for line in lines if 'a' in line]
17 not_a_lines = [line for line in lines if 'a' not in line]
18
19 with open(old, 'w') as old_file:
20 old_file.writelines(not_a_lines)
21
22 with open(new, 'w') as new_file:
23 new_file.writelines(a_lines)
24
25
26 def main():
27 old = input('Enter the old file path: ')
28 new = input('Enter the new file path: ')
29 move(old, new)
30 print('Done! ')
31
32
33 if __name__ == "__main__":
34 main()
35
Output
Output
1 ''' Take a sample of ten phishing e-mails (or any text file) and find most
2 commonly occurring word(s)
3
4 the file `data/phishing.txt` contains the text extracted from 10 phishing
emails
5 the samples are taken from https://security.berkeley.edu/
6 '''
7
8 from collections import Counter
9 from tabulate import tabulate
10 import os
11
12 # in data folder of current directory
13 filename = os.path.join('data', 'phishing.txt')
14
15 with open(filename, 'r') as file:
16 content = file.read()
17
18 # take all the words
19 words = Counter(content.split())
20
21 # count the most common words
22 most_common = words.most_common(20)
23
24 print('Top 20 Commonly used words\n')
25 print(tabulate(most_common, tablefmt='fancy_grid'))
26
Output
Note : the file data/phishing.txt contains the text extracted from 10 phishing emails
the samples are taken from https://security.berkeley.edu/
1 ''' Program to create CSV file and store empno,name,salary and search any
empno and
2 display name,salary and if not found appropriate message.
3 '''
4
5 import os
6 import csv
7 from utils import drive_menu
8
9 filename = os.path.join('data', 'employee.csv')
10
11
12 def init():
13 ''' Create files if not present '''
14 if not os.path.isfile(filename):
15 with open(filename, 'w') as file:
16 file.write('empno,name,salary')
17
18
19 def store() -> None:
20 ''' Store the record of employee '''
21 record = input('Enter empno, name and salary seperated by comma\n>>> ')
22 with open(filename, 'a') as file:
23 file.write(f'\n{record}')
24 print('Employee recorded')
25
26
27 def retrieve() -> None:
28 ''' Retrieve the record of existing employee '''
29 empno = input('Enter empno to search\n>>> ')
30 with open(filename, 'r') as file:
31 employees = csv.DictReader(file)
32 for row in employees:
33 if row['empno'] == empno:
34 print(f"Name: {row['name']}\nSalary: {row['salary']}")
35 return
36 print('Employee not found in records')
37
38
39 def main():
40 init()
41 menus = {}
42 menus['1'] = {'desc': 'Store new Employee', 'func': store}
43 menus['2'] = {'desc': 'Search Employee', 'func': retrieve}
44 drive_menu('Employee Management', menus)
45
46
47 if __name__ == "__main__":
48 main()
49
Output
1
2 MENU for Employee Management
3
4 ╒══════════╤════════════════════╕
5 │ Choice │ Description │
6 ╞══════════╪════════════════════╡
7 │ 1 │ Store new Employee │
8 ├──────────┼────────────────────┤
9 │ 2 │ Search Employee │
10 ╘══════════╧════════════════════╛
11 Enter your choice or X to quit
12
13 >>>
14
1 >>> 2
2 Enter empno to search
3 >>> 13
4 Employee not found in records
5
6 Press [ENTER] to continue or CTRL+C to quit
1 >>> 1
2 Enter empno, name and salary seperated by comma
3 >>> 12, Akshay Kumar, 10000
4 Employee recorded
5
6 Press [ENTER] to continue or CTRL+C to quit
1 >>> 2
2 Enter empno to search
3 >>> 12
4 Name: Akshay Kumar
5 Salary: 10000
6
7 Press [ENTER] to continue or CTRL+C to quit
xiv. Program to implement Stack in Python using List.
Code
Output
( during the execution of the program the screen is cleared and the menu is displayed several times, for
an aesthetic experience. To keep stuff clean, the same menu is not being repeated here)
1 >>> 1
2 Enter data to push: hoch
3
4 >>> 1
5 Enter data to push: poch
6
7 >>> 1
8 Enter data to push: ghosh
9
10 >>> 3
11 ghosh
12
13 >>> 4
14 top
15 ╒═══════╕
16 │ ghosh │
17 ├───────┤
18 │ poch │
19 ├───────┤
20 │ hoch │
21 ╘═══════╛
22
23 >>> 2
24 ghosh
25
26 >>> 4
27 top
28 ╒══════╕
29 │ poch │
30 ├──────┤
31 │ hoch │
32 ╘══════╛
33
xv. Program to implement Queue in Python using List.
Code
Output
1
2 MENU for Queue Operations
3
4 ╒══════════╤═══════════════╕
5 │ Choice │ Description │
6 ╞══════════╪═══════════════╡
7 │ 1 │ Enqueue │
8 ├──────────┼───────────────┤
9 │ 2 │ Dequeue │
10 ├──────────┼───────────────┤
11 │ 3 │ Peek (front) │
12 ├──────────┼───────────────┤
13 │ 4 │ Rear │
14 ├──────────┼───────────────┤
15 │ 5 │ Display │
16 ╘══════════╧═══════════════╛
17 Enter your choice or X to quit
18
19 >>>
20
( during the execution of the program the screen is cleared and the menu is displayed several times, for
an aesthetic experience. To keep stuff clean, the same menu is not being repeated here)
1 >>> 1
2 Enter data to enqueue: utopia
3
4 >>> 1
5 Enter data to enqueue: distopia
6
7 >>> 1
8 Enter data to enqueue: ultadanga
9
10 >>> 5
11 front
12 ╒════════╤══════════╤═══════════╕
13 │ utopia │ distopia │ ultadanga │
14 ╘════════╧══════════╧═══════════╛
15
16 >>> 3
17 utopia
18
19 >>> 4
20 ultadanga
21
22 >>> 2
23 utopia
24
25 >>> 5
26 front
27 ╒══════════╤═══════════╕
28 │ distopia │ ultadanga │
29 ╘══════════╧═══════════╛
30
xvi. Program to create 21 Stick Game so that computer
always wins
Code
Output
( during the execution of the program the screen is cleared and the menu is displayed several times, for
an aesthetic experience. To keep stuff clean, the same menu is not being repeated here)
1 ''' Program to connect with database and store record of employee and
display records.
2 '''
3
4 from sqlTor import SqlTor
5 import mysql.connector
6 from mysql.connector import errorcode
7 from tabulate import tabulate
8 from utils import clear_screen
9
10
11 def input_employee_details():
12 while True:
13 try:
14 name = input('name: ')
15 assert 5 < len(name) < 20
16 department = input('department: ')
17 assert len(department) < 20
18 salary = int(input('salary: '))
19 assert salary >= 0
20 except Exception as err:
21 print(f'Please enter valid details. {err}')
22 else:
23 break
24
25 return name, department, salary
26
27
28 def input_emp_id():
29 while True:
30 try:
31 emp_id = int(input('Enter employee id: '))
32 except ValueError:
33 print('Invalid Employee id. It must be integer.')
34 else:
35 break
36 return emp_id
37
38
39 def create_table(cursor):
40 ''' Takes the cursor object and creates table '''
41
42 table_creation = ("CREATE TABLE employees(\
43 emp_id integer NOT NULL PRIMARY KEY,\
44 name char(20) NOT NULL,\
45 department char(20) NOT NULL,\
46 salary integer NOT NULL);")
47
48 try:
49 cursor.execute(table_creation)
50 except mysql.connector.Error as err:
51 if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
52 print('table already exists')
53 else:
54 print(err)
55 else:
56 print('Created table `employees` successfully')
57
58
59 def display_all(cursor):
60 ''' Display all employees '''
61
62 query = "SELECT * FROM employees"
63
64 try:
65 cursor.execute(query)
66 except Exception as err:
67 print(err)
68 else:
69 employees = cursor.fetchall()
70 if employees:
71 print(f'''\n\nHere is the list of all employees
72 \n{tabulate(employees,tablefmt='fancy_grid',headers=
['emp_id','name','department','salary'])}\n''')
73 else:
74 print('No employees recorded yet')
75
76
77 def record_new(cursor):
78 ''' Record a new employee '''
79
80 print('Enter the details to add new employee.\n')
81
82 emp_id = input_emp_id()
83
84 name, department, salary = input_employee_details()
85
86 insert_employee = f"INSERT INTO employees \
87 VALUES({emp_id},\
88 '{name}','{department}',{salary})"
89
90 try:
91 cursor.execute(insert_employee)
92 except Exception as err:
93 if err.errno == errorcode.ER_DUP_ENTRY:
94 print('Duplicate entry. emp_id must be unique.')
95 else:
96 print('New employee added successfully 😃')
97
98
99 if __name__ == "__main__":
100
101 with SqlTor() as my_con:
102 cursor = my_con.cursor()
103 create_table(cursor)
104 while True:
105 clear_screen()
106 display_all(cursor)
107 print('RECORD NEW EMPLOYEES')
108 record_new(cursor)
109 my_con.commit()
110
Output
1 ''' Program to connect with database and search employee number in table
employee
2 and display record, if empno not found display appropriate message. '''
3
4 from utils import clear_screen
5 from sqlTor import SqlTor
6 from q17_dbRecord import input_emp_id
7
8
9 def get_employee(cursor) -> tuple or None:
10 ''' Input employee id and fetch details of employee.
11 Returns a tuple or None if not found '''
12
13 emp_id = input_emp_id()
14
15 query = f'SELECT * FROM employees WHERE emp_id={emp_id}'
16
17 try:
18 cursor.execute(query)
19 except Exception as err:
20 print(err)
21 else:
22 employees = cursor.fetchall()
23 if employees:
24 return employees[0]
25
26
27 if __name__ == "__main__":
28
29 with SqlTor() as my_con:
30 cursor = my_con.cursor()
31
32 while True:
33 clear_screen()
34 print('SEARCH EMPLOYEE')
35 emp = get_employee(cursor)
36 if emp:
37 print('Record found 🥰')
38 print(f'''
39 name: {emp[1]},
40 department: {emp[2]},
41 salary: {emp[3]}''')
42 else:
43 print('Employee Not found 😢')
44
Output
1 SEARCH EMPLOYEE
2 Enter employee id: 12
3 Record found 🥰
4
5 name: Hans Chen,
6 department: Sales,
7 salary: 10000
8
9 Press [ENTER] to continue or CTRL+C to quit
10
11 # screen gets cleared
12
13 SEARCH EMPLOYEE
14 Enter employee id: 100
15 Employee Not found 😢
16
17 Press [ENTER] to continue or CTRL+C to quit
18 ^C
19 Interrupt recieved. Quitting.
20
xix. Program to connect with database and update the
employee record of entered empno.
Code
1 ''' Program to connect with database and update the employee record of
entered empno. '''
2
3 from utils import clear_screen
4 from sqlTor import SqlTor
5
6 from q18_dbSearch import get_employee
7 from q17_dbRecord import input_employee_details
8
9
10 def update_employee(cursor):
11 ''' Update an employee '''
12
13 emp = get_employee(cursor)
14
15 if not emp:
16 print('Employee does not exist.')
17 return
18
19 print('Enter new details of employee.')
20 name, department, salary = input_employee_details()
21
22 employee_updation = f"UPDATE employees \
23 SET name='{name}',\
24 department='{department}',\
25 salary={salary} \
26 WHERE emp_id={emp[0]};"
27
28 try:
29 cursor.execute(employee_updation)
30 except Exception as err:
31 print(err)
32 else:
33 print('Update Successful!')
34
35
36 if __name__ == "__main__":
37 with SqlTor() as my_con:
38 cursor = my_con.cursor()
39 while True:
40 clear_screen()
41 print('UPDATE EMPLOYEE')
42 update_employee(cursor)
43 my_con.commit()
44
Output
1
2 UPDATE EMPLOYEE
3 Enter employee id: 12
4 Enter new details of employee.
5 name: Aahnik Daw
6 department: Machine Learning
7 salary: 10
8 Update Successful!
9
10 Press [ENTER] to continue or CTRL+C to quit
11
12 # screen gets cleared
13
14 UPDATE EMPLOYEE
15 Enter employee id: 100
16 Employee does not exist.
17
18 Press [ENTER] to continue or CTRL+C to quit
19 ^C
20 Interrupt recieved. Quitting.
21
xx. Program to connect with database and delete the record
of entered employee number.
Code
1 ''' Program to connect with database and delete the record of entered
employee number. '''
2
3 from sqlTor import SqlTor
4 from utils import clear_screen
5 from q18_dbSearch import get_employee
6
7
8 def delete_employee(cursor):
9 ''' Delete an employee '''
10
11 emp = get_employee(cursor)
12
13 if not emp:
14 print('Employee does not exist.')
15 return
16
17 employee_deletion = f'DELETE FROM employees WHERE emp_id={emp[0]}'
18
19 try:
20 cursor.execute(employee_deletion)
21 except Exception as err:
22 print(err)
23 else:
24 print('Successfully deleted.')
25
26
27 if __name__ == "__main__":
28
29 with SqlTor() as my_con:
30 cursor = my_con.cursor()
31 while True:
32 clear_screen()
33 print('DELETE EMPLOYEE')
34 delete_employee(cursor)
35 my_con.commit()
36
Output
1 DELETE EMPLOYEE
2 Enter employee id: 12
3 Successfully deleted.
4
5 Press [ENTER] to continue or CTRL+C to quit
6
7 # screen gets cleared
8
9 DELETE EMPLOYEE
10 Enter employee id: 100
11 Employee does not exist.
12
13 Press [ENTER] to continue or CTRL+C to quit
14 ^C
15 Interrupt recieved. Quitting.
Helper scripts
utils.py
1
2 ''' General purpose utility module, to reduce number of lines of code in
solution
3 Enables my code to be DRY (Dont Repeat Yourself)
4 '''
5
6 import os
7 from tabulate import tabulate
8 import sys
9 import signal
10
11
12 def handle_interrupt(*args):
13 print('\nInterrupt recieved. Quitting.')
14 sys.exit(0)
15
16
17 def clear_screen():
18
19 # handle user interrupt
20 signal.signal(signal.SIGTERM, handle_interrupt)
21 signal.signal(signal.SIGINT, handle_interrupt)
22
23 # wait for user to see current screen
24 input('\nPress [ENTER] to continue or CTRL+C to quit\n')
25
26 if os.name == 'posix':
27 # for Linux and Mac
28 os.system('clear')
29 else:
30 # for Windows
31 os.system('cls')
32
33
34 def drive_menu(heading: str, menus: dict) -> None:
35 ''' Function to allow a menu driven program
36
37 Args:
38 heading (str): heading to be displayed on top of menu
39 menus (dict): dictionary of menus containing
40 key (menu id) value (another dictionary having `desc` and `func` )
41 '''
42
43 table = [[ch, menu['desc']] for ch, menu in menus.items()]
44 menu_chart = f'''
45 MENU for {heading}
46 \n{tabulate(table,tablefmt='fancy_grid',headers=
['Choice','Description'])}
47 Enter your choice or X to quit
48 \n>>> '''
49 choice = ''
50 while choice != 'X':
51 clear_screen()
52 choice = input(menu_chart)
53 if choice in menus.keys():
54 val = menus[choice]['func']()
55 if val:
56 print(val)
57 elif choice == 'X':
58 print('Bye 🤗')
59 else:
60 print('INVALID CHOICE')
61
sqlTor.py
1 '''
2 An utility module that helps to connect to the my sql database
3 '''
4
5 import mysql.connector
6 import yaml
7
8 # read the config file, and load it into a dict
9 with open('config.yaml') as f:
10 config = yaml.full_load(f)
11
12
13 class SqlTor():
14 ''' Context manager to enable easy connection to database
15 '''
16
17 def __init__(self) -> None:
18 self.conn = mysql.connector.connect(**config)
19
20 def __enter__(self):
21 ''' Entry point '''
22 if self.conn.is_connected():
23 return self.conn
24 else:
25 raise Exception('Not connected to MySQL')
26
27 def __exit__(self, exception_type, exception_value, traceback):
28 ''' Exit '''
29 self.conn.close()
30
SQL
the full emp table
1 SELECT
2 *
3 FROM
4 emp
5 WHERE
6 department = 'Sales';
1 SELECT
2 *
3 FROM
4 emp
5 WHERE
6 name LIKE 'K%';
7
1 SELECT
2 name
3 FROM
4 emp
5 WHERE
6 sex = 'F' AND department = 'Finance';
iv. To display name and sex of all the employees whose age
is in the range of 40 to 50 in ascending order of their name.
1 SELECT
2 name, sex
3 FROM
4 emp
5 WHERE
6 age BETWEEN 40 AND 50
7 ORDER BY name;
1 SELECT
2 COUNT(*) 'female emp older than 20 in accounts'
3 FROM
4 emp></div>
5 WHERE
6 age > 20 AND department = 'Accounts';
the full games table
1 SELECT
2 gamename, gcode
3 FROM
4 games;
1 SELECT
2 *
3 FROM
4 games
5 WHERE
6 prizemoney > 7000;
7
1 SELECT
2 *
3 FROM
4 games
5 ORDER BY scheduledate;
ix. To display sum of PrizeMoney for each of the Numberof
participation groupings ( as shown in column number 2 or 4).
1 SELECT
2 number, SUM(prizemoney)
3 FROM
4 games
5 GROUP BY number;
1 SELECT
2 SUM(prizemoney)
3 FROM
4 games;
5
the full loans table
xi. Display the sum of all Loan Amount whose Interest rate is
greater than 10.
1 SELECT
2 SUM(loan_amount)
3 FROM
4 loans
5 WHERE
6 int_rate > 10;
1 SELECT
2 MAX(int_rate)
3 FROM
4 loans;
xiii. Display the count of all loan holders whose name ends
with ‘SHARMA’.
1 SELECT
2 COUNT(cust_name)
3 FROM
4 loans
5 WHERE
6 cust_name LIKE '%SHARMA';
1 SELECT
2 COUNT(cust_name)
3 FROM
4 loans
5 WHERE
6 int_rate IS NULL;
xv. Display the Interest-wise details of Loan Account
Holders.
1 SELECT
2 *
3 FROM
4 loans
5 ORDER BY interest;
1 SELECT
2 *
3 FROM
4 loans
5 WHERE
6 installments >= 10
7 ORDER BY interest;
8
1
2 ALTER TABLE loans
3 ADD (Adress TEXT);
4
1 UPDATE loans
2 SET
3 int_rate = int_rate - 1
4 WHERE
5 int_rate IS NOT NULL;