python-lab-toolkit 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. pylab/__init__.py +43 -0
  2. pylab/cli.py +282 -0
  3. pylab/data/Data.csv +11 -0
  4. pylab/data/alphabet_stock_data.csv +143 -0
  5. pylab/data/breast-cancer.csv +351 -0
  6. pylab/data/dirtydata.csv +33 -0
  7. pylab/data/groceries.csv +359 -0
  8. pylab/data/iris.csv +151 -0
  9. pylab/data/rainfall.csv +151 -0
  10. pylab/data/students.csv +7 -0
  11. pylab/data/winequality-red.csv +1601 -0
  12. pylab/data/winequality-white.csv +2401 -0
  13. pylab/datasets.py +277 -0
  14. pylab/environment.py +136 -0
  15. pylab/errors.py +53 -0
  16. pylab/generator.py +216 -0
  17. pylab/registry.py +562 -0
  18. pylab/templates/q1/variable_validator.py +43 -0
  19. pylab/templates/q10/password_strength.py +42 -0
  20. pylab/templates/q11/recursion_math.py +28 -0
  21. pylab/templates/q12/main_analyzer.py +46 -0
  22. pylab/templates/q12/text_analyzer.py +16 -0
  23. pylab/templates/q12/text_preprocessor.py +15 -0
  24. pylab/templates/q13/student.py +26 -0
  25. pylab/templates/q14/circle.py +26 -0
  26. pylab/templates/q15/employee_salary.py +46 -0
  27. pylab/templates/q16/smart_calculator.py +51 -0
  28. pylab/templates/q17/complex_number.py +43 -0
  29. pylab/templates/q18/vehicle_inheritance.py +43 -0
  30. pylab/templates/q19/file_word_counter.py +48 -0
  31. pylab/templates/q19/sample.txt +6 -0
  32. pylab/templates/q2/single_number.py +26 -0
  33. pylab/templates/q20/age_validator.py +27 -0
  34. pylab/templates/q21/transaction_manager.py +45 -0
  35. pylab/templates/q22/date_formatter.py +30 -0
  36. pylab/templates/q23/rainfall_analyzer.py +73 -0
  37. pylab/templates/q24/student_marks.py +58 -0
  38. pylab/templates/q25/library_manager.py +182 -0
  39. pylab/templates/q26/mysql_employee_manager.py +239 -0
  40. pylab/templates/q27/crud_client.py +98 -0
  41. pylab/templates/q27/mock_server.py +85 -0
  42. pylab/templates/q28/index.html +33 -0
  43. pylab/templates/q28/login_handler.py +31 -0
  44. pylab/templates/q28/server.py +44 -0
  45. pylab/templates/q29/index.html +50 -0
  46. pylab/templates/q29/register_handler.py +42 -0
  47. pylab/templates/q29/server.py +42 -0
  48. pylab/templates/q3/string_operations.py +32 -0
  49. pylab/templates/q30/crud_handler.py +60 -0
  50. pylab/templates/q30/database.py +66 -0
  51. pylab/templates/q30/index.html +59 -0
  52. pylab/templates/q30/server.py +51 -0
  53. pylab/templates/q31/numpy_matrix.py +40 -0
  54. pylab/templates/q32/numpy_slicing.py +43 -0
  55. pylab/templates/q33/pandas_students.py +41 -0
  56. pylab/templates/q34/pandas_salary.py +37 -0
  57. pylab/templates/q35/sales_barchart.py +58 -0
  58. pylab/templates/q36/weather_plot.py +50 -0
  59. pylab/templates/q37/age_categorization.py +38 -0
  60. pylab/templates/q38/concat_rows.py +38 -0
  61. pylab/templates/q39/concat_cols.py +38 -0
  62. pylab/templates/q4/menu_string_processor.py +68 -0
  63. pylab/templates/q40/concat_merge.py +44 -0
  64. pylab/templates/q41/pandas_joins.py +46 -0
  65. pylab/templates/q42/groupby_school.py +32 -0
  66. pylab/templates/q43/groupby_multi.py +29 -0
  67. pylab/templates/q44/alphabet_stock_viz.py +95 -0
  68. pylab/templates/q45/multi_plot.py +65 -0
  69. pylab/templates/q46/dataframe_barchart.py +60 -0
  70. pylab/templates/q47/preprocess_data.py +54 -0
  71. pylab/templates/q48/clean_dirtydata.py +62 -0
  72. pylab/templates/q49/wine_regression.py +169 -0
  73. pylab/templates/q5/phonebook.py +105 -0
  74. pylab/templates/q50/breast_cancer_classifier.py +147 -0
  75. pylab/templates/q51/iris_clustering.py +95 -0
  76. pylab/templates/q52/apriori_groceries.py +88 -0
  77. pylab/templates/q6/calculator.py +67 -0
  78. pylab/templates/q7/session_attendees.py +37 -0
  79. pylab/templates/q8/number_properties.py +68 -0
  80. pylab/templates/q9/greet_people.py +26 -0
  81. python_lab_toolkit-1.0.0.dist-info/LICENSE +21 -0
  82. python_lab_toolkit-1.0.0.dist-info/METADATA +427 -0
  83. python_lab_toolkit-1.0.0.dist-info/RECORD +86 -0
  84. python_lab_toolkit-1.0.0.dist-info/WHEEL +5 -0
  85. python_lab_toolkit-1.0.0.dist-info/entry_points.txt +2 -0
  86. python_lab_toolkit-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,46 @@
