-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPPL.py
More file actions
427 lines (361 loc) · 16.2 KB
/
Copy pathPPL.py
File metadata and controls
427 lines (361 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
"""Python Programming Lab (PPL) - an interactive menu of ten classic programming exercises.
Each exercise is presented the way a lab record is written up: Aim, Algorithm,
Program, Output and Result.
"""
from __future__ import annotations
import inspect
import os
import platform
import tempfile
import textwrap
from collections import Counter
from dataclasses import dataclass
from typing import Callable
import numpy as np
# --------------------------------------------------------------------------- #
# Shared input helpers (kept small and reused so every exercise validates the
# same way instead of repeating its own retry loop).
# --------------------------------------------------------------------------- #
def read_int(prompt: str) -> int:
while True:
try:
return int(input(prompt))
except ValueError:
print('\n Invalid input (e.g. 1 or 2 or 3)\n')
def read_int_list(prompt: str) -> list[int]:
while True:
try:
return [int(value) for value in input(prompt).split()]
except ValueError:
print('\n Invalid input (e.g. 1 2 3)\n')
def read_text(prompt: str) -> str:
while True:
text = input(prompt)
if text.strip():
return text
print('\n Invalid input (text cannot be empty)\n')
# --------------------------------------------------------------------------- #
# 1. Count the number of even/odd numbers in a given list.
# --------------------------------------------------------------------------- #
def count_odd_even() -> None:
numbers = read_int_list('\nInput:\n\n Enter the list (separated by spaces): ')
odd = sum(1 for n in numbers if n % 2 != 0)
even = len(numbers) - odd
print(f'\nOutput:\n\n Number of odd numbers: {odd}\n Number of even numbers: {even}')
# --------------------------------------------------------------------------- #
# 2. Count the number of digits and letters in a given text.
# --------------------------------------------------------------------------- #
def count_digits_letters() -> None:
text = read_text('\nInput:\n\n Enter the text: ')
digits = sum(1 for ch in text if ch.isdigit())
letters = sum(1 for ch in text if ch.isalpha())
print(f'\nOutput:\n\n Number of digits: {digits}\n Number of letters: {letters}')
# --------------------------------------------------------------------------- #
# 3. Validate a password.
# --------------------------------------------------------------------------- #
def check_password() -> None:
rules: list[tuple[Callable[[str], bool], str]] = [
(lambda s: any(ch.islower() for ch in s), 'At least 1 letter between [a-z]'),
(lambda s: any(ch.isupper() for ch in s), 'At least 1 letter between [A-Z]'),
(lambda s: any(ch.isdigit() for ch in s), 'At least 1 number between [0-9]'),
(lambda s: any(ch in '$#@' for ch in s), 'At least 1 character from [$#@]'),
(lambda s: len(s) >= 6, 'Minimum length 6 characters'),
(lambda s: len(s) <= 16, 'Maximum length 16 characters'),
]
while True:
password = input('\nInput:\n\n Enter the password: ')
failed_rule = next((message for is_met, message in rules if not is_met(password)), None)
if failed_rule is None:
print('\nOutput:\n\n Valid Password')
return
print(f'\nOutput:\n\n Invalid Password ({failed_rule})')
# --------------------------------------------------------------------------- #
# 4. Sum and average of n integers, 0 to finish.
# --------------------------------------------------------------------------- #
def sum_and_average() -> None:
total, count = 0, 0
number = read_int('\nInput:\n\n Enter the number (0 to finish): ')
while number != 0:
total += number
count += 1
number = read_int(' Enter the number (0 to finish): ')
if count == 0:
print('\nOutput:\n\n Sum of the above numbers: 0\n Average of the above numbers: 0')
else:
print(f'\nOutput:\n\n Sum of the above numbers: {total}\n Average of the above numbers: {total / count}')
# --------------------------------------------------------------------------- #
# 5. Count upper case and lower case letters in a string.
# --------------------------------------------------------------------------- #
def count_case() -> None:
text = read_text('\nInput:\n\n Enter the text: ')
upper = sum(1 for ch in text if ch.isupper())
lower = sum(1 for ch in text if ch.islower())
print(f'\nOutput:\n\n Number of upper case letters: {upper}\n Number of lower case letters: {lower}')
# --------------------------------------------------------------------------- #
# 6. Fibonacci series using a while loop.
# --------------------------------------------------------------------------- #
def fibonacci_series() -> None:
limit = read_int('\nInput:\n\n Enter the number: ')
series = []
a, b = 0, 1
while b <= limit:
series.append(b)
a, b = b, a + b
print(f"\nOutput:\n\n Fibonacci series: {', '.join(map(str, series))}")
# --------------------------------------------------------------------------- #
# 7. Factorial using recursion.
# --------------------------------------------------------------------------- #
def factorial() -> None:
def factorial_of(n: int) -> int:
return 1 if n <= 1 else n * factorial_of(n - 1)
while True:
number = read_int('\nInput:\n\n Enter the number: ')
if number < 0:
print('\n Invalid input (must be 0 or a positive number)\n')
continue
break
print(f'\nOutput:\n\n Factorial of {number} is: {factorial_of(number)}')
# --------------------------------------------------------------------------- #
# 8. Binary search.
# --------------------------------------------------------------------------- #
def binary_search() -> None:
while True:
numbers = read_int_list('\nInput:\n\n Enter the list, sorted ascending (separated by spaces): ')
if numbers == sorted(numbers):
break
print('\n Invalid input (the list must be sorted in ascending order)\n')
target = read_int(' Search: ')
low, high, index = 0, len(numbers) - 1, -1
while low <= high:
mid = (low + high) // 2
if numbers[mid] == target:
index = mid
break
if target < numbers[mid]:
high = mid - 1
else:
low = mid + 1
if index != -1:
print(f'\nOutput:\n\n Number {target} is present at index {index} in the list')
else:
print(f'\nOutput:\n\n Number {target} is not present in the list')
# --------------------------------------------------------------------------- #
# 9. Most frequent word in a text read from a file.
# --------------------------------------------------------------------------- #
def most_frequent_word() -> None:
text = read_text('\nInput:\n\n Write (to file): ')
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as file:
file.write(text)
path = file.name
try:
with open(path, encoding='utf-8') as file:
content = file.read()
finally:
os.remove(path)
for punctuation in ',.!?;:':
content = content.replace(punctuation, ' ')
words = content.split()
if not words:
print('\nOutput:\n\n No words found in the given text')
return
word, freq = Counter(words).most_common(1)[0]
print(f"\nOutput:\n\n Frequent word: '{word}' at {freq} times")
# --------------------------------------------------------------------------- #
# 10. Matrix addition, subtraction and (element-wise) multiplication.
# --------------------------------------------------------------------------- #
def matrix_operations() -> None:
def read_matrix(rows: int, columns: int, label: str) -> np.ndarray:
matrix = []
for row_number in range(1, rows + 1):
while True:
row = read_int_list(f' Enter row {row_number} of the {label} matrix (separated by spaces): ')
if len(row) == columns:
matrix.append(row)
break
print(f'\n Invalid input (expected {columns} numbers)\n')
return np.array(matrix)
print('\nInput:\n')
rows = read_int(' Enter the number of rows: ')
columns = read_int(' Enter the number of columns: ')
first = read_matrix(rows, columns, 'first')
second = read_matrix(rows, columns, 'second')
operations = {
'1': ('addition', first + second),
'2': ('subtraction', first - second),
'3': ('multiplication (element-wise)', first * second),
}
while True:
print('\n[1 - addition | 2 - subtraction | 3 - multiplication | e - exit]\n')
choice = input('Select operation: ').strip().lower()
if choice == 'e':
break
if choice in operations:
name, result = operations[choice]
print(f'\nOutput ({name}):\n')
for row in result:
print(' ' + ' '.join(map(str, row)))
else:
print('\nInvalid Input')
# --------------------------------------------------------------------------- #
# Exercise registry and menu.
# --------------------------------------------------------------------------- #
@dataclass(frozen=True)
class Exercise:
aim: str
algorithm: list[str]
run: Callable[[], None]
EXERCISES: dict[int, Exercise] = {
1: Exercise(
aim='Write a Python program to count the number of even/odd numbers in a given list.',
algorithm=[
'Read a list of integers from the user.',
'Initialise odd and even counters to 0.',
'For each number, increment even if it is divisible by 2, else increment odd.',
'Display the odd and even counts.',
],
run=count_odd_even,
),
2: Exercise(
aim='Write a Python program to calculate the number of digits and letters in a given text.',
algorithm=[
'Read a text string from the user.',
'Initialise digit and letter counters to 0.',
'For each character, increment digits if it is a digit, or letters if it is alphabetic.',
'Display the digit and letter counts.',
],
run=count_digits_letters,
),
3: Exercise(
aim=(
'Write a Python program to check the validity of a password validation:\n\n'
' a. At least 1 letter between [a-z] and 1 letter between [A-Z].\n\n'
' b. At least 1 number between [0-9].\n\n'
' c. At least 1 character from [$#@].\n\n'
' d. Minimum length 6 characters.\n\n'
' e. Maximum length 16 characters.'
),
algorithm=[
'Read a password string from the user.',
'Check it contains a lower case letter, an upper case letter, a digit and one of [$#@].',
'Check its length is between 6 and 16 characters.',
'If every check passes, display "Valid Password".',
'Otherwise, display which rule failed and ask for the password again.',
],
run=check_password,
),
4: Exercise(
aim=(
'Write a Python program to calculate the sum and average of n integer numbers '
'(input from the user). Input 0 to finish.'
),
algorithm=[
'Initialise sum and count to 0.',
'Repeatedly read an integer until the user enters 0.',
'Add each non-zero number to the sum and increment the count.',
'If count is 0, the sum and average are both 0; otherwise average = sum / count.',
'Display the sum and the average.',
],
run=sum_and_average,
),
5: Exercise(
aim=(
'Write a Python function that accepts a string and calculate the number of upper '
'case letters and lower case letters.'
),
algorithm=[
'Read a text string from the user.',
'Initialise upper and lower counters to 0.',
'For each character, increment upper if it is upper case, or lower if it is lower case.',
'Display the upper case and lower case counts.',
],
run=count_case,
),
6: Exercise(
aim='Write a Python program to calculate the Fibonacci series using while loop.',
algorithm=[
'Read a limiting number n from the user.',
'Initialise the series with a = 0 and b = 1.',
'While b is less than or equal to n, append b to the series and update a, b = b, a + b.',
'Display the series.',
],
run=fibonacci_series,
),
7: Exercise(
aim='Write a python program to find the factorial of a given number using recursion function.',
algorithm=[
'Read a non-negative integer n from the user.',
'Define a recursive function that returns 1 when n is 0 or 1.',
'Otherwise, the function returns n multiplied by the factorial of n - 1.',
'Display the factorial of n.',
],
run=factorial,
),
8: Exercise(
aim='Write a python program to implement the binary search algorithm.',
algorithm=[
'Read a list sorted in ascending order and a target value from the user.',
'Set low to 0 and high to the last index of the list.',
'While low <= high, compute mid = (low + high) // 2.',
'If the middle element equals the target, the search succeeds at index mid.',
'If the target is smaller, search the left half (high = mid - 1); otherwise search the right half (low = mid + 1).',
'If the loop ends with no match, the value is not present in the list.',
],
run=binary_search,
),
9: Exercise(
aim='Write a python program to find the most frequent words in a text read from a file.',
algorithm=[
'Read a line of text from the user and write it to a temporary file.',
'Read the text back from that file.',
'Replace punctuation with spaces and split the text into words.',
'Count how many times each word occurs.',
'Display the word with the highest count.',
],
run=most_frequent_word,
),
10: Exercise(
aim='Write a python program to perform the matrix addition, subtraction and multiplication.',
algorithm=[
'Read the number of rows and columns, then read both matrices of that size.',
'Repeatedly ask the user to choose addition, subtraction, element-wise multiplication, or exit.',
'Compute and display the result of the chosen operation.',
],
run=matrix_operations,
),
}
def render_program(func: Callable[[], None]) -> str:
return textwrap.indent(inspect.getsource(func), ' ')
def list_of_programs() -> str:
return '\n\n'.join(f'{number}. {exercise.aim}' for number, exercise in sorted(EXERCISES.items()))
def run_exercise(number: int) -> None:
exercise = EXERCISES[number]
print(f'\nAim:\n\n {exercise.aim}')
print('\nAlgorithm:\n')
for step, description in enumerate(exercise.algorithm, start=1):
print(f' {step}. {description}')
print(f'\nProgram:\n\n{render_program(exercise.run)}')
exercise.run()
print('\nResult:\n\n Thus the above code was executed successfully.')
def clear_screen() -> None:
os.system('cls' if platform.system() == 'Windows' else 'clear')
if platform.system() == 'Windows':
os.system('title Python Programming Lab')
def main() -> None:
clear_screen()
print('\nWelcome to Python Programming Lab!')
while True:
print('\n[lop - list of programs | 1 to 10 - number of programs | cls - clear screen | e - exit]')
command = input('\nEnter your command: ').strip().lower()
if command == 'lop':
print(f'\n{list_of_programs()}')
elif command == 'e':
break
elif command == 'cls':
clear_screen()
print('\nWelcome to Python Programming Lab!')
elif command.isdigit() and int(command) in EXERCISES:
run_exercise(int(command))
else:
print('\nInvalid command (expected: lop, 1-10, cls, or e)')
if __name__ == '__main__':
main()