-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunified_interface.py
More file actions
799 lines (670 loc) · 27.5 KB
/
unified_interface.py
File metadata and controls
799 lines (670 loc) · 27.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
"""
Unified Interface for Algorithm Recommender System
===================================================
This module provides a single, unified interface for all algorithm
recommendation functionality. Users can simply provide raw input
(arrays or graphs) and receive intelligent algorithm recommendations.
The system supports three domains:
1. SORTING: Recommends among Insertion, Selection, Merge, Quick, Heap Sort
2. ARRAY SEARCHING: Recommends among Linear, Binary, Jump, Exponential Search
3. GRAPH SEARCHING: Recommends among BFS, Dijkstra, Bellman-Ford, A*
Key Features:
- Automatic feature extraction from raw input
- ML-based algorithm selection with correctness constraints
- Human-readable explanations for all recommendations
- Optional execution of recommended algorithm
Usage:
from algorithm_recommender import AlgorithmRecommender
recommender = AlgorithmRecommender()
recommender.load_models() # Or train_all() if models don't exist
# Sorting recommendation
result = recommender.recommend_sorting([5, 2, 8, 1, 9])
print(result['algorithm'], result['explanation'])
# Array search recommendation
result = recommender.recommend_array_search([1, 2, 3, 4, 5])
print(result['algorithm'])
# Graph search recommendation
graph = {0: [(1, 1.0), (2, 4.0)], 1: [(2, 2.0)], 2: []}
result = recommender.recommend_graph_search(graph)
print(result['algorithm'])
Author: Algorithm Recommender Research Team
Version: 1.0.0
"""
import os
from typing import List, Dict, Tuple, Optional, Union, Any, Callable
# Import recommenders
from sorting.recommender import SortingRecommender
from sorting.algorithms import SORTING_ALGORITHMS
from searching.array_search.recommender import ArraySearchRecommender
from searching.array_search.algorithms import ARRAY_SEARCH_ALGORITHMS
from searching.graph_search.recommender import GraphSearchRecommender
from searching.graph_search.algorithms import GRAPH_SEARCH_ALGORITHMS
# Import new modules
from searching.string_search.recommender import StringSearchRecommender
from searching.string_search.algorithms import STRING_SEARCH_ALGORITHMS
from searching.tree_search.recommender import TreeSearchRecommender
from searching.tree_search.algorithms import TREE_SEARCH_ALGORITHMS, BST, AVLTree
# Import structure inference
from utils.structure_inference import (
StructureInference, StructureType, StructureInferenceResult,
infer_structure, infer_from_problem
)
class AlgorithmRecommender:
"""
Unified interface for all algorithm recommendation functionality.
This class provides a single entry point for recommending algorithms
across three domains: sorting, array searching, and graph searching.
The recommender:
1. Accepts raw input (no precomputed features required)
2. Automatically extracts relevant features
3. Uses trained ML models to recommend algorithms
4. Enforces correctness constraints (especially for searching)
5. Provides human-readable explanations
Attributes:
sorting: SortingRecommender instance
array_search: ArraySearchRecommender instance
graph_search: GraphSearchRecommender instance
Example:
>>> recommender = AlgorithmRecommender()
>>> recommender.load_models()
>>>
>>> # Sorting
>>> result = recommender.recommend_sorting([3, 1, 4, 1, 5])
>>> print(f"Use {result['algorithm']}: {result['explanation']}")
>>>
>>> # Array search
>>> result = recommender.recommend_array_search([1, 2, 3, 4, 5])
>>> print(f"Use {result['algorithm']}")
>>>
>>> # Graph search
>>> graph = {0: [(1, 1.0)], 1: [(2, 1.0)], 2: []}
>>> result = recommender.recommend_graph_search(graph)
>>> print(f"Use {result['algorithm']}")
"""
def __init__(self, models_dir: Optional[str] = None):
"""
Initialize the unified recommender.
Args:
models_dir: Directory containing trained models.
Defaults to 'models/' relative to this file.
"""
if models_dir is None:
self.models_dir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'models'
)
else:
self.models_dir = models_dir
# Initialize recommenders
self.sorting = SortingRecommender()
self.array_search = ArraySearchRecommender()
self.graph_search = GraphSearchRecommender()
self.string_search = StringSearchRecommender()
self.tree_search = TreeSearchRecommender()
# Initialize structure inference
self.structure_inference = StructureInference()
self._models_loaded = False
def load_models(self, verbose: bool = True):
"""
Load all pre-trained models from disk.
Args:
verbose: Whether to print loading progress.
Raises:
FileNotFoundError: If any required model file is missing.
"""
sorting_path = os.path.join(self.models_dir, 'sorting_model.pkl')
array_search_path = os.path.join(self.models_dir, 'array_search_model.pkl')
graph_search_path = os.path.join(self.models_dir, 'graph_search_model.pkl')
string_search_path = os.path.join(self.models_dir, 'string_search_model.pkl')
tree_search_path = os.path.join(self.models_dir, 'tree_search_model.pkl')
# Check required models
missing = []
if not os.path.exists(sorting_path):
missing.append('sorting_model.pkl')
if not os.path.exists(array_search_path):
missing.append('array_search_model.pkl')
if not os.path.exists(graph_search_path):
missing.append('graph_search_model.pkl')
if missing:
raise FileNotFoundError(
f"Missing required model files: {missing}. "
f"Run train_all() to generate models."
)
if verbose:
print("Loading models...")
self.sorting.load_model(sorting_path)
self.array_search.load_model(array_search_path)
self.graph_search.load_model(graph_search_path)
# Load optional new models if they exist
if os.path.exists(string_search_path):
try:
self.string_search.load_model(string_search_path)
if verbose:
print(" ✓ String search model loaded")
except Exception as e:
if verbose:
print(f" ⚠ String search model not loaded: {e}")
elif verbose:
print(" ⚠ String search model not found (optional)")
if os.path.exists(tree_search_path):
try:
self.tree_search.load_model(tree_search_path)
if verbose:
print(" ✓ Tree search model loaded")
except Exception as e:
if verbose:
print(f" ⚠ Tree search model not loaded: {e}")
elif verbose:
print(" ⚠ Tree search model not found (optional)")
self._models_loaded = True
if verbose:
print("All required models loaded successfully!")
def train_all(
self,
sorting_instances: int = 800,
array_search_instances: int = 400,
graph_search_instances: int = 300,
verbose: bool = True
):
"""
Train all models from scratch.
This generates training data, trains RandomForest classifiers,
and saves the models to disk.
Args:
sorting_instances: Number of sorting training instances.
array_search_instances: Number of array search instances.
graph_search_instances: Number of graph search instances.
verbose: Whether to print progress.
"""
os.makedirs(self.models_dir, exist_ok=True)
# Train sorting model
if verbose:
print("\n" + "=" * 60)
print("TRAINING SORTING MODEL")
print("=" * 60)
from sorting.train import train_sorting_model
train_sorting_model(
num_instances=sorting_instances,
output_dir=self.models_dir,
verbose=verbose
)
self.sorting.load_model(models_dir=self.models_dir)
# Train array search model
if verbose:
print("\n" + "=" * 60)
print("TRAINING ARRAY SEARCH MODEL")
print("=" * 60)
from searching.array_search.train import train_array_search_model
train_array_search_model(
num_instances=array_search_instances,
output_dir=self.models_dir,
verbose=verbose
)
self.array_search.load_model(models_dir=self.models_dir)
# Train graph search model
if verbose:
print("\n" + "=" * 60)
print("TRAINING GRAPH SEARCH MODEL")
print("=" * 60)
from searching.graph_search.train import train_graph_search_model
train_graph_search_model(
num_instances=graph_search_instances,
output_dir=self.models_dir,
verbose=verbose
)
self.graph_search.load_model(models_dir=self.models_dir)
# Train string search model
if verbose:
print("\n" + "=" * 60)
print("TRAINING STRING SEARCH MODEL")
print("=" * 60)
from searching.string_search.train import train_string_search_model
string_search_path = os.path.join(self.models_dir, 'string_search_model.pkl')
train_string_search_model(
num_instances=300,
output_path=string_search_path,
seed=42,
verbose=verbose
)
self.string_search.load_model(models_dir=self.models_dir)
# Train tree search model
if verbose:
print("\n" + "=" * 60)
print("TRAINING TREE SEARCH MODEL")
print("=" * 60)
from searching.tree_search.train import train_tree_search_model
tree_search_path = os.path.join(self.models_dir, 'tree_search_model.pkl')
train_tree_search_model(
num_instances=300,
output_path=tree_search_path,
seed=42,
verbose=verbose
)
self.tree_search.load_model(models_dir=self.models_dir)
self._models_loaded = True
if verbose:
print("\n" + "=" * 60)
print("ALL MODELS TRAINED SUCCESSFULLY!")
print("=" * 60)
def recommend_sorting(
self,
arr: List[Union[int, float]],
return_probabilities: bool = False
) -> Dict:
"""
Recommend the best sorting algorithm for a raw input array.
The system automatically extracts features and uses the ML model
to select the optimal algorithm.
Args:
arr: Raw input array to be sorted.
return_probabilities: Include probability distribution.
Returns:
Dictionary containing:
- 'algorithm': Recommended algorithm name
- 'explanation': Why this algorithm was chosen
- 'features': Extracted features
- 'feature_summary': Human-readable feature description
- 'probabilities': (if requested) Probability per algorithm
Example:
>>> result = recommender.recommend_sorting([5, 2, 8, 1, 9])
>>> print(result['algorithm'])
'insertion_sort'
>>> print(result['explanation'])
'Array is small, nearly sorted → Insertion Sort selected.'
"""
self._ensure_models_loaded()
return self.sorting.recommend(arr, return_probabilities)
def recommend_array_search(
self,
arr: List[Union[int, float]],
return_probabilities: bool = False
) -> Dict:
"""
Recommend the best array search algorithm.
Correctness Constraints (STRICT):
- Linear Search: Always valid
- Binary/Jump Search: Only if array is sorted
- Exponential Search: Only if sorted and uniform
The recommender will NEVER recommend an invalid algorithm.
Args:
arr: Raw input array.
return_probabilities: Include probability distribution.
Returns:
Dictionary with algorithm, explanation, valid_algorithms, etc.
Example:
>>> result = recommender.recommend_array_search([1, 2, 3, 4, 5])
>>> print(result['algorithm'])
'binary_search'
>>> print(result['valid_algorithms'])
['linear_search', 'binary_search', 'jump_search', 'exponential_search']
"""
self._ensure_models_loaded()
return self.array_search.recommend(arr, return_probabilities=return_probabilities)
def recommend_graph_search(
self,
graph: Dict[Any, List[Tuple[Any, float]]],
has_heuristic: bool = False,
return_probabilities: bool = False
) -> Dict:
"""
Recommend the best graph search algorithm.
Correctness Constraints (STRICT):
- BFS: Only for unweighted graphs
- Dijkstra: Only for non-negative weights
- Bellman-Ford: Required for negative weights
- A*: Only when heuristic is available
The recommender will NEVER recommend an invalid algorithm.
Args:
graph: Adjacency list {node: [(neighbor, weight), ...]}.
has_heuristic: Whether a heuristic function is available.
return_probabilities: Include probability distribution.
Returns:
Dictionary with algorithm, explanation, valid_algorithms, etc.
Example:
>>> graph = {0: [(1, 1.0)], 1: [(2, 1.0)], 2: []}
>>> result = recommender.recommend_graph_search(graph)
>>> print(result['algorithm'])
'bfs'
"""
self._ensure_models_loaded()
return self.graph_search.recommend(graph, has_heuristic, return_probabilities)
def recommend_string_search(
self,
text: str,
patterns: Union[str, List[str]],
is_prefix_query: bool = False,
return_probabilities: bool = False
) -> Dict:
"""
Recommend the best string search algorithm.
Correctness Constraints (STRICT):
- Naive String Search: Always valid
- Trie Search: Only valid for multiple patterns OR prefix queries
Args:
text: The text to search in.
patterns: Single pattern or list of patterns.
is_prefix_query: Whether this is a prefix-based search.
return_probabilities: Include probability distribution.
Returns:
Dictionary with algorithm, explanation, valid_algorithms, etc.
Example:
>>> result = recommender.recommend_string_search("hello world", ["hello", "world"])
>>> print(result['algorithm'])
'trie_search'
"""
self._ensure_models_loaded()
if self.string_search.model is None:
raise RuntimeError("String search model not loaded. Train with train_all().")
return self.string_search.recommend(text, patterns, is_prefix_query, return_probabilities)
def recommend_tree_search(
self,
tree: Union[BST, AVLTree, Dict],
keys: Optional[List[Any]] = None,
return_probabilities: bool = False
) -> Dict:
"""
Recommend the best tree search algorithm.
Correctness Constraints (STRICT):
- BST Search: Always valid (but O(n) worst case on skewed trees)
- Balanced Tree Search: Only valid on balanced trees
Args:
tree: BST, AVLTree, or dict representation.
keys: Optional list of keys if tree is dict.
return_probabilities: Include probability distribution.
Returns:
Dictionary with algorithm, explanation, valid_algorithms, etc.
Example:
>>> bst = BST()
>>> bst.from_list([5, 3, 7, 1, 9])
>>> result = recommender.recommend_tree_search(bst)
>>> print(result['algorithm'])
"""
self._ensure_models_loaded()
if self.tree_search.model is None:
raise RuntimeError("Tree search model not loaded. Train with train_all().")
return self.tree_search.recommend(tree, keys, return_probabilities)
def recommend_auto(
self,
data: Any = None,
problem_statement: str = "",
operation_hint: str = "",
**kwargs
) -> Dict:
"""
Automatically detect input type and recommend appropriate algorithm.
This is the smart entry point that uses structure inference to
determine what kind of problem the user has and routes to the
correct recommender.
Args:
data: Input data (array, graph, tree, string, etc.)
problem_statement: Natural language problem description.
operation_hint: Hint about operation (sort, search, etc.)
**kwargs: Additional arguments passed to specific recommender.
Returns:
Dictionary containing:
- 'task_type': Detected task type
- 'structure_type': Detected structure type
- 'algorithm': Recommended algorithm
- 'explanation': Why this algorithm was chosen
- 'inference_result': Structure inference details
Example:
>>> result = recommender.recommend_auto([5, 2, 8, 1, 9], operation_hint="sort")
>>> print(result['task_type'], result['algorithm'])
"""
self._ensure_models_loaded()
# Infer from problem statement if provided
if problem_statement:
inference_result = self.structure_inference.infer_from_problem(problem_statement)
elif data is not None:
inference_result = self.structure_inference.infer(data)
else:
raise ValueError("Either data or problem_statement must be provided")
structure_type = inference_result.structure_type
task_type = self.structure_inference.get_task_type(structure_type, operation_hint)
result = {
'task_type': task_type,
'structure_type': structure_type.value,
'inference_result': inference_result.to_dict(),
}
try:
if task_type == 'sorting':
recommendation = self.sorting.recommend(data, **kwargs)
elif task_type == 'array_search':
recommendation = self.array_search.recommend(data, **kwargs)
elif task_type == 'graph_search':
has_heuristic = kwargs.get('has_heuristic', False)
recommendation = self.graph_search.recommend(data, has_heuristic, **kwargs)
elif task_type == 'string_search':
if isinstance(data, tuple) and len(data) >= 2:
text, patterns = data[0], data[1]
else:
text = data
patterns = kwargs.get('patterns', [''])
is_prefix = kwargs.get('is_prefix_query', False)
recommendation = self.string_search.recommend(text, patterns, is_prefix)
elif task_type == 'tree_search':
keys = kwargs.get('keys', None)
recommendation = self.tree_search.recommend(data, keys)
else:
recommendation = {'algorithm': 'unknown', 'explanation': 'Could not determine task type'}
result.update(recommendation)
except Exception as e:
result['error'] = str(e)
result['algorithm'] = 'unknown'
result['explanation'] = f'Error during recommendation: {e}'
return result
def sort(
self,
arr: List[Union[int, float]]
) -> Tuple[List[float], str, str]:
"""
Recommend and execute sorting on an array.
Convenience method that recommends the best algorithm and
executes it in one call.
Args:
arr: Raw input array.
Returns:
Tuple of (sorted_array, algorithm_name, explanation).
Example:
>>> sorted_arr, algo, why = recommender.sort([5, 2, 8, 1, 9])
>>> print(sorted_arr)
[1, 2, 5, 8, 9]
"""
self._ensure_models_loaded()
return self.sorting.execute_recommendation(arr)
def search_array(
self,
arr: List[Union[int, float]],
target: Union[int, float]
) -> Tuple[int, str, str]:
"""
Recommend and execute array search.
Args:
arr: Raw input array.
target: Value to search for.
Returns:
Tuple of (index, algorithm_name, explanation).
Index is -1 if target not found.
Example:
>>> idx, algo, why = recommender.search_array([1, 2, 3, 4, 5], 3)
>>> print(idx, algo)
2 binary_search
"""
self._ensure_models_loaded()
return self.array_search.execute_recommendation(arr, target)
def search_graph(
self,
graph: Dict[Any, List[Tuple[Any, float]]],
start: Any,
goal: Any,
heuristic: Optional[Callable] = None,
node_positions: Optional[Dict] = None
) -> Tuple[Optional[List[Any]], float, str, str]:
"""
Recommend and execute graph search.
Args:
graph: Adjacency list representation.
start: Starting node.
goal: Target node.
heuristic: Optional heuristic function for A*.
node_positions: Optional positions for Euclidean heuristic.
Returns:
Tuple of (path, cost, algorithm_name, explanation).
Path is None if goal is unreachable.
Example:
>>> graph = {0: [(1, 1.0)], 1: [(2, 1.0)], 2: []}
>>> path, cost, algo, why = recommender.search_graph(graph, 0, 2)
>>> print(path, cost)
[0, 1, 2] 2.0
"""
self._ensure_models_loaded()
return self.graph_search.execute_recommendation(
graph, start, goal, heuristic, node_positions
)
def _ensure_models_loaded(self):
"""Ensure models are loaded before making recommendations."""
if not self._models_loaded:
raise RuntimeError(
"Models not loaded. Call load_models() or train_all() first."
)
def get_available_algorithms(self) -> Dict[str, List[str]]:
"""
Get all available algorithms organized by domain.
Returns:
Dictionary mapping domain to algorithm names.
"""
return {
'sorting': list(SORTING_ALGORITHMS.keys()),
'array_search': list(ARRAY_SEARCH_ALGORITHMS.keys()),
'graph_search': list(GRAPH_SEARCH_ALGORITHMS.keys()),
'string_search': list(STRING_SEARCH_ALGORITHMS.keys()),
'tree_search': list(TREE_SEARCH_ALGORITHMS.keys()),
}
def get_feature_importance(self, domain: str) -> Dict[str, float]:
"""
Get feature importance for a specific domain's model.
Args:
domain: One of 'sorting', 'array_search', 'graph_search'.
Returns:
Dictionary mapping feature names to importance scores.
"""
self._ensure_models_loaded()
if domain == 'sorting':
return self.sorting.get_feature_importance()
elif domain == 'array_search':
# Array search recommender doesn't have this method yet
raise NotImplementedError("Feature importance not yet implemented for array_search")
elif domain == 'graph_search':
raise NotImplementedError("Feature importance not yet implemented for graph_search")
else:
raise ValueError(f"Unknown domain: {domain}")
def demo():
"""
Demonstrate the unified algorithm recommender.
This function shows how to use the system for all three domains.
"""
print("=" * 70)
print("ALGORITHM RECOMMENDER SYSTEM - DEMONSTRATION")
print("=" * 70)
# Initialize recommender
recommender = AlgorithmRecommender()
# Check if models exist, train if not
try:
recommender.load_models()
except FileNotFoundError:
print("\nModels not found. Training all models...")
recommender.train_all(
sorting_instances=500,
array_search_instances=300,
graph_search_instances=200
)
print("\n" + "-" * 70)
print("SORTING DEMONSTRATIONS")
print("-" * 70)
# Demo 1: Small random array
arr1 = [5, 2, 8, 1, 9, 3, 7]
result1 = recommender.recommend_sorting(arr1)
print(f"\nArray: {arr1}")
print(f"Recommended: {result1['algorithm']}")
print(f"Explanation: {result1['explanation']}")
# Demo 2: Large sorted array
arr2 = list(range(1000))
result2 = recommender.recommend_sorting(arr2)
print(f"\nArray: [0, 1, 2, ..., 999] (sorted, n=1000)")
print(f"Recommended: {result2['algorithm']}")
print(f"Explanation: {result2['explanation']}")
# Demo 3: Execute sorting
arr3 = [10, 5, 8, 3, 1]
sorted_arr, algo, explanation = recommender.sort(arr3)
print(f"\nSorting {arr3}")
print(f"Result: {sorted_arr}")
print(f"Used: {algo}")
print("\n" + "-" * 70)
print("ARRAY SEARCH DEMONSTRATIONS")
print("-" * 70)
# Demo 4: Sorted array
arr4 = list(range(100))
result4 = recommender.recommend_array_search(arr4)
print(f"\nArray: [0, 1, 2, ..., 99] (sorted)")
print(f"Recommended: {result4['algorithm']}")
print(f"Valid options: {result4['valid_algorithms']}")
print(f"Explanation: {result4['explanation']}")
# Demo 5: Unsorted array
arr5 = [5, 2, 8, 1, 9, 3, 7]
result5 = recommender.recommend_array_search(arr5)
print(f"\nArray: {arr5} (unsorted)")
print(f"Recommended: {result5['algorithm']}")
print(f"Valid options: {result5['valid_algorithms']}")
print(f"Note: Only linear_search is valid for unsorted arrays!")
# Demo 6: Execute search
arr6 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
idx, algo, explanation = recommender.search_array(arr6, 7)
print(f"\nSearching for 7 in {arr6}")
print(f"Found at index: {idx}")
print(f"Used: {algo}")
print("\n" + "-" * 70)
print("GRAPH SEARCH DEMONSTRATIONS")
print("-" * 70)
# Demo 7: Unweighted graph
graph1 = {
0: [(1, 1.0), (2, 1.0)],
1: [(3, 1.0)],
2: [(3, 1.0)],
3: []
}
result7 = recommender.recommend_graph_search(graph1)
print(f"\nUnweighted graph: 0 -> 1,2; 1,2 -> 3")
print(f"Recommended: {result7['algorithm']}")
print(f"Valid options: {result7['valid_algorithms']}")
# Demo 8: Weighted graph
graph2 = {
0: [(1, 4.0), (2, 1.0)],
1: [(3, 1.0)],
2: [(1, 2.0), (3, 5.0)],
3: []
}
result8 = recommender.recommend_graph_search(graph2)
print(f"\nWeighted graph (non-negative)")
print(f"Recommended: {result8['algorithm']}")
print(f"Valid options: {result8['valid_algorithms']}")
# Demo 9: Graph with negative weights
graph3 = {
0: [(1, 4.0), (2, 5.0)],
1: [(2, -3.0)], # Negative weight!
2: []
}
result9 = recommender.recommend_graph_search(graph3)
print(f"\nGraph with NEGATIVE weights")
print(f"Recommended: {result9['algorithm']}")
print(f"Valid options: {result9['valid_algorithms']}")
print(f"Note: Only bellman_ford can handle negative weights!")
# Demo 10: Execute graph search
path, cost, algo, explanation = recommender.search_graph(graph2, 0, 3)
print(f"\nFinding path from 0 to 3")
print(f"Path: {path}")
print(f"Cost: {cost}")
print(f"Used: {algo}")
print("\n" + "=" * 70)
print("DEMONSTRATION COMPLETE")
print("=" * 70)
if __name__ == '__main__':
demo()