1
+ import sys
2
+ from text_preprocessor import normalize_text, remove_punctuation, tokenize
3
+ from text_analyzer import compute_word_frequencies, count_alphabetic_characters, count_unique_words
4
+
5
+ def display_docstrings():
6
+ print("=== Function Docstrings (Inspection) ===")
7
+ functions = [
8
+ ("normalize_text", normalize_text),
9
+ ("remove_punctuation", remove_punctuation),
10
+ ("tokenize", tokenize),
11
+ ("compute_word_frequencies", compute_word_frequencies),
12
+ ("count_alphabetic_characters", count_alphabetic_characters),
13
+ ("count_unique_words", count_unique_words),
14
+ ]
15
+ for name, func in functions:
16
+ print(f"Function: {name}")
17
+ print(f"Docstring: {func.__doc__.strip()}\n")
18
+
19
+ def main():
20
+ sample_paragraph = (
21
+ "Python is a versatile, high-level programming language. "
22
+ "Python emphasizes code readability, and Python developers love clean software!"
23
+ )
24
+ print("=== Modular Text Analysis Demonstration ===")
25
+ print(f"Input Text:\n\"{sample_paragraph}\"\n")
26
+
27
+ alpha_count = count_alphabetic_characters(sample_paragraph)
28
+ normalized = normalize_text(sample_paragraph)
29
+ clean_text = remove_punctuation(normalized)
30
+ tokens = tokenize(clean_text)
31
+ frequencies = compute_word_frequencies(tokens)
32
+ unique_count = count_unique_words(tokens)
33
+
34
+ print(f"Total Alphabetic Characters: {alpha_count}")
35
+ print(f"Total Word Tokens : {len(tokens)}")
36
+ print(f"Total Unique Words : {unique_count}\n")
37
+ print("Word Frequencies (sorted by occurrences):")
38
+ sorted_freq = sorted(frequencies.items(), key=lambda item: item[1], reverse=True)
39
+ for word, count in sorted_freq:
40
+ print(f" {word:<14} : {count}")
41
+
42
+ print()
43
+ display_docstrings()
44
+
45
+ if __name__ == "__main__":
46
+ main()
@@ -0,0 +1,16 @@
1
+ from typing import Dict, List
2
+
3
+ def compute_word_frequencies(tokens: List[str]) -> Dict[str, int]:
4
+ """Computes the frequency count for every unique token in the list."""
5
+ frequencies = {}
6
+ for token in tokens:
7
+ frequencies[token] = frequencies.get(token, 0) + 1
8
+ return frequencies
9
+
10
+ def count_alphabetic_characters(text: str) -> int:
11
+ """Counts the total number of alphabetic characters present in the text."""
12
+ return sum(1 for char in text if char.isalpha())
13
+
14
+ def count_unique_words(tokens: List[str]) -> int:
15
+ """Returns the count of distinct words present in the token list."""
16
+ return len(set(tokens))
@@ -0,0 +1,15 @@
1
+ import string
2
+ from typing import List
3
+
4
+ def normalize_text(text: str) -> str:
5
+ """Converts the input string to lowercase and trims surrounding whitespace."""
6
+ return text.strip().lower()
7
+
8
+ def remove_punctuation(text: str) -> str:
9
+ """Removes all standard punctuation marks from the provided text."""
10
+ translator = str.maketrans("", "", string.punctuation)
11
+ return text.translate(translator)
12
+
13
+ def tokenize(text: str) -> List[str]:
14
+ """Splits a normalized, unpunctuated text into a list of word tokens."""
15
+ return text.split()
@@ -0,0 +1,26 @@
1
+ import sys
2
+
3
+ class Student:
4
+ def __init__(self, name, roll_number, course):
5
+ self.name = name.strip()
6
+ self.roll_number = str(roll_number).strip()
7
+ self.course = course.strip()
8
+
9
+ def display(self):
10
+ print(f"Name : {self.name}")
11
+ print(f"Roll Number : {self.roll_number}")
12
+ print(f"Course : {self.course}")
13
+ print("-" * 30)
14
+
15
+ def main():
16
+ print("=== Student Record Display System ===")
17
+ student_records = [
18
+ Student("Aarav Sharma", "CS202601", "Computer Science"),
19
+ Student("Diya Patel", "DS202614", "Data Science & AI"),
20
+ Student("Kabir Mehta", "CY202622", "Cybersecurity"),
21
+ ]
22
+ for s in student_records:
23
+ s.display()
24
+
25
+ if __name__ == "__main__":
26
+ main()
@@ -0,0 +1,26 @@
1
+ import math
2
+ import sys
3
+
4
+ class Circle:
5
+ def __init__(self, radius):
6
+ if radius < 0:
7
+ raise ValueError("Circle radius cannot be negative.")
8
+ self.radius = float(radius)
9
+
10
+ def area(self):
11
+ return math.pi * (self.radius ** 2)
12
+
13
+ def circumference(self):
14
+ return 2 * math.pi * self.radius
15
+
16
+ def main():
17
+ print("=== Circle Properties Calculator ===")
18
+ radii = [1.0, 3.5, 7.0, 10.0, 14.5]
19
+ print(f"{'Radius':<10} | {'Area':<16} | {'Circumference':<16}")
20
+ print("-" * 48)
21
+ for r in radii:
22
+ c = Circle(r)
23
+ print(f"{c.radius:<10.2f} | {c.area():<16.4f} | {c.circumference():<16.4f}")
24
+
25
+ if __name__ == "__main__":
26
+ main()
@@ -0,0 +1,46 @@
1
+ import sys
2
+
3
+ class Employee:
4
+ HRA_RATE = 0.20
5
+ DA_RATE = 0.10
6
+
7
+ def __init__(self, emp_id, name, basic_pay):
8
+ self.emp_id = str(emp_id).strip()
9
+ self.name = name.strip()
10
+ if basic_pay < 0:
11
+ raise ValueError("Basic pay cannot be negative.")
12
+ self.basic_pay = float(basic_pay)
13
+
14
+ def calculate_hra(self):
15
+ return self.basic_pay * self.HRA_RATE
16
+
17
+ def calculate_da(self):
18
+ return self.basic_pay * self.DA_RATE
19
+
20
+ def calculate_gross_salary(self):
21
+ return self.basic_pay + self.calculate_hra() + self.calculate_da()
22
+
23
+ def display_salary_slip(self):
24
+ hra = self.calculate_hra()
25
+ da = self.calculate_da()
26
+ gross = self.calculate_gross_salary()
27
+ print(f"Employee ID : {self.emp_id}")
28
+ print(f"Name : {self.name}")
29
+ print(f"Basic Pay : ₹{self.basic_pay:,.2f}")
30
+ print(f"HRA (20%) : ₹{hra:,.2f}")
31
+ print(f"DA (10%) : ₹{da:,.2f}")
32
+ print(f"Gross Salary : ₹{gross:,.2f}")
33
+ print("=" * 36)
34
+
35
+ def main():
36
+ print("=== Employee Salary Statement ===")
37
+ team = [
38
+ Employee("E101", "Priya Nair", 45000),
39
+ Employee("E102", "Rajesh Kumar", 62000),
40
+ Employee("E103", "Ananya Sen", 80000),
41
+ ]
42
+ for emp in team:
43
+ emp.display_salary_slip()
44
+
45
+ if __name__ == "__main__":
46
+ main()
@@ -0,0 +1,51 @@
1
+ import sys
2
+
3
+ class SmartCalculator:
4
+ def add(self, a=0, b=0, c=0):
5
+ return a + b + c
6
+
7
+ def multiply(self, *args):
8
+ if not args:
9
+ return 0
10
+ product = 1
11
+ for val in args:
12
+ product *= val
13
+ return product
14
+
15
+ def process_data(self, data):
16
+ if isinstance(data, (int, float)):
17
+ return f"Numeric absolute square: {abs(data) ** 2}"
18
+ elif isinstance(data, str):
19
+ return f"Processed string (length {len(data)}): {data.upper()}"
20
+ elif isinstance(data, (list, tuple, set)):
21
+ return f"Collection with {len(data)} items, sorted: {sorted(list(data))}"
22
+ elif isinstance(data, dict):
23
+ return f"Dictionary with keys: {list(data.keys())}"
24
+ else:
25
+ return f"Unsupported data type: {type(data).__name__}"
26
+
27
+ def main():
28
+ print("=== SmartCalculator Demonstration ===")
29
+ calc = SmartCalculator()
30
+
31
+ print("1. Addition with Default Arguments:")
32
+ print(" calc.add() = ", calc.add())
33
+ print(" calc.add(10) = ", calc.add(10))
34
+ print(" calc.add(10, 20) = ", calc.add(10, 20))
35
+ print(" calc.add(10, 20, 30) = ", calc.add(10, 20, 30))
36
+
37
+ print("\n2. Multiplication with Variable Arguments (*args):")
38
+ print(" calc.multiply() = ", calc.multiply())
39
+ print(" calc.multiply(5) = ", calc.multiply(5))
40
+ print(" calc.multiply(2, 3, 4) = ", calc.multiply(2, 3, 4))
41
+ print(" calc.multiply(1, 2, 3, 4, 5, 6) = ", calc.multiply(1, 2, 3, 4, 5, 6))
42
+
43
+ print("\n3. Type-Dependent Processing:")
44
+ print(" Integer :", calc.process_data(12))
45
+ print(" Float :", calc.process_data(-4.5))
46
+ print(" String :", calc.process_data("python lab toolkit"))
47
+ print(" List :", calc.process_data([42, 7, 19, 3, 88]))
48
+ print(" Dict :", calc.process_data({"id": 1, "status": "active"}))
49
+
50
+ if __name__ == "__main__":
51
+ main()
@@ -0,0 +1,43 @@
1
+ import sys
2
+
3
+ class ComplexNumber:
4
+ def __init__(self, real=0.0, imag=0.0):
5
+ self.real = float(real)
6
+ self.imag = float(imag)
7
+
8
+ def __add__(self, other):
9
+ if not isinstance(other, ComplexNumber):
10
+ return NotImplemented
11
+ return ComplexNumber(self.real + other.real, self.imag + other.imag)
12
+
13
+ def __eq__(self, other):
14
+ if not isinstance(other, ComplexNumber):
15
+ return False
16
+ return math_is_close(self.real, other.real) and math_is_close(self.imag, other.imag)
17
+
18
+ def __str__(self):
19
+ sign = "+" if self.imag >= 0 else "-"
20
+ return f"{self.real:.2f} {sign} {abs(self.imag):.2f}i"
21
+
22
+ def __repr__(self):
23
+ return f"ComplexNumber(real={self.real}, imag={self.imag})"
24
+
25
+ def math_is_close(a, b, tol=1e-9):
26
+ return abs(a - b) <= tol
27
+
28
+ def main():
29
+ print("=== Complex Number Operator Overloading (+, ==) ===")
30
+ c1 = ComplexNumber(3.5, 4.2)
31
+ c2 = ComplexNumber(1.5, -2.2)
32
+ c3 = ComplexNumber(5.0, 2.0)
33
+
34
+ c_sum = c1 + c2
35
+ print(f"c1 : {c1}")
36
+ print(f"c2 : {c2}")
37
+ print(f"c1 + c2 : {c_sum}")
38
+ print(f"c3 : {c3}")
39
+ print(f"c_sum == c3 : {c_sum == c3}")
40
+ print(f"c1 == c2 : {c1 == c2}")
41
+
42
+ if __name__ == "__main__":
43
+ main()
@@ -0,0 +1,43 @@
1
+ import sys
2
+
3
+ class Vehicle:
4
+ def __init__(self, make, model, year):
5
+ self.make = make.strip()
6
+ self.model = model.strip()
7
+ self.year = int(year)
8
+
9
+ def start_engine(self):
10
+ return f"The {self.year} {self.make} {self.model} engine is starting with a gentle purr."
11
+
12
+ def get_details(self):
13
+ return f"Vehicle: {self.year} {self.make} {self.model}"
14
+
15
+ class Car(Vehicle):
16
+ def __init__(self, make, model, year, num_doors, fuel_type):
17
+ super().__init__(make, model, year)
18
+ self.num_doors = int(num_doors)
19
+ self.fuel_type = fuel_type.strip()
20
+
21
+ def start_engine(self):
22
+ base_status = super().start_engine()
23
+ return f"{base_status} The dashboard lights illuminate in sport mode."
24
+
25
+ def get_details(self):
26
+ parent_details = super().get_details()
27
+ return f"{parent_details} [Doors: {self.num_doors}, Fuel: {self.fuel_type}]"
28
+
29
+ def main():
30
+ print("=== Vehicle and Car Inheritance Demonstration ===")
31
+ v = Vehicle("GenericMotors", "Utility-X", 2021)
32
+ c = Car("Tesla", "Model 3", 2024, 4, "Electric")
33
+
34
+ print("Vehicle Instance:")
35
+ print(" Details:", v.get_details())
36
+ print(" Engine :", v.start_engine())
37
+ print()
38
+ print("Car Instance (Subclass using super()):")
39
+ print(" Details:", c.get_details())
40
+ print(" Engine :", c.start_engine())
41
+
42
+ if __name__ == "__main__":
43
+ main()
@@ -0,0 +1,48 @@
1
+ import collections
2
+ import os
3
+ import sys
4
+
5
+ def analyze_text_file(filepath):
6
+ if not os.path.exists(filepath):
7
+ raise FileNotFoundError(f"File '{filepath}' does not exist.")
8
+
9
+ total_lines = 0
10
+ total_words = 0
11
+ total_characters = 0
12
+ word_counter = collections.Counter()
13
+
14
+ with open(filepath, "r", encoding="utf-8") as f:
15
+ for line in f:
16
+ total_lines += 1
17
+ total_characters += len(line)
18
+ clean_words = [w.strip(".,!?:;\"'()[]{}") for w in line.lower().split()]
19
+ valid_words = [w for w in clean_words if w]
20
+ total_words += len(valid_words)
21
+ word_counter.update(valid_words)
22
+
23
+ top_five = word_counter.most_common(5)
24
+ return {
25
+ "lines": total_lines,
26
+ "words": total_words,
27
+ "characters": total_characters,
28
+ "top_five": top_five
29
+ }
30
+
31
+ def main():
32
+ target = sys.argv[1] if len(sys.argv) > 1 else "sample.txt"
33
+ print(f"=== Text File Statistics Analyzer: '{target}' ===")
34
+ try:
35
+ stats = analyze_text_file(target)
36
+ print(f"Total Lines : {stats['lines']}")
37
+ print(f"Total Words : {stats['words']}")
38
+ print(f"Total Characters : {stats['characters']}")
39
+ print("\nTop 5 Most Frequent Words:")
40
+ for word, count in stats["top_five"]:
41
+ print(f" {word:<12} : {count} occurrences")
42
+ except FileNotFoundError as e:
43
+ print(f"Error: {e}")
44
+ except PermissionError as e:
45
+ print(f"Permission Error: Access denied for '{target}'. {e}")
46
+
47
+ if __name__ == "__main__":
48
+ main()
@@ -0,0 +1,6 @@
1
+ Python is an easy to learn, powerful programming language.
2
+ It has efficient high-level data structures and a simple but effective approach to object-oriented programming.
3
+ Python elegant syntax and dynamic typing, together with its interpreted nature,
4
+ make it an ideal language for scripting and rapid application development in many areas on most platforms.
5
+ The Python interpreter and the extensive standard library are freely available in source or binary form.
6
+ Python encourages programmers to write clean, readable code with modular design.
@@ -0,0 +1,26 @@
1
+ import sys
2
+
3
+ def find_single_number(numbers):
4
+ if not numbers:
5
+ raise ValueError("The input list cannot be empty.")
6
+ unique_val = 0
7
+ for num in numbers:
8
+ unique_val ^= num
9
+ return unique_val
10
+
11
+ def main():
12
+ print("=== Single Number Finder using XOR ===")
13
+ sample_arrays = [
14
+ [4, 1, 2, 1, 2],
15
+ [2, 2, 1],
16
+ [17, 45, 17, 89, 45],
17
+ [99],
18
+ [10, 20, 30, 40, 50, 40, 30, 20, 10]
19
+ ]
20
+ for arr in sample_arrays:
21
+ unique_item = find_single_number(arr)
22
+ print(f"Array: {arr}")
23
+ print(f"Single Unique Element: {unique_item}\n")
24
+
25
+ if __name__ == "__main__":
26
+ main()
@@ -0,0 +1,27 @@
1
+ import sys
2
+
3
+ class InvalidAgeException(Exception):
4
+ def __init__(self, age, message="Age must be between 18 and 60 inclusive."):
5
+ self.age = age
6
+ self.message = message
7
+ super().__init__(f"InvalidAgeException: Age {age} is outside the allowed range. {message}")
8
+
9
+ def validate_age(age):
10
+ if not isinstance(age, (int, float)):
11
+ raise TypeError("Age must be a numeric value.")
12
+ if age < 18 or age > 60:
13
+ raise InvalidAgeException(age)
14
+ return True
15
+
16
+ def main():
17
+ print("=== Custom InvalidAgeException Validator (Range: 18 - 60) ===")
18
+ test_ages = [15, 18, 25, 45, 60, 65, -2]
19
+ for candidate in test_ages:
20
+ try:
21
+ validate_age(candidate)
22
+ print(f"[APPROVED] Age {candidate:<3}: Valid applicant age.")
23
+ except InvalidAgeException as err:
24
+ print(f"[REJECTED] Age {candidate:<3}: {err.message}")
25
+
26
+ if __name__ == "__main__":
27
+ main()
@@ -0,0 +1,45 @@
1
+ import sys
2
+
3
+ class InsufficientBalanceError(Exception):
4
+ pass
5
+
6
+ class BankAccount:
7
+ def __init__(self, owner, balance):
8
+ self.owner = owner
9
+ self.balance = float(balance)
10
+
11
+ def withdraw(self, amount):
12
+ print(f"Initiating withdrawal of ₹{amount:,.2f} for account: {self.owner}")
13
+ try:
14
+ if amount <= 0:
15
+ raise ValueError("Withdrawal amount must be greater than zero.")
16
+ if amount > self.balance:
17
+ raise InsufficientBalanceError(
18
+ f"Insufficient funds! Requested: ₹{amount:,.2f}, Available: ₹{self.balance:,.2f}"
19
+ )
20
+ self.balance -= amount
21
+ except ValueError as ve:
22
+ print(f" [EXCEPT] Validation Failure: {ve}")
23
+ raise
24
+ except InsufficientBalanceError as ibe:
25
+ print(f" [EXCEPT] Transaction Declined: {ibe}")
26
+ raise
27
+ else:
28
+ print(f" [ELSE] Transaction Authorized! Remaining Balance: ₹{self.balance:,.2f}")
29
+ return self.balance
30
+ finally:
31
+ print(" [FINALLY] Releasing transaction lock and writing audit ledger entry.\n")
32
+
33
+ def main():
34
+ print("=== Robust Transaction Error Handling (try-except-else-finally) ===")
35
+ account = BankAccount("Rohit Sharma", 5000.0)
36
+
37
+ test_amounts = [1500.0, 4000.0, -200.0]
38
+ for amt in test_amounts:
39
+ try:
40
+ account.withdraw(amt)
41
+ except Exception:
42
+ pass
43
+
44
+ if __name__ == "__main__":
45
+ main()
@@ -0,0 +1,30 @@
1
+ import datetime
2
+ import sys
3
+
4
+ def format_date(date_str):
5
+ clean_str = date_str.strip()
6
+ try:
7
+ parsed_date = datetime.datetime.strptime(clean_str, "%d-%m-%Y")
8
+ return True, parsed_date.strftime("%B %d, %Y")
9
+ except ValueError as err:
10
+ return False, f"Invalid date '{date_str}': {err}"
11
+
12
+ def main():
13
+ print("=== Date Formatter and Validator (dd-mm-yyyy -> MonthName dd, yyyy) ===")
14
+ dates_to_test = [
15
+ "15-08-1947",
16
+ "26-01-1950",
17
+ "29-02-2024",
18
+ "29-02-2023",
19
+ "31-04-2023",
20
+ "12-13-2023",
21
+ "05-11-2026",
22
+ "invalid-date",
23
+ ]
24
+ for raw_date in dates_to_test:
25
+ valid, result = format_date(raw_date)
26
+ status = "[VALID] " if valid else "[INVALID]"
27
+ print(f" {status} {raw_date:<14} -> {result}")
28
+
29
+ if __name__ == "__main__":
30
+ main()
@@ -0,0 +1,73 @@
1
+ import csv
2
+ import os
3
+ import sys
4
+
5
+ def calculate_std(values, mean_val):
6
+ try:
7
+ import numpy as np
8
+ return float(np.std(values))
9
+ except ImportError:
10
+ variance = sum((x - mean_val) ** 2 for x in values) / len(values)
11
+ return variance ** 0.5
12
+
13
+ def analyze_rainfall(input_path, output_summary_path="rainfall_summary.csv"):
14
+ if not os.path.exists(input_path):
15
+ raise FileNotFoundError(f"Rainfall file '{input_path}' not found.")
16
+
17
+ station_data = {}
18
+ all_readings = []
19
+ max_rainfall = -1.0
20
+ max_record = None
21
+
22
+ with open(input_path, "r", encoding="utf-8") as f:
23
+ reader = csv.DictReader(f)
24
+ for row in reader:
25
+ station = row["Station"].strip()
26
+ date_str = row["Date"].strip()
27
+ val = float(row["Rainfall"])
28
+
29
+ if station not in station_data:
30
+ station_data[station] = []
31
+ station_data[station].append(val)
32
+ all_readings.append(val)
33
+
34
+ if val > max_rainfall:
35
+ max_rainfall = val
36
+ max_record = (station, date_str, val)
37
+
38
+ print("=== Rainfall Data Analysis ===")
39
+ print(f"Total Records Processed: {len(all_readings)}")
40
+ print(f"Distinct Stations Count : {len(station_data)}")
41
+ if max_record:
42
+ print(f"Maximum Rainfall Record : {max_record[2]} mm at {max_record[0]} on {max_record[1]}")
43
+
44
+ summary_rows = []
45
+ print("\nStation Statistics:")
46
+ print(f"{'Station':<18} | {'Avg (mm)':<10} | {'Std Dev (mm)':<12} | {'Readings':<8}")
47
+ print("-" * 56)
48
+ for st, vals in sorted(station_data.items()):
49
+ avg_val = sum(vals) / len(vals)
50
+ std_val = calculate_std(vals, avg_val)
51
+ summary_rows.append({
52
+ "Station": st,
53
+ "Average_Rainfall": round(avg_val, 2),
54
+ "Std_Deviation": round(std_val, 2),
55
+ "Total_Readings": len(vals)
56
+ })
57
+ print(f"{st:<18} | {avg_val:<10.2f} | {std_val:<12.2f} | {len(vals):<8}")
58
+
59
+ with open(output_summary_path, "w", newline="", encoding="utf-8") as out_f:
60
+ fieldnames = ["Station", "Average_Rainfall", "Std_Deviation", "Total_Readings"]
61
+ writer = csv.DictWriter(out_f, fieldnames=fieldnames)
62
+ writer.writeheader()
63
+ writer.writerows(summary_rows)
64
+
65
+ print(f"\nSummary report exported successfully to: {output_summary_path}")
66
+ return summary_rows
67
+
68
+ def main():
69
+ target = sys.argv[1] if len(sys.argv) > 1 else "rainfall.csv"
70
+ analyze_rainfall(target)
71
+
72
+ if __name__ == "__main__":
73
+ main()
@@ -0,0 +1,58 @@
1
+ import csv
2
+ import os
3
+ import sys
4
+
5
+ SAMPLE_STUDENTS = [
6
+ {"StudentID": "S101", "Name": "Aarav Sharma", "Marks": 88.5},
7
+ {"StudentID": "S102", "Name": "Diya Patel", "Marks": 94.0},
8
+ {"StudentID": "S103", "Name": "Kabir Mehta", "Marks": 79.5},
9
+ {"StudentID": "S104", "Name": "Ananya Sen", "Marks": 97.5},
10
+ {"StudentID": "S105", "Name": "Rohan Verma", "Marks": 83.0},
11
+ {"StudentID": "S106", "Name": "Ishaan Gupta", "Marks": 91.0},
12
+ ]
13
+
14
+ def ensure_students_csv(filepath):
15
+ if not os.path.exists(filepath):
16
+ with open(filepath, "w", newline="", encoding="utf-8") as f:
17
+ writer = csv.DictWriter(f, fieldnames=["StudentID", "Name", "Marks"])
18
+ writer.writeheader()
19
+ writer.writerows(SAMPLE_STUDENTS)
20
+
21
+ def process_students_csv(filepath):
22
+ ensure_students_csv(filepath)
23
+ students = []
24
+ total_marks = 0.0
25
+ highest_student = None
26
+
27
+ with open(filepath, "r", encoding="utf-8") as f:
28
+ reader = csv.DictReader(f)
29
+ for row in reader:
30
+ s_id = row["StudentID"].strip()
31
+ name = row["Name"].strip()
32
+ marks = float(row["Marks"])
33
+ record = {"StudentID": s_id, "Name": name, "Marks": marks}
34
+ students.append(record)
35
+ total_marks += marks
36
+ if highest_student is None or marks > highest_student["Marks"]:
37
+ highest_student = record
38
+
39
+ avg_marks = total_marks / len(students) if students else 0.0
40
+
41
+ print("=== Student Marks CSV Evaluation ===")
42
+ print(f"{'StudentID':<10} | {'Name':<18} | {'Marks':<8}")
43
+ print("-" * 42)
44
+ for s in students:
45
+ print(f"{s['StudentID']:<10} | {s['Name']:<18} | {s['Marks']:<8.2f}")
46
+
47
+ print("-" * 42)
48
+ print(f"Class Average Marks : {avg_marks:.2f}")
49
+ if highest_student:
50
+ print(f"Highest Scoring Student : {highest_student['Name']} ({highest_student['StudentID']}) with {highest_student['Marks']:.2f} marks")
51
+ return students, highest_student, avg_marks
52
+
53
+ def main():
54
+ target = sys.argv[1] if len(sys.argv) > 1 else "students.csv"
55
+ process_students_csv(target)
56
+
57
+ if __name__ == "__main__":
58
+ main()