pamdays 0.1.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 (69) hide show
  1. pamdays/__init__.py +55 -0
  2. pamdays/aidsbd/__init__.py +72 -0
  3. pamdays/aidsbd/p1.py +80 -0
  4. pamdays/aidsbd/p10.py +176 -0
  5. pamdays/aidsbd/p11.py +79 -0
  6. pamdays/aidsbd/p2.py +93 -0
  7. pamdays/aidsbd/p3.py +113 -0
  8. pamdays/aidsbd/p4.py +213 -0
  9. pamdays/aidsbd/p5.py +53 -0
  10. pamdays/aidsbd/p6.py +61 -0
  11. pamdays/aidsbd/p7.py +93 -0
  12. pamdays/aidsbd/p8.py +77 -0
  13. pamdays/aidsbd/p9.py +167 -0
  14. pamdays/core.py +161 -0
  15. pamdays/display.py +24 -0
  16. pamdays/dstt/__init__.py +59 -0
  17. pamdays/dstt/p1.py +68 -0
  18. pamdays/dstt/p2.py +181 -0
  19. pamdays/dstt/p3.py +99 -0
  20. pamdays/dstt/p4.py +52 -0
  21. pamdays/dstt/p5.py +53 -0
  22. pamdays/dstt/p6.py +47 -0
  23. pamdays/dstt/p7.py +64 -0
  24. pamdays/dstt/p8.py +66 -0
  25. pamdays/mobile/__init__.py +45 -0
  26. pamdays/mobile/p1.py +49 -0
  27. pamdays/mobile/p2.py +51 -0
  28. pamdays/mobile/p3.py +85 -0
  29. pamdays/mobile/p4.py +130 -0
  30. pamdays/mobile/p5.py +101 -0
  31. pamdays/programming/__init__.py +30 -0
  32. pamdays/programming/cloud/__init__.py +37 -0
  33. pamdays/programming/cloud/p1.py +63 -0
  34. pamdays/programming/cloud/p2.py +63 -0
  35. pamdays/programming/cloud/p3.py +56 -0
  36. pamdays/programming/cloud/p4.py +44 -0
  37. pamdays/programming/cybersecurity/__init__.py +39 -0
  38. pamdays/programming/cybersecurity/p1.py +126 -0
  39. pamdays/programming/cybersecurity/p2.py +66 -0
  40. pamdays/programming/cybersecurity/p3.py +63 -0
  41. pamdays/programming/cybersecurity/p4.py +60 -0
  42. pamdays/programming/nlp/__init__.py +48 -0
  43. pamdays/programming/nlp/p1.py +68 -0
  44. pamdays/programming/nlp/p2.py +51 -0
  45. pamdays/programming/nlp/p3.py +78 -0
  46. pamdays/programming/nlp/p4.py +88 -0
  47. pamdays/programming/nlp/p5.py +66 -0
  48. pamdays/programming/nnfl/__init__.py +37 -0
  49. pamdays/programming/nnfl/p1.py +71 -0
  50. pamdays/programming/nnfl/p2.py +68 -0
  51. pamdays/programming/nnfl/p3.py +57 -0
  52. pamdays/programming/nnfl/p4.py +55 -0
  53. pamdays/programming/uiux/__init__.py +38 -0
  54. pamdays/programming/uiux/p1.py +53 -0
  55. pamdays/programming/uiux/p2.py +57 -0
  56. pamdays/programming/uiux/p3.py +50 -0
  57. pamdays/programming/uiux/p4.py +48 -0
  58. pamdays/programming/webtech/__init__.py +38 -0
  59. pamdays/programming/webtech/p1.py +52 -0
  60. pamdays/programming/webtech/p2.py +68 -0
  61. pamdays/programming/webtech/p3.py +98 -0
  62. pamdays/programming/webtech/p4.py +82 -0
  63. pamdays/registry.py +50 -0
  64. pamdays/search.py +60 -0
  65. pamdays-0.1.0.dist-info/METADATA +177 -0
  66. pamdays-0.1.0.dist-info/RECORD +69 -0
  67. pamdays-0.1.0.dist-info/WHEEL +5 -0
  68. pamdays-0.1.0.dist-info/licenses/LICENSE +21 -0
  69. pamdays-0.1.0.dist-info/top_level.txt +1 -0
