skl-core 1.0.0__tar.gz
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.
- skl_core-1.0.0/PKG-INFO +92 -0
- skl_core-1.0.0/README.md +79 -0
- skl_core-1.0.0/pyproject.toml +38 -0
- skl_core-1.0.0/setup.cfg +4 -0
- skl_core-1.0.0/src/skl/__init__.py +62 -0
- skl_core-1.0.0/src/skl/__main__.py +4 -0
- skl_core-1.0.0/src/skl/cli.py +173 -0
- skl_core-1.0.0/src/skl/modules/__init__.py +14 -0
- skl_core-1.0.0/src/skl/modules/p01_setup.py +6 -0
- skl_core-1.0.0/src/skl/modules/p02_bfs_dfs.py +23 -0
- skl_core-1.0.0/src/skl/modules/p03_astar.py +21 -0
- skl_core-1.0.0/src/skl/modules/p04_csp.py +22 -0
- skl_core-1.0.0/src/skl/modules/p05_rules.py +11 -0
- skl_core-1.0.0/src/skl/modules/p06_minimax.py +22 -0
- skl_core-1.0.0/src/skl/modules/p07_preprocess.py +14 -0
- skl_core-1.0.0/src/skl/modules/p08_nlp.py +13 -0
- skl_core-1.0.0/src/skl/modules/p09_bayes.py +17 -0
- skl_core-1.0.0/src/skl/modules/p10_regression.py +11 -0
- skl_core-1.0.0/src/skl/modules/p11_4queens.py +22 -0
- skl_core-1.0.0/src/skl/modules/p12_8puzzle.py +27 -0
- skl_core-1.0.0/src/skl/modules/p13_inventory.py +27 -0
- skl_core-1.0.0/src/skl/registry.py +448 -0
- skl_core-1.0.0/src/skl_core.egg-info/PKG-INFO +92 -0
- skl_core-1.0.0/src/skl_core.egg-info/SOURCES.txt +25 -0
- skl_core-1.0.0/src/skl_core.egg-info/dependency_links.txt +1 -0
- skl_core-1.0.0/src/skl_core.egg-info/entry_points.txt +3 -0
- skl_core-1.0.0/src/skl_core.egg-info/top_level.txt +1 -0
skl_core-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: skl-core
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Standard Knowledge & Algorithm Library: search, CSP, game theory, heuristics, and utilities.
|
|
5
|
+
Author: SKL Developers
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: algorithms,search,bfs,dfs,astar,minimax,csp,backtracking,puzzle,utilities
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
11
|
+
Requires-Python: >=3.7
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# SKL (Standard Knowledge & Algorithm Library)
|
|
15
|
+
|
|
16
|
+
A lightweight Python library providing clean, minimal implementations of standard computer science algorithms, search heuristics, constraint satisfaction problems, and data utilities.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## 📦 Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install skl
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## 🚀 CLI Usage
|
|
29
|
+
|
|
30
|
+
Access algorithms and code snippets directly from the terminal:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
# Interactive menu
|
|
34
|
+
skl
|
|
35
|
+
|
|
36
|
+
# Print & copy 4-Queens solver
|
|
37
|
+
skl 4queen
|
|
38
|
+
|
|
39
|
+
# Print & copy 8-Puzzle solver
|
|
40
|
+
skl 8puzzle
|
|
41
|
+
|
|
42
|
+
# Print & copy Inventory management
|
|
43
|
+
skl lib
|
|
44
|
+
|
|
45
|
+
# Graph traversal (BFS & DFS)
|
|
46
|
+
skl bfs
|
|
47
|
+
|
|
48
|
+
# Pathfinding (A* search)
|
|
49
|
+
skl astar
|
|
50
|
+
|
|
51
|
+
# Dump all algorithm scripts to the current directory
|
|
52
|
+
skl saveall
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## ⚡ Direct Code Execution & Clipboard
|
|
58
|
+
|
|
59
|
+
- **Automatic Clipboard Copy**: Every query automatically copies the compact code directly to your system clipboard (press `Ctrl + V` to paste into any editor).
|
|
60
|
+
- **Run on Demand**:
|
|
61
|
+
```bash
|
|
62
|
+
skl 4queen --run
|
|
63
|
+
skl 8puzzle --run
|
|
64
|
+
skl astar --run
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## 🐍 Python Import API
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import skl
|
|
73
|
+
|
|
74
|
+
# Execute algorithm
|
|
75
|
+
skl.run("4queen")
|
|
76
|
+
skl.run("8puzzle")
|
|
77
|
+
|
|
78
|
+
# Retrieve raw code string
|
|
79
|
+
snippet = skl.code("lib")
|
|
80
|
+
print(snippet)
|
|
81
|
+
|
|
82
|
+
# Copy to clipboard
|
|
83
|
+
skl.copy("astar")
|
|
84
|
+
|
|
85
|
+
# Save all files locally
|
|
86
|
+
skl.save_all("./scripts")
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## 📄 License
|
|
92
|
+
MIT
|
skl_core-1.0.0/README.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# SKL (Standard Knowledge & Algorithm Library)
|
|
2
|
+
|
|
3
|
+
A lightweight Python library providing clean, minimal implementations of standard computer science algorithms, search heuristics, constraint satisfaction problems, and data utilities.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 📦 Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install skl
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## 🚀 CLI Usage
|
|
16
|
+
|
|
17
|
+
Access algorithms and code snippets directly from the terminal:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
# Interactive menu
|
|
21
|
+
skl
|
|
22
|
+
|
|
23
|
+
# Print & copy 4-Queens solver
|
|
24
|
+
skl 4queen
|
|
25
|
+
|
|
26
|
+
# Print & copy 8-Puzzle solver
|
|
27
|
+
skl 8puzzle
|
|
28
|
+
|
|
29
|
+
# Print & copy Inventory management
|
|
30
|
+
skl lib
|
|
31
|
+
|
|
32
|
+
# Graph traversal (BFS & DFS)
|
|
33
|
+
skl bfs
|
|
34
|
+
|
|
35
|
+
# Pathfinding (A* search)
|
|
36
|
+
skl astar
|
|
37
|
+
|
|
38
|
+
# Dump all algorithm scripts to the current directory
|
|
39
|
+
skl saveall
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## ⚡ Direct Code Execution & Clipboard
|
|
45
|
+
|
|
46
|
+
- **Automatic Clipboard Copy**: Every query automatically copies the compact code directly to your system clipboard (press `Ctrl + V` to paste into any editor).
|
|
47
|
+
- **Run on Demand**:
|
|
48
|
+
```bash
|
|
49
|
+
skl 4queen --run
|
|
50
|
+
skl 8puzzle --run
|
|
51
|
+
skl astar --run
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## 🐍 Python Import API
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
import skl
|
|
60
|
+
|
|
61
|
+
# Execute algorithm
|
|
62
|
+
skl.run("4queen")
|
|
63
|
+
skl.run("8puzzle")
|
|
64
|
+
|
|
65
|
+
# Retrieve raw code string
|
|
66
|
+
snippet = skl.code("lib")
|
|
67
|
+
print(snippet)
|
|
68
|
+
|
|
69
|
+
# Copy to clipboard
|
|
70
|
+
skl.copy("astar")
|
|
71
|
+
|
|
72
|
+
# Save all files locally
|
|
73
|
+
skl.save_all("./scripts")
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
## 📄 License
|
|
79
|
+
MIT
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "skl-core"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Standard Knowledge & Algorithm Library: search, CSP, game theory, heuristics, and utilities."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.7"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "SKL Developers" }
|
|
14
|
+
]
|
|
15
|
+
keywords = [
|
|
16
|
+
"algorithms",
|
|
17
|
+
"search",
|
|
18
|
+
"bfs",
|
|
19
|
+
"dfs",
|
|
20
|
+
"astar",
|
|
21
|
+
"minimax",
|
|
22
|
+
"csp",
|
|
23
|
+
"backtracking",
|
|
24
|
+
"puzzle",
|
|
25
|
+
"utilities"
|
|
26
|
+
]
|
|
27
|
+
classifiers = [
|
|
28
|
+
"Programming Language :: Python :: 3",
|
|
29
|
+
"Operating System :: OS Independent",
|
|
30
|
+
"Topic :: Software Development :: Libraries :: Python Modules"
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.scripts]
|
|
34
|
+
skl = "skl.cli:main"
|
|
35
|
+
sk-lib = "skl.cli:main"
|
|
36
|
+
|
|
37
|
+
[tool.setuptools.packages.find]
|
|
38
|
+
where = ["src"]
|
skl_core-1.0.0/setup.cfg
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""SKL - Standard Knowledge & Algorithm Library
|
|
2
|
+
"""
|
|
3
|
+
|
|
4
|
+
from .registry import MODULES
|
|
5
|
+
from .cli import find_module, copy_to_clipboard, save_all_files
|
|
6
|
+
|
|
7
|
+
__version__ = "1.0.0"
|
|
8
|
+
|
|
9
|
+
def get(query):
|
|
10
|
+
return find_module(query)
|
|
11
|
+
|
|
12
|
+
def code(query) -> str:
|
|
13
|
+
mod = find_module(query)
|
|
14
|
+
if not mod:
|
|
15
|
+
raise ValueError(f"Module '{query}' not found.")
|
|
16
|
+
return mod["code"]
|
|
17
|
+
|
|
18
|
+
def show(query):
|
|
19
|
+
mod = find_module(query)
|
|
20
|
+
if not mod:
|
|
21
|
+
print(f"[!] Module '{query}' not found.")
|
|
22
|
+
return
|
|
23
|
+
print("=" * 60)
|
|
24
|
+
print(f"Program {mod['id']:02d}: {mod['title']}")
|
|
25
|
+
print("=" * 60)
|
|
26
|
+
print(f"Description:\n {mod['desc']}\n")
|
|
27
|
+
print("CODE:")
|
|
28
|
+
print("-" * 40)
|
|
29
|
+
print(mod["code"])
|
|
30
|
+
print("-" * 40)
|
|
31
|
+
print("EXPECTED OUTPUT:")
|
|
32
|
+
print(mod["output"])
|
|
33
|
+
print("=" * 60)
|
|
34
|
+
|
|
35
|
+
def run(query):
|
|
36
|
+
mod = find_module(query)
|
|
37
|
+
if not mod:
|
|
38
|
+
print(f"[!] Module '{query}' not found.")
|
|
39
|
+
return
|
|
40
|
+
print(f"[Executing {mod['id']:02d}: {mod['title']}...]")
|
|
41
|
+
exec(mod["code"], {"__name__": "__main__"})
|
|
42
|
+
|
|
43
|
+
def copy(query) -> bool:
|
|
44
|
+
mod = find_module(query)
|
|
45
|
+
if not mod:
|
|
46
|
+
print(f"[!] Module '{query}' not found.")
|
|
47
|
+
return False
|
|
48
|
+
return copy_to_clipboard(mod["code"])
|
|
49
|
+
|
|
50
|
+
def save_all(target_dir="."):
|
|
51
|
+
save_all_files(target_dir)
|
|
52
|
+
|
|
53
|
+
__all__ = [
|
|
54
|
+
"MODULES",
|
|
55
|
+
"get",
|
|
56
|
+
"code",
|
|
57
|
+
"show",
|
|
58
|
+
"run",
|
|
59
|
+
"copy",
|
|
60
|
+
"save_all",
|
|
61
|
+
"__version__"
|
|
62
|
+
]
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import subprocess
|
|
3
|
+
import os
|
|
4
|
+
from .registry import MODULES
|
|
5
|
+
|
|
6
|
+
def copy_to_clipboard(text: str) -> bool:
|
|
7
|
+
try:
|
|
8
|
+
if sys.platform == "win32":
|
|
9
|
+
proc = subprocess.Popen(["clip"], stdin=subprocess.PIPE, shell=True)
|
|
10
|
+
proc.communicate(text.encode("utf-8"))
|
|
11
|
+
return True
|
|
12
|
+
elif sys.platform == "darwin":
|
|
13
|
+
proc = subprocess.Popen(["pbcopy"], stdin=subprocess.PIPE)
|
|
14
|
+
proc.communicate(text.encode("utf-8"))
|
|
15
|
+
return True
|
|
16
|
+
else:
|
|
17
|
+
proc = subprocess.Popen(["xclip", "-selection", "clipboard"], stdin=subprocess.PIPE)
|
|
18
|
+
proc.communicate(text.encode("utf-8"))
|
|
19
|
+
return True
|
|
20
|
+
except Exception:
|
|
21
|
+
return False
|
|
22
|
+
|
|
23
|
+
def find_module(query):
|
|
24
|
+
query_str = str(query).strip().lower()
|
|
25
|
+
if query_str.isdigit():
|
|
26
|
+
mid = int(query_str)
|
|
27
|
+
if mid in MODULES:
|
|
28
|
+
return MODULES[mid]
|
|
29
|
+
|
|
30
|
+
aliases = {
|
|
31
|
+
"setup": 1, "install": 1, "env": 1,
|
|
32
|
+
"bfs": 2, "dfs": 2, "graph": 2,
|
|
33
|
+
"astar": 3, "a*": 3, "path": 3,
|
|
34
|
+
"csp": 4, "map": 4, "coloring": 4,
|
|
35
|
+
"rules": 5, "expert": 5, "diag": 5, "medical": 5,
|
|
36
|
+
"minimax": 6, "ttt": 6, "tic": 6, "game": 6,
|
|
37
|
+
"preprocess": 7, "pandas": 7, "data": 7, "clean": 7,
|
|
38
|
+
"nlp": 8, "token": 8, "nltk": 8, "words": 8,
|
|
39
|
+
"bayes": 9, "naive": 9, "spam": 9, "classify": 9,
|
|
40
|
+
"regression": 10, "linear": 10, "ols": 10, "fit": 10,
|
|
41
|
+
"4queen": 11, "4queens": 11, "queen": 11, "queens": 11,
|
|
42
|
+
"8puzzle": 12, "puzzle": 12, "eight": 12, "tiles": 12,
|
|
43
|
+
"lib": 13, "library": 13, "inventory": 13, "catalog": 13
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
clean_q = query_str.replace("-", "").replace("_", "").replace(" ", "")
|
|
47
|
+
if clean_q in aliases:
|
|
48
|
+
return MODULES[aliases[clean_q]]
|
|
49
|
+
|
|
50
|
+
for mod in MODULES.values():
|
|
51
|
+
if clean_q in mod["key"] or clean_q in mod["title"].lower().replace(" ", ""):
|
|
52
|
+
return mod
|
|
53
|
+
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
def save_all_files(target_dir="."):
|
|
57
|
+
os.makedirs(target_dir, exist_ok=True)
|
|
58
|
+
for mid, data in MODULES.items():
|
|
59
|
+
fname = f"p{mid:02d}_{data['key']}.py"
|
|
60
|
+
path = os.path.join(target_dir, fname)
|
|
61
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
62
|
+
f.write(f"# Module {mid:02d}: {data['title']}\n\n")
|
|
63
|
+
f.write(data["code"] + "\n")
|
|
64
|
+
print(f"\n[+] Saved all {len(MODULES)} program files in '{os.path.abspath(target_dir)}'.")
|
|
65
|
+
|
|
66
|
+
def display_menu():
|
|
67
|
+
print("=" * 60)
|
|
68
|
+
print(" SKL Toolkit (v1.0.0) ")
|
|
69
|
+
print("=" * 60)
|
|
70
|
+
for mid, data in MODULES.items():
|
|
71
|
+
print(f" {mid:2d}. {data['title']}")
|
|
72
|
+
print("-" * 60)
|
|
73
|
+
print(" A. Save all programs as .py files in current directory")
|
|
74
|
+
print(" Q. Quit")
|
|
75
|
+
print("=" * 60)
|
|
76
|
+
|
|
77
|
+
def main():
|
|
78
|
+
args = sys.argv[1:]
|
|
79
|
+
|
|
80
|
+
if not args:
|
|
81
|
+
while True:
|
|
82
|
+
display_menu()
|
|
83
|
+
choice = input("\nEnter selection (1-13), 'A' to save all, or 'Q' to quit: ").strip().lower()
|
|
84
|
+
if choice == "q":
|
|
85
|
+
break
|
|
86
|
+
elif choice == "a":
|
|
87
|
+
save_all_files()
|
|
88
|
+
break
|
|
89
|
+
|
|
90
|
+
mod = find_module(choice)
|
|
91
|
+
if not mod:
|
|
92
|
+
print("[!] Invalid selection.")
|
|
93
|
+
continue
|
|
94
|
+
|
|
95
|
+
print("\n" + "=" * 60)
|
|
96
|
+
print(f"Program {mod['id']:02d}: {mod['title']}")
|
|
97
|
+
print("=" * 60)
|
|
98
|
+
print(f"Description:\n {mod['desc']}\n")
|
|
99
|
+
print("CODE:")
|
|
100
|
+
print("-" * 40)
|
|
101
|
+
print(mod["code"])
|
|
102
|
+
print("-" * 40)
|
|
103
|
+
print("EXPECTED OUTPUT:")
|
|
104
|
+
print(mod["output"])
|
|
105
|
+
print("=" * 60)
|
|
106
|
+
|
|
107
|
+
if copy_to_clipboard(mod["code"]):
|
|
108
|
+
print("[*] Code copied to clipboard! (Ctrl + V to paste)")
|
|
109
|
+
|
|
110
|
+
sub = input("\nExecute this program now? (y/n) [n]: ").strip().lower()
|
|
111
|
+
if sub == "y":
|
|
112
|
+
print("\n[Executing...]")
|
|
113
|
+
print("-" * 40)
|
|
114
|
+
try:
|
|
115
|
+
exec(mod["code"], {"__name__": "__main__"})
|
|
116
|
+
except Exception as e:
|
|
117
|
+
print(f"Notice: {e}")
|
|
118
|
+
print("-" * 40)
|
|
119
|
+
input("\nPress Enter to return to menu...")
|
|
120
|
+
return
|
|
121
|
+
|
|
122
|
+
if args[0] in ["--save-all", "-sa", "saveall", "dump"]:
|
|
123
|
+
save_all_files()
|
|
124
|
+
return
|
|
125
|
+
|
|
126
|
+
mod = find_module(args[0])
|
|
127
|
+
if not mod:
|
|
128
|
+
print(f"[!] Unknown target '{args[0]}'.")
|
|
129
|
+
print("Usage: skl [1-13 | 4queen | 8puzzle | lib | saveall]")
|
|
130
|
+
return
|
|
131
|
+
|
|
132
|
+
if "--code" in args or "-c" in args:
|
|
133
|
+
print(mod["code"])
|
|
134
|
+
return
|
|
135
|
+
|
|
136
|
+
if "--save" in args or "-s" in args:
|
|
137
|
+
fname = f"p{mod['id']:02d}_{mod['key']}.py"
|
|
138
|
+
with open(fname, "w", encoding="utf-8") as f:
|
|
139
|
+
f.write(mod["code"] + "\n")
|
|
140
|
+
print(f"[+] Saved to {fname}")
|
|
141
|
+
return
|
|
142
|
+
|
|
143
|
+
if "--copy" in args:
|
|
144
|
+
if copy_to_clipboard(mod["code"]):
|
|
145
|
+
print(f"[+] Code copied to clipboard!")
|
|
146
|
+
else:
|
|
147
|
+
print("[!] Clipboard copy failed.")
|
|
148
|
+
return
|
|
149
|
+
|
|
150
|
+
if "--run" in args or "-r" in args:
|
|
151
|
+
print(f"[Executing {mod['id']:02d}: {mod['title']}...]")
|
|
152
|
+
try:
|
|
153
|
+
exec(mod["code"], {"__name__": "__main__"})
|
|
154
|
+
except Exception as e:
|
|
155
|
+
print(f"Error: {e}")
|
|
156
|
+
return
|
|
157
|
+
|
|
158
|
+
print("=" * 60)
|
|
159
|
+
print(f"Program {mod['id']:02d}: {mod['title']}")
|
|
160
|
+
print("=" * 60)
|
|
161
|
+
print(f"Description:\n {mod['desc']}\n")
|
|
162
|
+
print("CODE:")
|
|
163
|
+
print("-" * 40)
|
|
164
|
+
print(mod["code"])
|
|
165
|
+
print("-" * 40)
|
|
166
|
+
print("EXPECTED OUTPUT:")
|
|
167
|
+
print(mod["output"])
|
|
168
|
+
print("=" * 60)
|
|
169
|
+
if copy_to_clipboard(mod["code"]):
|
|
170
|
+
print("[*] Code copied to clipboard! (Ctrl + V to paste)")
|
|
171
|
+
|
|
172
|
+
if __name__ == "__main__":
|
|
173
|
+
main()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# SKL Modules Package
|
|
2
|
+
from . import p01_setup
|
|
3
|
+
from . import p02_bfs_dfs
|
|
4
|
+
from . import p03_astar
|
|
5
|
+
from . import p04_csp
|
|
6
|
+
from . import p05_rules
|
|
7
|
+
from . import p06_minimax
|
|
8
|
+
from . import p07_preprocess
|
|
9
|
+
from . import p08_nlp
|
|
10
|
+
from . import p09_bayes
|
|
11
|
+
from . import p10_regression
|
|
12
|
+
from . import p11_4queens
|
|
13
|
+
from . import p12_8puzzle
|
|
14
|
+
from . import p13_inventory
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Program 02: Graph Traversal (BFS & DFS)
|
|
2
|
+
|
|
3
|
+
graph = {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': []}
|
|
4
|
+
|
|
5
|
+
def bfs(s):
|
|
6
|
+
q, v = [s], set()
|
|
7
|
+
for u in q:
|
|
8
|
+
if u not in v:
|
|
9
|
+
print(u, end=' ')
|
|
10
|
+
v.add(u)
|
|
11
|
+
q += graph[u]
|
|
12
|
+
|
|
13
|
+
def dfs(u, v=None):
|
|
14
|
+
if v is None: v = set()
|
|
15
|
+
if u not in v:
|
|
16
|
+
print(u, end=' ')
|
|
17
|
+
v.add(u)
|
|
18
|
+
for n in graph[u]: dfs(n, v)
|
|
19
|
+
|
|
20
|
+
print("BFS Traversal:")
|
|
21
|
+
bfs('A')
|
|
22
|
+
print("\nDFS Traversal:")
|
|
23
|
+
dfs('A')
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Program 03: A* Pathfinding Algorithm
|
|
2
|
+
|
|
3
|
+
import heapq
|
|
4
|
+
|
|
5
|
+
graph = {'A': [('B', 1), ('C', 3)], 'B': [('D', 3), ('E', 1)], 'C': [('F', 2)],
|
|
6
|
+
'D': [('G', 2)], 'E': [('G', 4)], 'F': [('G', 1)], 'G': []}
|
|
7
|
+
h = {'A': 6, 'B': 4, 'C': 4, 'D': 2, 'E': 3, 'F': 1, 'G': 0}
|
|
8
|
+
|
|
9
|
+
def a_star(start, goal):
|
|
10
|
+
q, visited = [(h[start], 0, start, [start])], set()
|
|
11
|
+
while q:
|
|
12
|
+
f, g, u, path = heapq.heappop(q)
|
|
13
|
+
if u == goal: return path, g
|
|
14
|
+
if u not in visited:
|
|
15
|
+
visited.add(u)
|
|
16
|
+
for n, cost in graph[u]:
|
|
17
|
+
heapq.heappush(q, (g + cost + h[n], g + cost, n, path + [n]))
|
|
18
|
+
|
|
19
|
+
path, cost = a_star('A', 'G')
|
|
20
|
+
print("Shortest Path:", path)
|
|
21
|
+
print("Total Cost:", cost)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Program 04: Constraint Satisfaction Problem (Map Coloring)
|
|
2
|
+
|
|
3
|
+
colors = ['Red', 'Green', 'Blue']
|
|
4
|
+
regions = ['A', 'B', 'C', 'D']
|
|
5
|
+
neighbors = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], 'C': ['A', 'B', 'D'], 'D': ['B', 'C']}
|
|
6
|
+
assignment = {}
|
|
7
|
+
|
|
8
|
+
def solve(i=0):
|
|
9
|
+
if i == len(regions): return True
|
|
10
|
+
r = regions[i]
|
|
11
|
+
for c in colors:
|
|
12
|
+
if all(assignment.get(n) != c for n in neighbors[r]):
|
|
13
|
+
assignment[r] = c
|
|
14
|
+
if solve(i + 1): return True
|
|
15
|
+
del assignment[r]
|
|
16
|
+
return False
|
|
17
|
+
|
|
18
|
+
if solve():
|
|
19
|
+
print("Solution:")
|
|
20
|
+
for r, c in assignment.items(): print(r, "=", c)
|
|
21
|
+
else:
|
|
22
|
+
print("No solution exists")
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Program 05: Production Rule Inference System
|
|
2
|
+
|
|
3
|
+
print("DIAGNOSTIC EXPERT SYSTEM\n" + "-" * 24)
|
|
4
|
+
ask = lambda s: input(f"Presence of {s}? (yes/no): ").strip().lower() == "yes"
|
|
5
|
+
fever, cough, cold, headache = ask("fever"), ask("cough"), ask("cold"), ask("headache")
|
|
6
|
+
|
|
7
|
+
if fever and cough: print("Diagnosis: Flu")
|
|
8
|
+
elif fever and headache: print("Diagnosis: Viral Fever")
|
|
9
|
+
elif cold and cough: print("Diagnosis: Common Cold")
|
|
10
|
+
elif headache: print("Diagnosis: Headache")
|
|
11
|
+
else: print("Diagnosis: Inconclusive / Undetermined")
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Program 06: Minimax Decision Strategy
|
|
2
|
+
|
|
3
|
+
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)]
|
|
4
|
+
|
|
5
|
+
def check_winner(b):
|
|
6
|
+
for x, y, z in wins:
|
|
7
|
+
if b[x] != ' ' and b[x] == b[y] == b[z]: return 1 if b[x] == 'X' else -1
|
|
8
|
+
return 0 if ' ' not in b else None
|
|
9
|
+
|
|
10
|
+
def minimax(b, is_max):
|
|
11
|
+
w = check_winner(b)
|
|
12
|
+
if w is not None: return w
|
|
13
|
+
scores = [minimax(b[:i] + ('X' if is_max else 'O') + b[i+1:], not is_max)
|
|
14
|
+
for i, c in enumerate(b) if c == ' ']
|
|
15
|
+
return max(scores) if is_max else min(scores)
|
|
16
|
+
|
|
17
|
+
def best_move(b):
|
|
18
|
+
return max((i for i, c in enumerate(b) if c == ' '),
|
|
19
|
+
key=lambda i: minimax(b[:i] + 'X' + b[i+1:], False))
|
|
20
|
+
|
|
21
|
+
board = ['O','X','O','X','X',' ',' ',' ','O']
|
|
22
|
+
print("Best move for X is position:", best_move(board) + 1)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Program 07: Tabular Data Preprocessing & Cleaning
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
data = {'Name': ['Arun','Bala','Cathy','David','Eva'], 'Age': [20,21,None,22,20], 'Marks': [85,90,78,None,88]}
|
|
6
|
+
df = pd.DataFrame(data)
|
|
7
|
+
print("Original Data:\n", df)
|
|
8
|
+
print("\nMissing Values:\n", df.isnull().sum())
|
|
9
|
+
df['Age'] = df['Age'].fillna(df['Age'].mean())
|
|
10
|
+
df['Marks'] = df['Marks'].fillna(df['Marks'].mean())
|
|
11
|
+
df = df.drop_duplicates()
|
|
12
|
+
print("\nAfter Preprocessing:\n", df)
|
|
13
|
+
df.to_csv("cleaned_data.csv", index=False)
|
|
14
|
+
print("\nCleaned dataset saved successfully.")
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Program 08: Text Tokenization & Lexical Analysis
|
|
2
|
+
|
|
3
|
+
import nltk
|
|
4
|
+
from nltk.tokenize import word_tokenize
|
|
5
|
+
from collections import Counter
|
|
6
|
+
|
|
7
|
+
nltk.download('punkt', quiet=True)
|
|
8
|
+
text = "Artificial intelligence is powerful. Artificial intelligence is useful."
|
|
9
|
+
words = [w for w in word_tokenize(text.lower()) if w.isalpha()]
|
|
10
|
+
print("Tokens:\n", words)
|
|
11
|
+
print("\nWord Frequency:")
|
|
12
|
+
for word, count in Counter(words).items():
|
|
13
|
+
print(word, ":", count)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Program 09: Multinomial Naive Bayes Classifier
|
|
2
|
+
|
|
3
|
+
from sklearn.feature_extraction.text import CountVectorizer
|
|
4
|
+
from sklearn.naive_bayes import MultinomialNB
|
|
5
|
+
|
|
6
|
+
messages = ["win money now", "free lottery ticket", "claim your prize",
|
|
7
|
+
"meeting at 10 am", "project meeting tomorrow", "submit the assignment"]
|
|
8
|
+
labels = ["Spam", "Spam", "Spam", "Not Spam", "Not Spam", "Not Spam"]
|
|
9
|
+
|
|
10
|
+
vectorizer = CountVectorizer()
|
|
11
|
+
X = vectorizer.fit_transform(messages)
|
|
12
|
+
model = MultinomialNB().fit(X, labels)
|
|
13
|
+
|
|
14
|
+
test_msg = ["free money prize"]
|
|
15
|
+
pred = model.predict(vectorizer.transform(test_msg))
|
|
16
|
+
print("Message:", test_msg[0])
|
|
17
|
+
print("Prediction:", pred[0])
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Program 10: Ordinary Least Squares Linear Regression
|
|
2
|
+
|
|
3
|
+
from sklearn.linear_model import LinearRegression
|
|
4
|
+
|
|
5
|
+
hours = [[1], [2], [3], [4], [5]]
|
|
6
|
+
marks = [20, 35, 50, 65, 80]
|
|
7
|
+
model = LinearRegression().fit(hours, marks)
|
|
8
|
+
|
|
9
|
+
study_hours = [[6]]
|
|
10
|
+
print("Input Feature:", study_hours[0][0])
|
|
11
|
+
print("Predicted Output:", model.predict(study_hours)[0])
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Program 11: 4-Queens Backtracking Constraint Solver
|
|
2
|
+
|
|
3
|
+
board = [-1] * 4
|
|
4
|
+
|
|
5
|
+
def is_safe(r, c):
|
|
6
|
+
return all(board[i] != c and abs(board[i] - c) != r - i for i in range(r))
|
|
7
|
+
|
|
8
|
+
def solve(r=0):
|
|
9
|
+
if r == 4:
|
|
10
|
+
print("4-Queens Solution:")
|
|
11
|
+
for i in range(4):
|
|
12
|
+
print('. ' * board[i] + 'Q ' + '. ' * (3 - board[i]))
|
|
13
|
+
print("Column Positions:", board)
|
|
14
|
+
return True
|
|
15
|
+
for c in range(4):
|
|
16
|
+
if is_safe(r, c):
|
|
17
|
+
board[r] = c
|
|
18
|
+
if solve(r + 1): return True
|
|
19
|
+
board[r] = -1
|
|
20
|
+
return False
|
|
21
|
+
|
|
22
|
+
solve()
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Program 12: 8-Puzzle Sliding Tile State Solver
|
|
2
|
+
|
|
3
|
+
from collections import deque
|
|
4
|
+
|
|
5
|
+
adj = {0:[1,3], 1:[0,2,4], 2:[1,5], 3:[0,4,6], 4:[1,3,5,7], 5:[2,4,8], 6:[3,7], 7:[4,6,8], 8:[5,7]}
|
|
6
|
+
|
|
7
|
+
def solve_8_puzzle(start, goal=(1, 2, 3, 4, 5, 6, 7, 8, 0)):
|
|
8
|
+
q, visited = deque([(start, [start])]), {start}
|
|
9
|
+
while q:
|
|
10
|
+
s, path = q.popleft()
|
|
11
|
+
if s == goal: return path
|
|
12
|
+
z = s.index(0)
|
|
13
|
+
for n in adj[z]:
|
|
14
|
+
nxt = list(s)
|
|
15
|
+
nxt[z], nxt[n] = nxt[n], nxt[z]
|
|
16
|
+
t = tuple(nxt)
|
|
17
|
+
if t not in visited:
|
|
18
|
+
visited.add(t)
|
|
19
|
+
q.append((t, path + [t]))
|
|
20
|
+
|
|
21
|
+
start = (1, 2, 3, 0, 4, 6, 7, 5, 8)
|
|
22
|
+
path = solve_8_puzzle(start)
|
|
23
|
+
print(f"8-Puzzle Solved in {len(path) - 1} moves:\n")
|
|
24
|
+
for step, p in enumerate(path):
|
|
25
|
+
print(f"Step {step}:")
|
|
26
|
+
for i in range(0, 9, 3): print(p[i:i+3])
|
|
27
|
+
print()
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Program 13: Catalog & Inventory Management System
|
|
2
|
+
|
|
3
|
+
class Library:
|
|
4
|
+
def __init__(self, books):
|
|
5
|
+
self.books = books
|
|
6
|
+
|
|
7
|
+
def show(self):
|
|
8
|
+
print("Available items:", self.books)
|
|
9
|
+
|
|
10
|
+
def borrow(self, b):
|
|
11
|
+
if b in self.books:
|
|
12
|
+
self.books.remove(b)
|
|
13
|
+
print(f"Issued: {b}")
|
|
14
|
+
else:
|
|
15
|
+
print(f"{b} is not available")
|
|
16
|
+
|
|
17
|
+
def return_book(self, b):
|
|
18
|
+
self.books.append(b)
|
|
19
|
+
print(f"Returned: {b}")
|
|
20
|
+
|
|
21
|
+
lib = Library(["Concepts", "Basics", "Data Mining", "Machine Learning"])
|
|
22
|
+
print("CATALOG & INVENTORY SYSTEM\n" + "-" * 26)
|
|
23
|
+
lib.show()
|
|
24
|
+
lib.borrow("Concepts")
|
|
25
|
+
lib.borrow("Concepts")
|
|
26
|
+
lib.return_book("Concepts")
|
|
27
|
+
lib.show()
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
# Standard Knowledge & Algorithm Library (SKL) Registry
|
|
2
|
+
|
|
3
|
+
MODULES = {
|
|
4
|
+
1: {
|
|
5
|
+
"id": 1,
|
|
6
|
+
"key": "setup",
|
|
7
|
+
"title": "Environment Verification & Core Libraries",
|
|
8
|
+
"desc": "Verification and imports for essential data science and computation packages.",
|
|
9
|
+
"steps": [
|
|
10
|
+
"Import required modules (numpy, pandas, matplotlib, sklearn, nltk, tensorflow).",
|
|
11
|
+
"Print system status and versions."
|
|
12
|
+
],
|
|
13
|
+
"code": """import numpy, pandas, matplotlib, sklearn, nltk, tensorflow
|
|
14
|
+
print("All libraries loaded successfully!")
|
|
15
|
+
print("NumPy version:", numpy.__version__)
|
|
16
|
+
print("Pandas version:", pandas.__version__)""",
|
|
17
|
+
"output": """All libraries loaded successfully!
|
|
18
|
+
NumPy version: 2.4.3
|
|
19
|
+
Pandas version: 3.0.2"""
|
|
20
|
+
},
|
|
21
|
+
2: {
|
|
22
|
+
"id": 2,
|
|
23
|
+
"key": "bfs_dfs",
|
|
24
|
+
"title": "Graph Traversal (BFS & DFS)",
|
|
25
|
+
"desc": "Implementation of Breadth-First Search and Depth-First Search on a graph.",
|
|
26
|
+
"steps": [
|
|
27
|
+
"Define graph representation via adjacency list dictionary.",
|
|
28
|
+
"Traverse level-by-level using queue for BFS.",
|
|
29
|
+
"Traverse branch-by-branch recursively for DFS."
|
|
30
|
+
],
|
|
31
|
+
"code": """graph = {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': []}
|
|
32
|
+
|
|
33
|
+
def bfs(s):
|
|
34
|
+
q, v = [s], set()
|
|
35
|
+
for u in q:
|
|
36
|
+
if u not in v:
|
|
37
|
+
print(u, end=' ')
|
|
38
|
+
v.add(u)
|
|
39
|
+
q += graph[u]
|
|
40
|
+
|
|
41
|
+
def dfs(u, v=None):
|
|
42
|
+
if v is None: v = set()
|
|
43
|
+
if u not in v:
|
|
44
|
+
print(u, end=' ')
|
|
45
|
+
v.add(u)
|
|
46
|
+
for n in graph[u]: dfs(n, v)
|
|
47
|
+
|
|
48
|
+
print("BFS Traversal:")
|
|
49
|
+
bfs('A')
|
|
50
|
+
print("\\nDFS Traversal:")
|
|
51
|
+
dfs('A')""",
|
|
52
|
+
"output": """BFS Traversal:
|
|
53
|
+
A B C D E F
|
|
54
|
+
DFS Traversal:
|
|
55
|
+
A B D E F C"""
|
|
56
|
+
},
|
|
57
|
+
3: {
|
|
58
|
+
"id": 3,
|
|
59
|
+
"key": "astar",
|
|
60
|
+
"title": "A* Pathfinding Algorithm",
|
|
61
|
+
"desc": "Heuristic search algorithm computing the shortest path using f(n) = g(n) + h(n).",
|
|
62
|
+
"steps": [
|
|
63
|
+
"Define weighted graph and heuristic estimates h(n).",
|
|
64
|
+
"Maintain priority queue ordered by f(n) = cost + h(n).",
|
|
65
|
+
"Expand lowest f(n) node until goal is reached."
|
|
66
|
+
],
|
|
67
|
+
"code": """import heapq
|
|
68
|
+
|
|
69
|
+
graph = {'A': [('B', 1), ('C', 3)], 'B': [('D', 3), ('E', 1)], 'C': [('F', 2)],
|
|
70
|
+
'D': [('G', 2)], 'E': [('G', 4)], 'F': [('G', 1)], 'G': []}
|
|
71
|
+
h = {'A': 6, 'B': 4, 'C': 4, 'D': 2, 'E': 3, 'F': 1, 'G': 0}
|
|
72
|
+
|
|
73
|
+
def a_star(start, goal):
|
|
74
|
+
q, visited = [(h[start], 0, start, [start])], set()
|
|
75
|
+
while q:
|
|
76
|
+
f, g, u, path = heapq.heappop(q)
|
|
77
|
+
if u == goal: return path, g
|
|
78
|
+
if u not in visited:
|
|
79
|
+
visited.add(u)
|
|
80
|
+
for n, cost in graph[u]:
|
|
81
|
+
heapq.heappush(q, (g + cost + h[n], g + cost, n, path + [n]))
|
|
82
|
+
|
|
83
|
+
path, cost = a_star('A', 'G')
|
|
84
|
+
print("Shortest Path:", path)
|
|
85
|
+
print("Total Cost:", cost)""",
|
|
86
|
+
"output": """Shortest Path: ['A', 'B', 'D', 'G']
|
|
87
|
+
Total Cost: 6"""
|
|
88
|
+
},
|
|
89
|
+
4: {
|
|
90
|
+
"id": 4,
|
|
91
|
+
"key": "csp",
|
|
92
|
+
"title": "Constraint Satisfaction Problem (Map Coloring)",
|
|
93
|
+
"desc": "Backtracking algorithm ensuring no adjacent nodes share the same label.",
|
|
94
|
+
"steps": [
|
|
95
|
+
"Define discrete domain labels and adjacency constraints.",
|
|
96
|
+
"Assign labels sequentially to unassigned variables.",
|
|
97
|
+
"Backtrack on constraint violations."
|
|
98
|
+
],
|
|
99
|
+
"code": """colors = ['Red', 'Green', 'Blue']
|
|
100
|
+
regions = ['A', 'B', 'C', 'D']
|
|
101
|
+
neighbors = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], 'C': ['A', 'B', 'D'], 'D': ['B', 'C']}
|
|
102
|
+
assignment = {}
|
|
103
|
+
|
|
104
|
+
def solve(i=0):
|
|
105
|
+
if i == len(regions): return True
|
|
106
|
+
r = regions[i]
|
|
107
|
+
for c in colors:
|
|
108
|
+
if all(assignment.get(n) != c for n in neighbors[r]):
|
|
109
|
+
assignment[r] = c
|
|
110
|
+
if solve(i + 1): return True
|
|
111
|
+
del assignment[r]
|
|
112
|
+
return False
|
|
113
|
+
|
|
114
|
+
if solve():
|
|
115
|
+
print("Solution:")
|
|
116
|
+
for r, c in assignment.items(): print(r, "=", c)
|
|
117
|
+
else:
|
|
118
|
+
print("No solution exists")""",
|
|
119
|
+
"output": """Solution:
|
|
120
|
+
A = Red
|
|
121
|
+
B = Green
|
|
122
|
+
C = Blue
|
|
123
|
+
D = Red"""
|
|
124
|
+
},
|
|
125
|
+
5: {
|
|
126
|
+
"id": 5,
|
|
127
|
+
"key": "rules",
|
|
128
|
+
"title": "Production Rule Inference System",
|
|
129
|
+
"desc": "Forward-chaining rule-based diagnostic engine.",
|
|
130
|
+
"steps": [
|
|
131
|
+
"Collect Boolean predicate inputs.",
|
|
132
|
+
"Evaluate conditional antecedent rules.",
|
|
133
|
+
"Derive consequent conclusion."
|
|
134
|
+
],
|
|
135
|
+
"code": """print("DIAGNOSTIC EXPERT SYSTEM\\n" + "-" * 24)
|
|
136
|
+
ask = lambda s: input(f"Presence of {s}? (yes/no): ").strip().lower() == "yes"
|
|
137
|
+
fever, cough, cold, headache = ask("fever"), ask("cough"), ask("cold"), ask("headache")
|
|
138
|
+
|
|
139
|
+
if fever and cough: print("Diagnosis: Flu")
|
|
140
|
+
elif fever and headache: print("Diagnosis: Viral Fever")
|
|
141
|
+
elif cold and cough: print("Diagnosis: Common Cold")
|
|
142
|
+
elif headache: print("Diagnosis: Headache")
|
|
143
|
+
else: print("Diagnosis: Inconclusive / Undetermined")""",
|
|
144
|
+
"output": """DIAGNOSTIC EXPERT SYSTEM
|
|
145
|
+
------------------------
|
|
146
|
+
Presence of fever? (yes/no): yes
|
|
147
|
+
Presence of cough? (yes/no): no
|
|
148
|
+
Presence of cold? (yes/no): yes
|
|
149
|
+
Presence of headache? (yes/no): yes
|
|
150
|
+
Diagnosis: Viral Fever"""
|
|
151
|
+
},
|
|
152
|
+
6: {
|
|
153
|
+
"id": 6,
|
|
154
|
+
"key": "minimax",
|
|
155
|
+
"title": "Minimax Decision Strategy",
|
|
156
|
+
"desc": "Zero-sum game search algorithm finding optimal moves.",
|
|
157
|
+
"steps": [
|
|
158
|
+
"Represent board state as a sequence.",
|
|
159
|
+
"Recursively maximize utility for agent and minimize for opponent.",
|
|
160
|
+
"Select action yielding highest minimax score."
|
|
161
|
+
],
|
|
162
|
+
"code": """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)]
|
|
163
|
+
|
|
164
|
+
def check_winner(b):
|
|
165
|
+
for x, y, z in wins:
|
|
166
|
+
if b[x] != ' ' and b[x] == b[y] == b[z]: return 1 if b[x] == 'X' else -1
|
|
167
|
+
return 0 if ' ' not in b else None
|
|
168
|
+
|
|
169
|
+
def minimax(b, is_max):
|
|
170
|
+
w = check_winner(b)
|
|
171
|
+
if w is not None: return w
|
|
172
|
+
scores = [minimax(b[:i] + ('X' if is_max else 'O') + b[i+1:], not is_max)
|
|
173
|
+
for i, c in enumerate(b) if c == ' ']
|
|
174
|
+
return max(scores) if is_max else min(scores)
|
|
175
|
+
|
|
176
|
+
def best_move(b):
|
|
177
|
+
return max((i for i, c in enumerate(b) if c == ' '),
|
|
178
|
+
key=lambda i: minimax(b[:i] + 'X' + b[i+1:], False))
|
|
179
|
+
|
|
180
|
+
board = ['O','X','O','X','X',' ',' ',' ','O']
|
|
181
|
+
print("Best move for X is position:", best_move(board) + 1)""",
|
|
182
|
+
"output": """Best move for X is position: 6"""
|
|
183
|
+
},
|
|
184
|
+
7: {
|
|
185
|
+
"id": 7,
|
|
186
|
+
"key": "preprocess",
|
|
187
|
+
"title": "Tabular Data Preprocessing & Cleaning",
|
|
188
|
+
"desc": "Handling missing observations, column mean imputation, and record deduplication.",
|
|
189
|
+
"steps": [
|
|
190
|
+
"Construct tabular structure with missing indicators.",
|
|
191
|
+
"Impute null values using central tendencies.",
|
|
192
|
+
"Eliminate redundant rows and export clean records."
|
|
193
|
+
],
|
|
194
|
+
"code": """import pandas as pd
|
|
195
|
+
|
|
196
|
+
data = {'Name': ['Arun','Bala','Cathy','David','Eva'], 'Age': [20,21,None,22,20], 'Marks': [85,90,78,None,88]}
|
|
197
|
+
df = pd.DataFrame(data)
|
|
198
|
+
print("Original Data:\\n", df)
|
|
199
|
+
print("\\nMissing Values:\\n", df.isnull().sum())
|
|
200
|
+
df['Age'] = df['Age'].fillna(df['Age'].mean())
|
|
201
|
+
df['Marks'] = df['Marks'].fillna(df['Marks'].mean())
|
|
202
|
+
df = df.drop_duplicates()
|
|
203
|
+
print("\\nAfter Preprocessing:\\n", df)
|
|
204
|
+
df.to_csv("cleaned_data.csv", index=False)
|
|
205
|
+
print("\\nCleaned dataset saved successfully.")""",
|
|
206
|
+
"output": """Original Data:
|
|
207
|
+
Name Age Marks
|
|
208
|
+
0 Arun 20.0 85.0
|
|
209
|
+
1 Bala 21.0 90.0
|
|
210
|
+
2 Cathy NaN 78.0
|
|
211
|
+
3 David 22.0 NaN
|
|
212
|
+
4 Eva 20.0 88.0
|
|
213
|
+
|
|
214
|
+
Missing Values:
|
|
215
|
+
Name 0
|
|
216
|
+
Age 1
|
|
217
|
+
Marks 1
|
|
218
|
+
dtype: int64
|
|
219
|
+
|
|
220
|
+
After Preprocessing:
|
|
221
|
+
Name Age Marks
|
|
222
|
+
0 Arun 20.00 85.00
|
|
223
|
+
1 Bala 21.00 90.00
|
|
224
|
+
2 Cathy 20.75 78.00
|
|
225
|
+
3 David 22.00 85.25
|
|
226
|
+
4 Eva 20.00 88.00
|
|
227
|
+
|
|
228
|
+
Cleaned dataset saved successfully."""
|
|
229
|
+
},
|
|
230
|
+
8: {
|
|
231
|
+
"id": 8,
|
|
232
|
+
"key": "nlp",
|
|
233
|
+
"title": "Text Tokenization & Lexical Analysis",
|
|
234
|
+
"desc": "Tokenizing textual content, cleansing punctuation, and computing lexical frequencies.",
|
|
235
|
+
"steps": [
|
|
236
|
+
"Load tokenizer models.",
|
|
237
|
+
"Normalize text casing and segment words.",
|
|
238
|
+
"Filter alphabetic terms and tally occurrences."
|
|
239
|
+
],
|
|
240
|
+
"code": """import nltk
|
|
241
|
+
from nltk.tokenize import word_tokenize
|
|
242
|
+
from collections import Counter
|
|
243
|
+
|
|
244
|
+
nltk.download('punkt', quiet=True)
|
|
245
|
+
text = "Artificial intelligence is powerful. Artificial intelligence is useful."
|
|
246
|
+
words = [w for w in word_tokenize(text.lower()) if w.isalpha()]
|
|
247
|
+
print("Tokens:\\n", words)
|
|
248
|
+
print("\\nWord Frequency:")
|
|
249
|
+
for word, count in Counter(words).items():
|
|
250
|
+
print(word, ":", count)""",
|
|
251
|
+
"output": """Tokens:
|
|
252
|
+
['artificial', 'intelligence', 'is', 'powerful', 'artificial', 'intelligence', 'is', 'useful']
|
|
253
|
+
|
|
254
|
+
Word Frequency:
|
|
255
|
+
artificial : 2
|
|
256
|
+
intelligence : 2
|
|
257
|
+
is : 2
|
|
258
|
+
powerful : 1
|
|
259
|
+
useful : 1"""
|
|
260
|
+
},
|
|
261
|
+
9: {
|
|
262
|
+
"id": 9,
|
|
263
|
+
"key": "bayes",
|
|
264
|
+
"title": "Multinomial Naive Bayes Classifier",
|
|
265
|
+
"desc": "Probabilistic text classification using Bag-of-Words and Bayes theorem.",
|
|
266
|
+
"steps": [
|
|
267
|
+
"Vectorize raw text corpora into count feature matrices.",
|
|
268
|
+
"Fit Multinomial Naive Bayes conditional distributions.",
|
|
269
|
+
"Perform inference on unseen text samples."
|
|
270
|
+
],
|
|
271
|
+
"code": """from sklearn.feature_extraction.text import CountVectorizer
|
|
272
|
+
from sklearn.naive_bayes import MultinomialNB
|
|
273
|
+
|
|
274
|
+
messages = ["win money now", "free lottery ticket", "claim your prize",
|
|
275
|
+
"meeting at 10 am", "project meeting tomorrow", "submit the assignment"]
|
|
276
|
+
labels = ["Spam", "Spam", "Spam", "Not Spam", "Not Spam", "Not Spam"]
|
|
277
|
+
|
|
278
|
+
vectorizer = CountVectorizer()
|
|
279
|
+
X = vectorizer.fit_transform(messages)
|
|
280
|
+
model = MultinomialNB().fit(X, labels)
|
|
281
|
+
|
|
282
|
+
test_msg = ["free money prize"]
|
|
283
|
+
pred = model.predict(vectorizer.transform(test_msg))
|
|
284
|
+
print("Message:", test_msg[0])
|
|
285
|
+
print("Prediction:", pred[0])""",
|
|
286
|
+
"output": """Message: free money prize
|
|
287
|
+
Prediction: Spam"""
|
|
288
|
+
},
|
|
289
|
+
10: {
|
|
290
|
+
"id": 10,
|
|
291
|
+
"key": "regression",
|
|
292
|
+
"title": "Ordinary Least Squares Linear Regression",
|
|
293
|
+
"desc": "Fitting a linear relationship between input features and target values.",
|
|
294
|
+
"steps": [
|
|
295
|
+
"Prepare feature-target training arrays.",
|
|
296
|
+
"Fit ordinary least squares parameter weights.",
|
|
297
|
+
"Predict target response for candidate query point."
|
|
298
|
+
],
|
|
299
|
+
"code": """from sklearn.linear_model import LinearRegression
|
|
300
|
+
|
|
301
|
+
hours = [[1], [2], [3], [4], [5]]
|
|
302
|
+
marks = [20, 35, 50, 65, 80]
|
|
303
|
+
model = LinearRegression().fit(hours, marks)
|
|
304
|
+
|
|
305
|
+
study_hours = [[6]]
|
|
306
|
+
print("Input Feature:", study_hours[0][0])
|
|
307
|
+
print("Predicted Output:", model.predict(study_hours)[0])""",
|
|
308
|
+
"output": """Input Feature: 6
|
|
309
|
+
Predicted Output: 95.0"""
|
|
310
|
+
},
|
|
311
|
+
11: {
|
|
312
|
+
"id": 11,
|
|
313
|
+
"key": "4queens",
|
|
314
|
+
"title": "4-Queens Backtracking Constraint Solver",
|
|
315
|
+
"desc": "Constraint satisfaction placement of 4 non-attacking queens on a 4x4 matrix.",
|
|
316
|
+
"steps": [
|
|
317
|
+
"Allocate board array tracking column placement per row index.",
|
|
318
|
+
"Verify row, column, and diagonal non-conflict safety.",
|
|
319
|
+
"Backtrack recursively upon encountering dead ends."
|
|
320
|
+
],
|
|
321
|
+
"code": """board = [-1] * 4
|
|
322
|
+
|
|
323
|
+
def is_safe(r, c):
|
|
324
|
+
return all(board[i] != c and abs(board[i] - c) != r - i for i in range(r))
|
|
325
|
+
|
|
326
|
+
def solve(r=0):
|
|
327
|
+
if r == 4:
|
|
328
|
+
print("4-Queens Solution:")
|
|
329
|
+
for i in range(4):
|
|
330
|
+
print('. ' * board[i] + 'Q ' + '. ' * (3 - board[i]))
|
|
331
|
+
print("Column Positions:", board)
|
|
332
|
+
return True
|
|
333
|
+
for c in range(4):
|
|
334
|
+
if is_safe(r, c):
|
|
335
|
+
board[r] = c
|
|
336
|
+
if solve(r + 1): return True
|
|
337
|
+
board[r] = -1
|
|
338
|
+
return False
|
|
339
|
+
|
|
340
|
+
solve()""",
|
|
341
|
+
"output": """4-Queens Solution:
|
|
342
|
+
. Q . .
|
|
343
|
+
. . . Q
|
|
344
|
+
Q . . .
|
|
345
|
+
. . Q .
|
|
346
|
+
Column Positions: [1, 3, 0, 2]"""
|
|
347
|
+
},
|
|
348
|
+
12: {
|
|
349
|
+
"id": 12,
|
|
350
|
+
"key": "8puzzle",
|
|
351
|
+
"title": "8-Puzzle Sliding Tile State Solver",
|
|
352
|
+
"desc": "Breadth-first state graph traversal locating minimum tile transitions.",
|
|
353
|
+
"steps": [
|
|
354
|
+
"Model board as a 9-tuple with 0 representing the blank.",
|
|
355
|
+
"Generate reachable configurations using adjacency swaps.",
|
|
356
|
+
"Identify minimum transition sequence to target configuration."
|
|
357
|
+
],
|
|
358
|
+
"code": """from collections import deque
|
|
359
|
+
|
|
360
|
+
adj = {0:[1,3], 1:[0,2,4], 2:[1,5], 3:[0,4,6], 4:[1,3,5,7], 5:[2,4,8], 6:[3,7], 7:[4,6,8], 8:[5,7]}
|
|
361
|
+
|
|
362
|
+
def solve_8_puzzle(start, goal=(1, 2, 3, 4, 5, 6, 7, 8, 0)):
|
|
363
|
+
q, visited = deque([(start, [start])]), {start}
|
|
364
|
+
while q:
|
|
365
|
+
s, path = q.popleft()
|
|
366
|
+
if s == goal: return path
|
|
367
|
+
z = s.index(0)
|
|
368
|
+
for n in adj[z]:
|
|
369
|
+
nxt = list(s)
|
|
370
|
+
nxt[z], nxt[n] = nxt[n], nxt[z]
|
|
371
|
+
t = tuple(nxt)
|
|
372
|
+
if t not in visited:
|
|
373
|
+
visited.add(t)
|
|
374
|
+
q.append((t, path + [t]))
|
|
375
|
+
|
|
376
|
+
start = (1, 2, 3, 0, 4, 6, 7, 5, 8)
|
|
377
|
+
path = solve_8_puzzle(start)
|
|
378
|
+
print(f"8-Puzzle Solved in {len(path) - 1} moves:\\n")
|
|
379
|
+
for step, p in enumerate(path):
|
|
380
|
+
print(f"Step {step}:")
|
|
381
|
+
for i in range(0, 9, 3): print(p[i:i+3])
|
|
382
|
+
print()""",
|
|
383
|
+
"output": """8-Puzzle Solved in 3 moves:
|
|
384
|
+
|
|
385
|
+
Step 0:
|
|
386
|
+
(1, 2, 3)
|
|
387
|
+
(0, 4, 6)
|
|
388
|
+
(7, 5, 8)
|
|
389
|
+
|
|
390
|
+
Step 1:
|
|
391
|
+
(1, 2, 3)
|
|
392
|
+
(4, 0, 6)
|
|
393
|
+
(7, 5, 8)
|
|
394
|
+
|
|
395
|
+
Step 2:
|
|
396
|
+
(1, 2, 3)
|
|
397
|
+
(4, 5, 6)
|
|
398
|
+
(7, 0, 8)
|
|
399
|
+
|
|
400
|
+
Step 3:
|
|
401
|
+
(1, 2, 3)
|
|
402
|
+
(4, 5, 6)
|
|
403
|
+
(7, 8, 0)"""
|
|
404
|
+
},
|
|
405
|
+
13: {
|
|
406
|
+
"id": 13,
|
|
407
|
+
"key": "inventory",
|
|
408
|
+
"title": "Catalog & Inventory Management System",
|
|
409
|
+
"desc": "Object-oriented state management for item checkout, check-in, and catalog listing.",
|
|
410
|
+
"steps": [
|
|
411
|
+
"Encapsulate collection records in a managed object class.",
|
|
412
|
+
"Implement issue/checkout with condition checks and removals.",
|
|
413
|
+
"Implement return operations with list restoration."
|
|
414
|
+
],
|
|
415
|
+
"code": """class Library:
|
|
416
|
+
def __init__(self, books):
|
|
417
|
+
self.books = books
|
|
418
|
+
|
|
419
|
+
def show(self):
|
|
420
|
+
print("Available items:", self.books)
|
|
421
|
+
|
|
422
|
+
def borrow(self, b):
|
|
423
|
+
if b in self.books:
|
|
424
|
+
self.books.remove(b)
|
|
425
|
+
print(f"Issued: {b}")
|
|
426
|
+
else:
|
|
427
|
+
print(f"{b} is not available")
|
|
428
|
+
|
|
429
|
+
def return_book(self, b):
|
|
430
|
+
self.books.append(b)
|
|
431
|
+
print(f"Returned: {b}")
|
|
432
|
+
|
|
433
|
+
lib = Library(["Concepts", "Basics", "Data Mining", "Machine Learning"])
|
|
434
|
+
print("CATALOG & INVENTORY SYSTEM\\n" + "-" * 26)
|
|
435
|
+
lib.show()
|
|
436
|
+
lib.borrow("Concepts")
|
|
437
|
+
lib.borrow("Concepts")
|
|
438
|
+
lib.return_book("Concepts")
|
|
439
|
+
lib.show()""",
|
|
440
|
+
"output": """CATALOG & INVENTORY SYSTEM
|
|
441
|
+
--------------------------
|
|
442
|
+
Available items: ['Concepts', 'Basics', 'Data Mining', 'Machine Learning']
|
|
443
|
+
Issued: Concepts
|
|
444
|
+
Concepts is not available
|
|
445
|
+
Returned: Concepts
|
|
446
|
+
Available items: ['Basics', 'Data Mining', 'Machine Learning', 'Concepts']"""
|
|
447
|
+
}
|
|
448
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: skl-core
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Standard Knowledge & Algorithm Library: search, CSP, game theory, heuristics, and utilities.
|
|
5
|
+
Author: SKL Developers
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: algorithms,search,bfs,dfs,astar,minimax,csp,backtracking,puzzle,utilities
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
11
|
+
Requires-Python: >=3.7
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# SKL (Standard Knowledge & Algorithm Library)
|
|
15
|
+
|
|
16
|
+
A lightweight Python library providing clean, minimal implementations of standard computer science algorithms, search heuristics, constraint satisfaction problems, and data utilities.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## 📦 Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install skl
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## 🚀 CLI Usage
|
|
29
|
+
|
|
30
|
+
Access algorithms and code snippets directly from the terminal:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
# Interactive menu
|
|
34
|
+
skl
|
|
35
|
+
|
|
36
|
+
# Print & copy 4-Queens solver
|
|
37
|
+
skl 4queen
|
|
38
|
+
|
|
39
|
+
# Print & copy 8-Puzzle solver
|
|
40
|
+
skl 8puzzle
|
|
41
|
+
|
|
42
|
+
# Print & copy Inventory management
|
|
43
|
+
skl lib
|
|
44
|
+
|
|
45
|
+
# Graph traversal (BFS & DFS)
|
|
46
|
+
skl bfs
|
|
47
|
+
|
|
48
|
+
# Pathfinding (A* search)
|
|
49
|
+
skl astar
|
|
50
|
+
|
|
51
|
+
# Dump all algorithm scripts to the current directory
|
|
52
|
+
skl saveall
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## ⚡ Direct Code Execution & Clipboard
|
|
58
|
+
|
|
59
|
+
- **Automatic Clipboard Copy**: Every query automatically copies the compact code directly to your system clipboard (press `Ctrl + V` to paste into any editor).
|
|
60
|
+
- **Run on Demand**:
|
|
61
|
+
```bash
|
|
62
|
+
skl 4queen --run
|
|
63
|
+
skl 8puzzle --run
|
|
64
|
+
skl astar --run
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## 🐍 Python Import API
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import skl
|
|
73
|
+
|
|
74
|
+
# Execute algorithm
|
|
75
|
+
skl.run("4queen")
|
|
76
|
+
skl.run("8puzzle")
|
|
77
|
+
|
|
78
|
+
# Retrieve raw code string
|
|
79
|
+
snippet = skl.code("lib")
|
|
80
|
+
print(snippet)
|
|
81
|
+
|
|
82
|
+
# Copy to clipboard
|
|
83
|
+
skl.copy("astar")
|
|
84
|
+
|
|
85
|
+
# Save all files locally
|
|
86
|
+
skl.save_all("./scripts")
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## 📄 License
|
|
92
|
+
MIT
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/skl/__init__.py
|
|
4
|
+
src/skl/__main__.py
|
|
5
|
+
src/skl/cli.py
|
|
6
|
+
src/skl/registry.py
|
|
7
|
+
src/skl/modules/__init__.py
|
|
8
|
+
src/skl/modules/p01_setup.py
|
|
9
|
+
src/skl/modules/p02_bfs_dfs.py
|
|
10
|
+
src/skl/modules/p03_astar.py
|
|
11
|
+
src/skl/modules/p04_csp.py
|
|
12
|
+
src/skl/modules/p05_rules.py
|
|
13
|
+
src/skl/modules/p06_minimax.py
|
|
14
|
+
src/skl/modules/p07_preprocess.py
|
|
15
|
+
src/skl/modules/p08_nlp.py
|
|
16
|
+
src/skl/modules/p09_bayes.py
|
|
17
|
+
src/skl/modules/p10_regression.py
|
|
18
|
+
src/skl/modules/p11_4queens.py
|
|
19
|
+
src/skl/modules/p12_8puzzle.py
|
|
20
|
+
src/skl/modules/p13_inventory.py
|
|
21
|
+
src/skl_core.egg-info/PKG-INFO
|
|
22
|
+
src/skl_core.egg-info/SOURCES.txt
|
|
23
|
+
src/skl_core.egg-info/dependency_links.txt
|
|
24
|
+
src/skl_core.egg-info/entry_points.txt
|
|
25
|
+
src/skl_core.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
skl
|