Skip to content
This repository was archived by the owner on Feb 27, 2026. It is now read-only.

Commit 6e7415c

Browse files
Merge branch 'main' into roundsuffix_entry
2 parents e89173f + 4e3bf97 commit 6e7415c

78 files changed

Lines changed: 7244 additions & 1153 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

content/ai/concepts/search-algorithms/terms/beam-search/beam-search.md

Lines changed: 63 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,20 @@
22
Title: 'BEAM Search'
33
Description: 'A graph searching algorithm that is a variant of breadth-first search.'
44
Subjects:
5-
- 'Data Science'
65
- 'AI'
6+
- 'Data Science'
77
Tags:
8-
- 'Search Algorithms'
98
- 'AI'
9+
- 'Algorithms'
10+
- 'Search Algorithms'
1011
CatalogContent:
1112
- 'learn-python-3'
12-
- 'paths/machine-learning-ai-engineering-foundations'
13+
- 'paths/computer-science'
1314
---
1415

1516
**BEAM Search**, a variant of [breadth-first Search](https://www.codecademy.com/resources/docs/ai/search-algorithms/breadth-first-search), is an algorithm that searches a weighted graph for an optimal path from some start node **S** to some goal node **G**. The difference between BEAM search and breadth-first search is that at every level of the search tree, only the top _β_ candidates are chosen for further exploration. Here, β is known as the _beam width_. The reasoning behind this is that a path from **S** to **G** is likely to pass through some top number of most promising nodes. This leads to an algorithm that is fast and memory-efficient because it can disregard many nodes that may appear to be too far from the goal. This, however, sometimes causes the algorithm to overlook a potential shortest path because a candidate node is greater than the beam width. This renders the algorithm as _incomplete_, meaning that finding the shortest path is not guaranteed. Since the algorithm can find a reasonably short path, trading completeness for efficiency is accepted. Much like [A\* search](https://www.codecademy.com/resources/docs/ai/search-algorithms/a-star-search) and [best-first search](https://www.codecademy.com/resources/docs/ai/search-algorithms/best-first-search), an evaluation function is used to evaluate the candidacy of nodes for further exploration.
1617

17-
## The Algorithm
18+
## How the Beam Search Algorithm Works
1819

1920
Similar to A\* search, the algorithm uses an **open list** and a **closed list** for the exploration of nodes. In this algorithm, the open list is an ordinary queue. The algorithm begins with a start node **S**, which also serves as the root node for the search tree.
2021

@@ -58,10 +59,67 @@ It is in this step that node **G** has been found:
5859
Trace the path from **S** to **G**:
5960
![Final-path](https://raw.githubusercontent.com/Codecademy/docs/main/media/BEAM-Search-final-path.png)
6061

61-
## Advantages and Disadvantages
62+
## Pseudocode for Beam Search Algorithm
63+
64+
```plaintext
65+
function BEAM_SEARCH(start_node, goal_test, beam_width, max_depth):
66+
current_level ← [start_node]
67+
depth ← 0
68+
69+
while current_level is not empty AND depth < max_depth:
70+
all_successors ← []
71+
72+
// Generate all successors from current level
73+
for each node in current_level:
74+
if goal_test(node):
75+
return SUCCESS (node)
76+
77+
successors ← get_successors(node)
78+
for each successor in successors:
79+
successor.score ← evaluation_function(successor)
80+
all_successors.append(successor)
81+
82+
if all_successors is empty:
83+
return FAILURE
84+
85+
// Sort all successors by their scores (best first)
86+
sorted_successors ← sort(all_successors, by=score, descending=True)
87+
88+
// Keep only top beam_width candidates for next level
89+
current_level ← sorted_successors[0 : beam_width]
90+
depth ← depth + 1
91+
92+
// Check final level for goal
93+
for each node in current_level:
94+
if goal_test(node):
95+
return SUCCESS (node)
96+
97+
return FAILURE
98+
```
99+
100+
## Advantages and Disadvantages of Beam Search
62101

63102
As stated before, the advantage of BEAM search is that it is efficient both in time and memory. The disadvantage can be seen from the example in that a possible shortest path from **S** to **G** was overlooked. This can be somewhat corrected by varying the beam width to include more nodes. This, however, would reduce the efficiency of the algorithm. Selecting the optimal beam width is problem-specific and usually requires further insight into the problem.
64103

65104
## Applications of BEAM Search
66105

67106
The BEAM search algorithm is commonly used in natural language processing and machine translation. An encoder is used to process the text from the source language and BEAM search selects the most probable words (the beam width) in the target language. The evaluation function in this context is the conditional probability of a word in the target language.
107+
108+
## Frequently Asked Questions
109+
110+
### 1. Is ChatGPT using beam search?
111+
112+
No, ChatGPT (and most large language models from OpenAI) doesn't use beam search during inference. It uses sampling-based decoding methods like top-k sampling, top-p (nucleus) sampling, or temperature-controlled sampling to generate text.
113+
114+
### 2. Where is beam search used?
115+
116+
Beam search is widely used in natural language processing (NLP) tasks where sequential predictions are needed:
117+
118+
- Machine translation (e.g., translating English to French)
119+
- Speech recognition
120+
- Text generation (in some models)
121+
- Optical character recognition (OCR)
122+
123+
### 3. What are the benefits of beam search?
124+
125+
Beam search is faster and more memory-efficient than exhaustive search. It explores only the most promising paths, giving better results than greedy search while still being customizable through the beam width. However, it might miss the optimal path.
Lines changed: 103 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,95 +1,156 @@
11
---
22
Title: '.Substring()'
3-
Description: 'Returns the substring of a string instance starting at a given index.'
3+
Description: 'Extracts a portion of a string starting from a specified index position.'
44
Subjects:
5-
- 'Code Foundations'
65
- 'Computer Science'
6+
- 'Web Development'
77
Tags:
8+
- 'Data Types'
89
- 'Methods'
910
- 'Strings'
1011
CatalogContent:
1112
- 'learn-c-sharp'
1213
- 'paths/computer-science'
1314
---
1415

15-
The **`.Substring()`** method is a string method that returns a substring of a string starting at the specified index. It will return all characters from that index to the end unless a maximum length is specified. If the starting index equals the string length, it returns an empty string (`""`). If the index is greater than the string length, it throws an `ArgumentOutOfRangeException`.
16+
The C# **`.Substring()`** method is a built-in [string](https://www.codecademy.com/resources/docs/c-sharp/strings) method that extracts a portion of a string starting from a specified index position. It returns a new string containing the characters from the starting position to either the end of the string or for a specified length, without modifying the original string.
1617

17-
## Syntax
18+
## Syntax of C# `.Substring()`
1819

1920
```pseudo
20-
.Substring(int startIndex)
21+
public string Substring(int startIndex)
22+
public string Substring(int startIndex, int length)
2123
```
2224

23-
Or, alternatively:
25+
**Parameters:**
2426

25-
```pseudo
26-
.Substring(int startIndex, int length)
27-
```
27+
- `startIndex`: The zero-based starting position from where the substring begins. The type is `System.Int32`.
28+
- `length` (optional): The number of characters to include in the substring. The type is `System.Int32`.
29+
30+
**Return value:**
31+
32+
Both methods return a new string (`System.String`) containing the extracted substring.
2833

29-
- `startIndex`: The index from where the substring starts.
30-
- `Length` (Optional): The number of characters to include in the substring..
34+
**Exceptions:**
3135

32-
## Example
36+
The method throws `ArgumentOutOfRangeException` if:
3337

34-
In this example, `.Substring()` is used to return the substring of "Codecademy" starting at index `4` and includes all characters from that position to the end of the string:
38+
- `startIndex` is less than zero or greater than the length of the string
39+
- `length` is less than zero
40+
- `startIndex` plus `length` indicates a position not within the current string
41+
42+
## Example 1: Basic Usage of `.Substring()`
43+
44+
This example demonstrates how to use the `.Substring()` method with a single parameter to extract characters from a specific position to the end of the string:
3545

3646
```cs
3747
using System;
3848

3949
public class Program
4050
{
41-
public static void Main()
42-
{
43-
string str = "Codecademy";
44-
Console.WriteLine(str.Substring(4));
45-
}
51+
public static void Main()
52+
{
53+
string text = "Hello World";
54+
55+
// Extract substring from index 6 to the end
56+
string result = text.Substring(6);
57+
58+
Console.WriteLine($"Original: {text}");
59+
Console.WriteLine($"Substring from index 6: {result}");
60+
}
4661
}
4762
```
4863

49-
The above example results in the following output:
64+
The output of this example will be:
5065

5166
```shell
52-
cademy
67+
Original: Hello World
68+
Substring from index 6: World
5369
```
5470

55-
## Example 2
71+
This example extracts all characters starting from index 6 (the letter 'W') to the end of the string.
72+
73+
## Example 2: Extract Characters with Length Using `.Substring()`
5674

57-
In this example, `.Substring()` is used with the optional `length` parameter to return a substring of 6 characters starting from index `2` of the string `"Codecademy"`.
75+
This example shows how to use the `.Substring()` method with both parameters to extract a specific number of characters:
5876

5977
```cs
6078
using System;
6179

6280
public class Program
6381
{
64-
public static void Main()
65-
{
66-
string str = "Codecademy";
67-
Console.WriteLine(str.Substring(2, 6));
68-
}
82+
public static void Main()
83+
{
84+
string email = "user@example.com";
85+
86+
// Extract username (characters before @)
87+
int atIndex = email.IndexOf('@');
88+
string username = email.Substring(0, atIndex);
89+
90+
// Extract domain (characters after @)
91+
string domain = email.Substring(atIndex + 1);
92+
93+
Console.WriteLine($"Email: {email}");
94+
Console.WriteLine($"Username: {username}");
95+
Console.WriteLine($"Domain: {domain}");
96+
}
6997
}
7098
```
7199

72-
The above code generates the following output:
100+
The output of this code will be:
73101

74-
````shell
75-
decade
102+
```shell
103+
Email: user@example.com
104+
Username: user
105+
Domain: example.com
106+
```
107+
108+
The above example demonstrates extracting the username from an email address and getting a portion of the domain.
76109

77-
## Codebyte Example
110+
## Codebyte Example: Using C# `.Substring()` for File Path Processing
78111

79-
The below code demonstrates how to use the Substring method:
112+
This example shows a real-world scenario where `.Substring()` is used to process file paths and extract file information:
80113

81114
```codebyte/csharp
82115
using System;
83116
84-
public class Example
117+
public class Program
85118
{
86-
public static void Main(string[] args)
87-
{
88-
string Name1 = "Brad";
89-
string Name2 = "Angelina";
90-
91-
Console.WriteLine(Name1.Substring(1));
92-
Console.WriteLine(Name2.Substring(1));
93-
}
119+
public static void Main()
120+
{
121+
string filePath = "C:\\Documents\\Projects\\MyApplication.exe";
122+
123+
// Extract filename with extension
124+
int lastSlash = filePath.LastIndexOf('\\');
125+
string fileName = filePath.Substring(lastSlash + 1);
126+
127+
// Extract file extension
128+
int dotIndex = fileName.LastIndexOf('.');
129+
string extension = fileName.Substring(dotIndex + 1);
130+
131+
// Extract filename without extension
132+
string nameOnly = fileName.Substring(0, dotIndex);
133+
134+
Console.WriteLine($"Full path: {filePath}");
135+
Console.WriteLine($"Filename: {fileName}");
136+
Console.WriteLine($"Extension: {extension}");
137+
Console.WriteLine($"Name only: {nameOnly}");
138+
}
94139
}
95-
````
140+
```
141+
142+
This example processes a file path to extract different components.
143+
144+
## Frequently Asked Questions
145+
146+
### 1. What happens if I pass a negative index to `.Substring()`?
147+
148+
The method will throw an `ArgumentOutOfRangeException` if the `startIndex` is negative or greater than the string length.
149+
150+
### 2. Can `.Substring()` modify the original string?
151+
152+
No, `.Substring()` returns a new string and does not modify the original string, as strings are immutable in C#.
153+
154+
### 3. What's the difference between `.Substring()` and `Span<char>`?
155+
156+
`.Substring()` creates a new string object, while `Span<char>` provides a memory-efficient way to work with string segments without allocation.

0 commit comments

Comments
 (0)