pamdays/__init__.py ADDED
@@ -0,0 +1,55 @@
1
+ """
2
+ pamdays
3
+ ~~~~~~~
4
+ Subject-wise practical-code library for TY B.Tech AI & DS students.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pamdays import aidsbd, dstt, mobile, programming
10
+ from pamdays.registry import REGISTRY
11
+ from pamdays.search import search
12
+
13
+ __version__ = "0.1.0"
14
+ __all__ = [
15
+ "aidsbd",
16
+ "dstt",
17
+ "programming",
18
+ "mobile",
19
+ "search",
20
+ "subjects",
21
+ "REGISTRY",
22
+ ]
23
+
24
+
25
+ def subjects():
26
+ """Return metadata for all available curriculum subjects."""
27
+ return [
28
+ {
29
+ "alias": "aidsbd",
30
+ "title": "Artificial Intelligence & Data Science and Big Data Lab",
31
+ "code": "2311304",
32
+ "alt_code": "2301304",
33
+ "semester": "V",
34
+ "notes": "Listed as Semester V in curriculum (course code 2301304 on p.1, 2311304 on p.9).",
35
+ },
36
+ {
37
+ "alias": "dstt",
38
+ "title": "Data Science Techniques and Tools Lab",
39
+ "code": "2311313",
40
+ "semester": "VI",
41
+ },
42
+ {
43
+ "alias": "programming",
44
+ "title": "Programming Lab",
45
+ "code": "2311316",
46
+ "semester": "VI",
47
+ "electives": ["uiux", "nnfl", "webtech", "cloud", "nlp", "cybersecurity"],
48
+ },
49
+ {
50
+ "alias": "mobile",
51
+ "title": "Mobile Application Development",
52
+ "code": "2311319",
53
+ "semester": "VI",
54
+ },
55
+ ]
@@ -0,0 +1,72 @@
1
+ """
2
+ pamdays.aidsbd
3
+ ~~~~~~~~~~~~~~
4
+ Artificial Intelligence & Data Science and Big Data Lab | Sem V | 2311304 (2301304 on p.1)
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pamdays.aidsbd import (
10
+ p1 as _p1,
11
+ p2 as _p2,
12
+ p3 as _p3,
13
+ p4 as _p4,
14
+ p5 as _p5,
15
+ p6 as _p6,
16
+ p7 as _p7,
17
+ p8 as _p8,
18
+ p9 as _p9,
19
+ p10 as _p10,
20
+ p11 as _p11,
21
+ )
22
+ from pamdays.display import print_subject_list
23
+ from pamdays.registry import get_practical
24
+
25
+ p1 = _p1.practical
26
+ p2 = _p2.practical
27
+ p3 = _p3.practical
28
+ p4 = _p4.practical
29
+ p5 = _p5.practical
30
+ p6 = _p6.practical
31
+ p7 = _p7.practical
32
+ p8 = _p8.practical
33
+ p9 = _p9.practical
34
+ p10 = _p10.practical
35
+ p11 = _p11.practical
36
+
37
+ # Concept aliases (point directly to the Practical objects)
38
+ astar = p1
39
+ minimax = p2
40
+ alphabeta = p3
41
+ csp = p4
42
+ nqueens = p4.nqueens
43
+ graphcoloring = p4.graphcoloring
44
+ sudoku = p4.sudoku
45
+ chatbot = p5
46
+ expertsystem = p6
47
+ datapreprocessing = p7
48
+ pca = p8
49
+ regression = p9
50
+ linearregression = p9.linear
51
+ logisticregression = p9.logistic
52
+ classification = p10
53
+ svm = p10.svm
54
+ spam = p10.svm
55
+ knn = p10.knn
56
+ kmeans = p11
57
+
58
+ _ALL = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11]
59
+
60
+
61
+ def list(detailed: bool = False) -> None: # noqa: A001
62
+ """List all practicals in AI & DSBD Lab."""
63
+ print_subject_list(
64
+ "Artificial Intelligence & Data Science and Big Data Lab (aidsbd) | Sem V | 2311304",
65
+ _ALL,
66
+ detailed=detailed,
67
+ )
68
+
69
+
70
+ def get(key):
71
+ """Return a Practical by number (int) or alias (str)."""
72
+ return get_practical("aidsbd", key)
pamdays/aidsbd/p1.py ADDED
@@ -0,0 +1,80 @@
1
+ """pamdays.aidsbd.p1 - A* Search Algorithm"""
2
+
3
+ from pamdays.core import Practical
4
+ from pamdays.registry import register
5
+
6
+ _CODE = '''\
7
+ import heapq
8
+
9
+ n = int(input("Enter grid size (e.g. 5): "))
10
+ grid = [[0] * n for _ in range(n)]
11
+ obs = int(input("Number of obstacles: "))
12
+ for _ in range(obs):
13
+ r, c = map(int, input("Obstacle row col: ").split())
14
+ grid[r][c] = 1
15
+
16
+ sr, sc = map(int, input("Start row col: ").split())
17
+ gr, gc = map(int, input("Goal row col: ").split())
18
+ start, goal = (sr, sc), (gr, gc)
19
+
20
+ def h(a, b):
21
+ return abs(a[0] - b[0]) + abs(a[1] - b[1])
22
+
23
+ open_heap = [(h(start, goal), 0, start)]
24
+ came_from = {}
25
+ g_score = {start: 0}
26
+ closed = set()
27
+
28
+ while open_heap:
29
+ _, g, cur = heapq.heappop(open_heap)
30
+ if cur == goal:
31
+ path = []
32
+ while cur in came_from:
33
+ path.append(cur)
34
+ cur = came_from[cur]
35
+ path.append(start)
36
+ print("Shortest Path:", " -> ".join(map(str, path[::-1])))
37
+ break
38
+ if cur in closed:
39
+ continue
40
+ closed.add(cur)
41
+ for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
42
+ nr, nc = cur[0] + dr, cur[1] + dc
43
+ nxt = (nr, nc)
44
+ if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0:
45
+ ng = g + 1
46
+ if ng < g_score.get(nxt, float("inf")):
47
+ g_score[nxt] = ng
48
+ came_from[nxt] = cur
49
+ heapq.heappush(open_heap, (ng + h(nxt, goal), ng, nxt))
50
+ else:
51
+ print("No path found.")
52
+ '''
53
+
54
+ practical = register(
55
+ "aidsbd",
56
+ Practical(
57
+ number=1,
58
+ title="Implement A star (A*) Algorithm for any game search problem",
59
+ concept="astar",
60
+ subject="aidsbd",
61
+ language="python",
62
+ runnable=True,
63
+ aim="Implement the A* search algorithm to find the shortest path on a grid with obstacles.",
64
+ problem_statement="Implement A star (A*) Algorithm for any game search problem.",
65
+ algorithm=[
66
+ "Read grid size, obstacle coordinates, start state, and goal state.",
67
+ "Initialize the open priority queue with start node where f(n) = g(n) + h(n) using Manhattan distance.",
68
+ "Pop the node with the lowest f-score from the open queue.",
69
+ "If the popped node is the goal, reconstruct and print the path.",
70
+ "Otherwise expand valid 4-directional neighbours, update g-scores if a cheaper path is found, and push to open queue.",
71
+ "Repeat until goal is reached or open queue is empty.",
72
+ ],
73
+ code=_CODE,
74
+ sample_input="5\n2\n1 1\n2 2\n0 0\n4 4",
75
+ sample_output="Shortest Path: (0, 0) -> (0, 1) -> (0, 2) -> (0, 3) -> (0, 4) -> (1, 4) -> (2, 4) -> (3, 4) -> (4, 4)",
76
+ time_complexity="O(b^d) worst case (depends on heuristic quality; O(N^2 log N) on an N x N grid).",
77
+ space_complexity="O(b^d) to store open and closed states (O(N^2) on an N x N grid).",
78
+ notes="Uses 4-directional movement and Manhattan distance heuristic on an N x N grid.",
79
+ ),
80
+ )
pamdays/aidsbd/p10.py ADDED
@@ -0,0 +1,176 @@
1
+ """pamdays.aidsbd.p10 - Classification: SVM (Email Spam) OR KNN (Iris)"""
2
+
3
+ from pamdays.core import Practical
4
+ from pamdays.registry import register, register_alias
5
+
6
+ _SVM_CODE = r'''\
7
+ import os
8
+ import sys
9
+
10
+ try:
11
+ import pandas as pd
12
+ from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
13
+ from sklearn.model_selection import train_test_split
14
+ from sklearn.svm import SVC
15
+ except ImportError as e:
16
+ print(f"Missing dependency: {e.name}. Install with: pip install pandas scikit-learn")
17
+ sys.exit(1)
18
+
19
+ print("Dataset: emails.csv (https://www.kaggle.com/datasets/balaka18/email-pam-classification-dataset-csv)")
20
+ path = input("Enter emails.csv path: ").strip()
21
+ if not os.path.exists(path):
22
+ print(f"File not found: {path}")
23
+ print("Expected word-count feature columns + 'Prediction' target (0=Not Spam, 1=Spam).")
24
+ sys.exit(1)
25
+
26
+ df = pd.read_csv(path).dropna()
27
+ if "Email No." in df.columns:
28
+ df = df.drop(columns=["Email No."])
29
+ target = "Prediction" if "Prediction" in df.columns else df.columns[-1]
30
+ X = df.drop(columns=[target]).select_dtypes(include="number")
31
+ y = df[target]
32
+
33
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
34
+ model = SVC(kernel="linear").fit(X_train, y_train)
35
+ preds = model.predict(X_test)
36
+
37
+ print("Accuracy:", round(accuracy_score(y_test, preds), 4))
38
+ print("Confusion Matrix:\n", confusion_matrix(y_test, preds))
39
+ print("\nReport:\n", classification_report(y_test, preds, target_names=["Not Spam", "Spam"]))
40
+ '''
41
+
42
+ _KNN_CODE = r'''\
43
+ import os
44
+ import sys
45
+
46
+ try:
47
+ import pandas as pd
48
+ from sklearn.datasets import load_iris
49
+ from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score
50
+ from sklearn.model_selection import train_test_split
51
+ from sklearn.neighbors import KNeighborsClassifier
52
+ except ImportError as e:
53
+ print(f"Missing dependency: {e.name}. Install with: pip install pandas scikit-learn")
54
+ sys.exit(1)
55
+
56
+ path = input("Enter iris.csv path (or press Enter for built-in Iris dataset): ").strip()
57
+ if path:
58
+ if not os.path.exists(path):
59
+ print(f"File not found: {path}")
60
+ sys.exit(1)
61
+ df = pd.read_csv(path).dropna()
62
+ X = df.iloc[:, :-1].select_dtypes(include="number")
63
+ y = df.iloc[:, -1]
64
+ else:
65
+ iris = load_iris()
66
+ X, y = iris.data, iris.target
67
+
68
+ k = int(input("Enter k for KNN (e.g. 5): "))
69
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
70
+ model = KNeighborsClassifier(n_neighbors=k).fit(X_train, y_train)
71
+ preds = model.predict(X_test)
72
+
73
+ cm = confusion_matrix(y_test, preds)
74
+ acc = accuracy_score(y_test, preds)
75
+ prec = precision_score(y_test, preds, average="macro", zero_division=0)
76
+ rec = recall_score(y_test, preds, average="macro", zero_division=0)
77
+
78
+ print("Confusion Matrix:\n", cm)
79
+ print(f"Accuracy : {acc:.4f}")
80
+ print(f"Error Rate: {1 - acc:.4f}")
81
+ print(f"Precision : {prec:.4f}")
82
+ print(f"Recall : {rec:.4f}")
83
+
84
+ total = cm.sum()
85
+ for i in range(len(cm)):
86
+ tp = int(cm[i, i])
87
+ fp = int(cm[:, i].sum() - tp)
88
+ fn = int(cm[i, :].sum() - tp)
89
+ tn = int(total - tp - fp - fn)
90
+ print(f"Class {i} -> TP={tp}, FP={fp}, TN={tn}, FN={fn}")
91
+ '''
92
+
93
+ _COMBINED_CODE = r'''\
94
+ print("Practical 10 Alternatives:")
95
+ print("A) Email Spam Detection using SVM (emails.csv)")
96
+ print("B) KNN Classification on Iris Dataset")
97
+ choice = input("Choose A or B: ").strip().upper()
98
+
99
+ if choice == "A":
100
+ ''' + "\n".join(" " + line for line in _SVM_CODE.splitlines()) + '''
101
+ elif choice == "B":
102
+ ''' + "\n".join(" " + line for line in _KNN_CODE.splitlines()) + '''
103
+ else:
104
+ print("Invalid choice. Use p10.svm or p10.knn directly.")
105
+ '''
106
+
107
+ p_svm = Practical(
108
+ number=10,
109
+ title="Email Spam Classification using Support Vector Machine (SVM)",
110
+ concept="svm",
111
+ subject="aidsbd",
112
+ language="python",
113
+ runnable=True,
114
+ aim="Classify emails as Not Spam (0) or Spam (1) using SVM and analyze classification performance.",
115
+ problem_statement="Classify the email using binary classification (Not Spam / Spam) using Support Vector Machine on emails.csv.",
116
+ algorithm=[
117
+ "Load emails.csv and drop non-feature 'Email No.' column if present.",
118
+ "Split word-frequency features and 'Prediction' label 80/20 into train/test sets.",
119
+ "Train a linear Support Vector Classifier (SVC).",
120
+ "Print accuracy, confusion matrix, and classification report.",
121
+ ],
122
+ code=_SVM_CODE,
123
+ time_complexity="O(N^2 * D) to O(N^3 * D) depending on support vectors and kernel.",
124
+ space_complexity="O(N * D) for training data and support vectors.",
125
+ references=["https://www.kaggle.com/datasets/balaka18/email-pam-classification-dataset-csv"],
126
+ )
127
+
128
+ p_knn = Practical(
129
+ number=10,
130
+ title="KNN Classification on Iris Dataset with Confusion Matrix Metrics",
131
+ concept="knn",
132
+ subject="aidsbd",
133
+ language="python",
134
+ runnable=True,
135
+ aim="Classify Iris flowers using K-Nearest Neighbors and compute TP, FP, TN, FN, Accuracy, Error Rate, Precision, and Recall.",
136
+ problem_statement="Implement KNN classification algorithm on iris.csv dataset and compute Confusion matrix metrics.",
137
+ algorithm=[
138
+ "Load iris.csv (or fallback to sklearn built-in Iris dataset).",
139
+ "Split into 75% train and 25% test sets.",
140
+ "Fit KNeighborsClassifier with user-chosen k.",
141
+ "Compute confusion matrix, accuracy, error rate (1 - accuracy), macro precision, macro recall, and per-class TP/FP/TN/FN.",
142
+ ],
143
+ code=_KNN_CODE,
144
+ sample_input="\n5",
145
+ sample_output="Confusion Matrix, Accuracy, Error Rate, Precision, Recall, and per-class TP/FP/TN/FN.",
146
+ time_complexity="O(N * D) per test query for brute-force distance calculation.",
147
+ space_complexity="O(N * D) to store training instances.",
148
+ )
149
+
150
+ practical = register(
151
+ "aidsbd",
152
+ Practical(
153
+ number=10,
154
+ title="Classification: SVM Email Spam Detection OR KNN on Iris Dataset",
155
+ concept="classification",
156
+ subject="aidsbd",
157
+ language="python",
158
+ runnable=True,
159
+ aim="Perform binary email spam classification with SVM (Option A) or Iris classification with KNN (Option B).",
160
+ problem_statement=(
161
+ "A) Classify email spam using SVM on emails.csv. "
162
+ "OR B) Implement KNN classification on iris.csv and compute Confusion Matrix metrics."
163
+ ),
164
+ algorithm=[
165
+ "Select Option A (pamdays.aidsbd.p10.svm) or Option B (pamdays.aidsbd.p10.knn).",
166
+ "Prepare train/test split and fit the chosen classifier.",
167
+ "Evaluate predictions with confusion matrix and classification metrics.",
168
+ ],
169
+ code=_COMBINED_CODE,
170
+ notes="Select an alternative explicitly via p10.svm or p10.knn.",
171
+ references=["https://www.kaggle.com/datasets/balaka18/email-pam-classification-dataset-csv"],
172
+ alternatives={"svm": p_svm, "knn": p_knn},
173
+ ),
174
+ )
175
+ register_alias("aidsbd", p_svm, "svm", "spam")
176
+ register_alias("aidsbd", p_knn, "knn")
pamdays/aidsbd/p11.py ADDED
@@ -0,0 +1,79 @@
1
+ """pamdays.aidsbd.p11 - K-Means Clustering with Elbow Method"""
2
+
3
+ from pamdays.core import Practical
4
+ from pamdays.registry import register
5
+
6
+ _CODE = r'''\
7
+ import os
8
+ import sys
9
+
10
+ try:
11
+ import pandas as pd
12
+ from sklearn.cluster import KMeans
13
+ from sklearn.preprocessing import StandardScaler
14
+ except ImportError as e:
15
+ print(f"Missing dependency: {e.name}. Install with: pip install pandas scikit-learn")
16
+ sys.exit(1)
17
+
18
+ print("Dataset: sample-sales-data (https://www.kaggle.com/datasets/kyanyoga/sample-sales-data) or any numeric CSV.")
19
+ path = input("Enter CSV path (or press Enter for built-in Iris numeric features): ").strip()
20
+ if path:
21
+ if not os.path.exists(path):
22
+ print(f"File not found: {path}")
23
+ sys.exit(1)
24
+ X = pd.read_csv(path, encoding="latin1").select_dtypes(include="number").dropna()
25
+ else:
26
+ from sklearn.datasets import load_iris
27
+ X = load_iris().data
28
+
29
+ X_scaled = StandardScaler().fit_transform(X)
30
+ max_k = int(input("Enter max k for Elbow Method (e.g. 8): "))
31
+
32
+ wcss = []
33
+ for k in range(1, max_k + 1):
34
+ km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X_scaled)
35
+ wcss.append(km.inertia_)
36
+ print(f"k={k}: WCSS={km.inertia_:.2f}")
37
+
38
+ try:
39
+ import matplotlib.pyplot as plt
40
+ plt.plot(range(1, max_k + 1), wcss, marker="o")
41
+ plt.xlabel("Number of Clusters (k)")
42
+ plt.ylabel("WCSS (Inertia)")
43
+ plt.title("Elbow Method for Optimal k")
44
+ plt.show()
45
+ except ImportError:
46
+ print("Install matplotlib to view the Elbow plot.")
47
+
48
+ chosen_k = int(input("Enter optimal k from elbow curve: "))
49
+ model = KMeans(n_clusters=chosen_k, n_init=10, random_state=42).fit(X_scaled)
50
+ labels = pd.Series(model.labels_)
51
+ print("\nCluster Sizes:\n", labels.value_counts().sort_index())
52
+ print("\nCluster Centroids (standardized):\n", model.cluster_centers_)
53
+ '''
54
+
55
+ practical = register(
56
+ "aidsbd",
57
+ Practical(
58
+ number=11,
59
+ title="Implement K-Means clustering on a dataset using the Elbow Method",
60
+ concept="kmeans",
61
+ subject="aidsbd",
62
+ language="python",
63
+ runnable=True,
64
+ aim="Group unlabeled data using K-Means clustering and choose optimal cluster count k via the Elbow Method.",
65
+ problem_statement="Implement K-Means clustering on a dataset. Determine the number of clusters using the elbow method.",
66
+ algorithm=[
67
+ "Load numeric columns from the CSV dataset (or fallback Iris features) and standardize them.",
68
+ "Run K-Means for k = 1 to max_k and record WCSS (inertia) for each k.",
69
+ "Plot WCSS vs k to identify the elbow point where inertia reduction slows.",
70
+ "Fit final K-Means with chosen k and print cluster sizes and centroids.",
71
+ ],
72
+ code=_CODE,
73
+ sample_input="\n8\n3",
74
+ sample_output="WCSS values for k=1..8, cluster sizes, and cluster centroids.",
75
+ time_complexity="O(N * K * D * I) where N=samples, K=clusters, D=features, I=iterations.",
76
+ space_complexity="O(N * D + K * D) for data and centroids.",
77
+ references=["https://www.kaggle.com/datasets/kyanyoga/sample-sales-data"],
78
+ ),
79
+ )
pamdays/aidsbd/p2.py ADDED
@@ -0,0 +1,93 @@
1
+ """pamdays.aidsbd.p2 - MiniMax Algorithm for Tic-Tac-Toe"""
2
+
3
+ from pamdays.core import Practical
4
+ from pamdays.registry import register
5
+
6
+ _CODE = '''\
7
+ board = [" "] * 9
8
+
9
+ def show():
10
+ for i in range(0, 9, 3):
11
+ print(" | ".join(board[i:i+3]))
12
+ if i < 6:
13
+ print("--+---+--")
14
+
15
+ def winner(b):
16
+ wins = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
17
+ for x, y, z in wins:
18
+ if b[x] == b[y] == b[z] != " ":
19
+ return b[x]
20
+ return "Draw" if " " not in b else None
21
+
22
+ def minimax(b, is_max):
23
+ w = winner(b)
24
+ if w == "O":
25
+ return 1
26
+ if w == "X":
27
+ return -1
28
+ if w == "Draw":
29
+ return 0
30
+ best = -2 if is_max else 2
31
+ for i in range(9):
32
+ if b[i] == " ":
33
+ b[i] = "O" if is_max else "X"
34
+ score = minimax(b, not is_max)
35
+ b[i] = " "
36
+ best = max(best, score) if is_max else min(best, score)
37
+ return best
38
+
39
+ def best_move():
40
+ move, best = -1, -2
41
+ for i in range(9):
42
+ if board[i] == " ":
43
+ board[i] = "O"
44
+ score = minimax(board, False)
45
+ board[i] = " "
46
+ if score > best:
47
+ best, move = score, i
48
+ return move
49
+
50
+ while True:
51
+ show()
52
+ pos = int(input("Enter your move (1-9): ")) - 1
53
+ if not (0 <= pos < 9) or board[pos] != " ":
54
+ print("Invalid move, try again.")
55
+ continue
56
+ board[pos] = "X"
57
+ if winner(board):
58
+ break
59
+ board[best_move()] = "O"
60
+ if winner(board):
61
+ break
62
+
63
+ show()
64
+ res = winner(board)
65
+ print("Result:", "Draw!" if res == "Draw" else f"{res} wins!")
66
+ '''
67
+
68
+ practical = register(
69
+ "aidsbd",
70
+ Practical(
71
+ number=2,
72
+ title="Implement MiniMax algorithm for Tic-Tac-Toe game",
73
+ concept="minimax",
74
+ subject="aidsbd",
75
+ language="python",
76
+ runnable=True,
77
+ aim="Implement the MiniMax adversarial search algorithm for human vs AI Tic-Tac-Toe.",
78
+ problem_statement="Implement MiniMax algorithm for Tic-Tac-Toe game.",
79
+ algorithm=[
80
+ "Represent the 3x3 Tic-Tac-Toe board as a 9-element list.",
81
+ "Define terminal state evaluation: +1 for AI ('O') win, -1 for Human ('X') win, 0 for draw.",
82
+ "In minimax(board, is_max), recursively try every empty cell for the current player.",
83
+ "Maximizing player chooses the move with maximum score; minimizing player chooses minimum score.",
84
+ "Alternate turns between human input (1-9) and AI best_move() until win or draw.",
85
+ ],
86
+ code=_CODE,
87
+ sample_input="5\n1\n2\n6\n7",
88
+ sample_output="Result: Draw! (or O wins!)",
89
+ time_complexity="O(b^m) where b <= 9 and m <= 9 (at most 9! game states).",
90
+ space_complexity="O(m) recursion stack depth (m <= 9).",
91
+ notes="Human plays 'X' and AI plays 'O' optimally using MiniMax.",
92
+ ),
93
+ )
pamdays/aidsbd/p3.py ADDED
@@ -0,0 +1,113 @@
1
+ """pamdays.aidsbd.p3 - Alpha-Beta Tree Search"""
2
+
3
+ from pamdays.core import Practical
4
+ from pamdays.registry import register
5
+
6
+ _CODE = '''\
7
+ board = [" "] * 9
8
+ pruned = 0
9
+
10
+ def show():
11
+ for i in range(0, 9, 3):
12
+ print(" | ".join(board[i:i+3]))
13
+ if i < 6:
14
+ print("--+---+--")
15
+
16
+ def winner(b):
17
+ wins = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
18
+ for x, y, z in wins:
19
+ if b[x] == b[y] == b[z] != " ":
20
+ return b[x]
21
+ return "Draw" if " " not in b else None
22
+
23
+ def alphabeta(b, alpha, beta, is_max):
24
+ global pruned
25
+ w = winner(b)
26
+ if w == "O":
27
+ return 1
28
+ if w == "X":
29
+ return -1
30
+ if w == "Draw":
31
+ return 0
32
+ if is_max:
33
+ val = -2
34
+ for i in range(9):
35
+ if b[i] == " ":
36
+ b[i] = "O"
37
+ val = max(val, alphabeta(b, alpha, beta, False))
38
+ b[i] = " "
39
+ alpha = max(alpha, val)
40
+ if beta <= alpha:
41
+ pruned += 1
42
+ break
43
+ return val
44
+ else:
45
+ val = 2
46
+ for i in range(9):
47
+ if b[i] == " ":
48
+ b[i] = "X"
49
+ val = min(val, alphabeta(b, alpha, beta, True))
50
+ b[i] = " "
51
+ beta = min(beta, val)
52
+ if beta <= alpha:
53
+ pruned += 1
54
+ break
55
+ return val
56
+
57
+ def best_move():
58
+ global pruned
59
+ pruned = 0
60
+ move, best = -1, -2
61
+ for i in range(9):
62
+ if board[i] == " ":
63
+ board[i] = "O"
64
+ score = alphabeta(board, -2, 2, False)
65
+ board[i] = " "
66
+ if score > best:
67
+ best, move = score, i
68
+ print(f"AI chose {move + 1} (branches pruned: {pruned})")
69
+ return move
70
+
71
+ while True:
72
+ show()
73
+ pos = int(input("Enter your move (1-9): ")) - 1
74
+ if not (0 <= pos < 9) or board[pos] != " ":
75
+ print("Invalid move, try again.")
76
+ continue
77
+ board[pos] = "X"
78
+ if winner(board):
79
+ break
80
+ board[best_move()] = "O"
81
+ if winner(board):
82
+ break
83
+
84
+ show()
85
+ res = winner(board)
86
+ print("Result:", "Draw!" if res == "Draw" else f"{res} wins!")
87
+ '''
88
+
89
+ practical = register(
90
+ "aidsbd",
91
+ Practical(
92
+ number=3,
93
+ title="Implement Alpha-Beta Tree search for any game search problem",
94
+ concept="alphabeta",
95
+ subject="aidsbd",
96
+ language="python",
97
+ runnable=True,
98
+ aim="Optimize MiniMax game tree search using Alpha-Beta pruning.",
99
+ problem_statement="Implement Alpha-Beta Tree search for any game search problem.",
100
+ algorithm=[
101
+ "Maintain alpha (best score guaranteed for MAX) and beta (best score guaranteed for MIN).",
102
+ "At MAX nodes, update alpha = max(alpha, val); at MIN nodes, update beta = min(beta, val).",
103
+ "Whenever beta <= alpha, prune remaining sibling branches (break out of the loop).",
104
+ "Play Tic-Tac-Toe and display the count of pruned branches per AI move.",
105
+ ],
106
+ code=_CODE,
107
+ sample_input="5\n1\n2\n6\n7",
108
+ sample_output="AI chose 1 (branches pruned: ...)\nResult: Draw!",
109
+ time_complexity="O(b^(d/2)) best case with optimal move ordering; O(b^d) worst case.",
110
+ space_complexity="O(d) recursion stack depth.",
111
+ notes="Demonstrates Alpha-Beta pruning on Tic-Tac-Toe and counts pruned branches.",
112
+ ),
113
+ )