فهرست مقاله
وقتی جستوجوی یک نامِ قطعه پاسخ نمیدهد، نخست باید بدانیم «بدون نتیجه» محصولِ کدام قرارداد است. در این درس، واژهنامهای ساختگی از نامهای کوتاه داریم و تمام مدخلهای داخلِ شعاعِ ویرایشیِ مشخص را میخواهیم. درخت BK روشِ کنارگذاشتنِ بعضی شاخهها را فراهم میکند؛ اما جایگزینکردنِ فاصلهٔ دقیقِ محور با علامتِ «بیشتر از حد» میتواند پاسخِ درست را پنهان کند. همین خطای ظریف را با شاهدِ دستی و مرجعِ مستقل بررسی میکنیم.
۱. قراردادِ فاصله و معنای نتیجهٔ خالی

هشت مدخل relay، delay، reply، rely، coil، code، node و mode داریم. برای پرسش rely و شعاعِ یک، پاسخِ کامل عبارت است از rely با فاصلهٔ صفر، سپس relay و reply با فاصلهٔ یک. ترتیبِ دو مدخلِ مساوی بر اساسِ رشتهٔ خام تعیین میشود. این نامها دادهٔ آزمایشاند؛ فراوانیِ واقعیِ کاربران، سندِ سازمانی یا ارتباطِ معنایی به آنها نسبت نمیدهیم.
تعریفِ فاصلهٔ لوناشتاین در NIST بر کمترین تعدادِ درج، حذف و جایگزینی تکیه دارد. هزینهٔ هر عمل را یک میگیریم؛ جابهجاییِ دو حرف، عملِ مستقلِ یکواحدی نیست. فاصلهٔ ab تا ba دو است. عددِ خروجی، شمارِ عمل است؛ زمان، بایت، احتمال و نمرهٔ معنایی نیست. برابری، تقارن و نامساویِ مثلثیِ همین فاصله برای حذفِ شاخهها لازماند.
درسِ نامزدهای فاصلهٔ ویرایشی همهٔ واژهها را میخواند و بیرونِ شعاع مقدارِ None میدهد. آن رابط برای قبول یا ردِ تکنامزد کافی است؛ مقدارِ None فاصلهٔ دقیق نیست. اینجا مسئلهٔ تازه، حفظِ پاسخ هنگامِ جستوجو در نمایهٔ شاخهای است. همچنین درختِ پیشوند و فراوانی مسیرِ آغازِ رشته را میپیماید؛ آن قرارداد با همسایگیِ ویرایشی فرق دارد.
۲. ساختِ درخت و بازهٔ مجازِ شاخهها

نخستین واژه محورِ ریشه میشود. برای درجِ هر واژه، فاصلهٔ دقیقش تا محور را محاسبه میکنیم؛ اگر شاخهای با آن عدد وجود داشت، پایین میرویم وگرنه شاخهٔ تازه میسازیم. بنابراین همهٔ واژههایی که واردِ شاخهٔ عددِ e از یک محور میشوند، نسبت به همان محور فاصلهٔ e دارند؛ این ویژگی فقط دربارهٔ فرزندِ مستقیم نیست. در گرههای پایینتر، تقسیمبندیِ تازهای نسبت به محورِ تازه انجام میشود.
برای پرسش، فاصلهٔ دقیق تا محور را d و شعاع را r بنامیم. اگر واژهای در شاخهٔ e پاسخِ معتبر باشد، نامساویِ مثلثی میگوید اختلافِ قدرمطلقِ e و d از r بیشتر نیست. پس فقط شاخههای بازهٔ بستهٔ d−r تا d+r لازماند. دو سرِ بازه داخلاند. منفیشدنِ کرانِ پایین اشکالی ندارد؛ برچسبِ شاخهها خودشان نامنفیاند.
این قاعده در پیادهسازیِ رسمیِ pybktree در نسخهٔ ثابتِ منبع نیز دیده میشود. کدِ آموزشیِ ما مستقل است: گرهها در آرایه، فرزندان با اندیس و پیمایش با پشته نگهداری میشوند. تابعِ فاصله قابل تعویض نیست تا یک شباهتِ نامتریک، بیصدا مبنای حذفِ شاخه شود. از ادعاهای کاراییِ README نتیجهای برای سامانهٔ خودمان نمیگیریم.
۳. شاهدِ خطا برای فاصلهٔ بریدهشده

فقط aaaa و bbbb را به همین ترتیب درج کنید؛ ریشه aaaa و برچسبِ شاخهٔ bbbb برابرِ چهار است. اکنون خودِ bbbb را با شعاعِ صفر میپرسیم. فاصلهٔ پرسش تا ریشه چهار است؛ بازهٔ مجاز فقط شاخهٔ چهار خواهد بود و پاسخِ دقیق پیدا میشود. دوربودنِ ریشه از پرسش، دوربودنِ همهٔ نوادگان را ثابت نمیکند.
حال تابعِ محدودشده برای فاصلهٔ بیرونِ شعاع None برگرداند و برنامهنویس آن را با r+1 جایگزین کند. اینجا عددِ ساختگی یک میشود؛ بازه فقط شاخهٔ یک را میخواند و bbbb گم میشود. جایگزینیِ «بیشتر از صفر» با فاصلهٔ دقیقِ یک مجاز نیست. برنامهٔ نهایی این مسیرِ غلط را استفاده نمیکند؛ فقط همان تصمیمِ نادرست را جدا محاسبه میکند تا شاهدِ منفی در خروجی ثبت شود.
مرزها نیز مهماند: برای محور aaa، فرزند abb، پرسش aab و شعاعِ یک، شاخهٔ دو دقیقاً روی کرانِ بالا است و نباید حذف شود. برای محور aaaa، فرزند aabb، پرسش abbb و شعاعِ یک، همان شاخهٔ دو روی کرانِ پایین قرار میگیرد. آزمونی که فقط پاسخهای نزدیکِ ریشه را بسنجد، ممکن است هر دو خطا را نبیند.
۴. کدِ کامل و مرجعِ مستقلِ گرافِ ویرایش

تابعِ radius_matches ظرفِ tuple دقیق با صفر تا سیودو واژهٔ یکتا میپذیرد. هر واژه، str دقیقِ ناتهی با حداکثر هشت نقطهٔ کد و فقط حروفِ کوچکِ انگلیسی است؛ پرسش میتواند تهی باشد. شعاع int دقیق از صفر تا دو است و bool و زیرکلاسها پذیرفته نمیشوند. تمامِ ورودی حتی برای واژهنامهٔ تهی اعتبارسنجی میشود. تابعِ exact_distance دو رشته در همین الفبا با امکانِ تهیبودن میگیرد.
این دامنه عمداً کوچک است؛ حروفِ انگلیسیِ مجاز هرکدام یک نقطهٔ کد دارند. برنامه پردازشِ زبانِ فارسی، نرمالسازی، خوشهٔ نویسهای، خطِ اتصال یا متنِ HTML را پیاده نمیکند. درخت در هر فراخوانی دوباره ساخته میشود؛ این انتخاب برای رابطِ آزمایشِ کامل است، نه پیشنهادِ معماریِ جستوجوی پرترافیک. کد با Python 3.14.5 و کتابخانهٔ استاندارد یک بار اجرا شده است.
"""Own bounded BK radius query; exact pivot distance, no NLP or speed claim."""
from collections import deque
from itertools import combinations, permutations, product
import json
import platform
MAX_TERMS = 32
MAX_POINTS = 8
MAX_RADIUS = 2
def _word(value, allow_empty):
if type(value) is not str:
raise TypeError("exact str required")
if len(value) > MAX_POINTS or (not value and not allow_empty):
raise ValueError("word length outside contract")
if any(not ('a' <= point <= 'z') for point in value):
raise ValueError("only lowercase ASCII letters are in this finite contract")
def _distance(a, b):
"""Exact unit-cost insertion/deletion/substitution, including distances > r."""
previous = list(range(len(b) + 1))
for i, left in enumerate(a, 1):
current = [i]
for j, right in enumerate(b, 1):
current.append(min(previous[j] + 1, current[j - 1] + 1,
previous[j - 1] + (left != right)))
previous = current
return previous[-1]
def exact_distance(a, b):
_word(a, allow_empty=True)
_word(b, allow_empty=True)
return _distance(a, b)
def _build(words):
"""Private valid-input builder: array indices, not nested node objects."""
nodes = []
for word in words:
if not nodes:
nodes.append([word, {}])
continue
cursor = 0
while True:
edge = _distance(word, nodes[cursor][0])
children = nodes[cursor][1]
if edge not in children:
children[edge] = len(nodes)
nodes.append([word, {}])
break
cursor = children[edge]
return nodes
def radius_matches(words, query, radius):
"""Rebuild a bounded vocabulary then return every (distance, word) match."""
if type(words) is not tuple:
raise TypeError("exact tuple vocabulary required")
if len(words) > MAX_TERMS:
raise ValueError("too many words")
seen = set()
for word in words:
_word(word, allow_empty=False)
if word in seen:
raise ValueError("duplicate word")
seen.add(word)
_word(query, allow_empty=True)
if type(radius) is not int:
raise TypeError("exact int radius required")
if not 0 <= radius <= MAX_RADIUS:
raise ValueError("radius outside contract")
nodes = _build(words)
stack = [0] if nodes else []
found = []
while stack:
cursor = stack.pop()
pivot, children = nodes[cursor]
d = _distance(pivot, query) # NEVER replace d with a capped sentinel.
if d <= radius:
found.append((d, pivot))
# Visit order is deterministic, but is not a ranking contract.
for edge in sorted(children, reverse=True):
if abs(edge - d) <= radius:
stack.append(children[edge])
return tuple(sorted(found))
def binary_edit_graph():
"""Independent finite oracle: literal one-edit edges, no DP recurrence."""
universe = tuple(''.join(bits) for n in range(4)
for bits in product('ab', repeat=n))
vertices = set(universe)
adjacency = {}
for word in universe:
neighbors = set()
for i in range(len(word)):
neighbors.add(word[:i] + word[i + 1:])
for letter in 'ab':
if letter != word[i]:
neighbors.add(word[:i] + letter + word[i + 1:])
for i in range(len(word) + 1):
for letter in 'ab':
neighbors.add(word[:i] + letter + word[i:])
adjacency[word] = neighbors & vertices
distances = {}
for start in universe:
lengths = {start: 0}
queue = deque([start])
while queue:
current = queue.popleft()
for neighbor in adjacency[current]:
if neighbor not in lengths:
lengths[neighbor] = lengths[current] + 1
queue.append(neighbor)
assert len(lengths) == len(universe)
distances[start] = lengths
return universe, distances
def _raises(category, function, *args):
try:
function(*args)
except category:
return True
return False
def run_example():
checks = {}
words = ('relay', 'delay', 'reply', 'rely', 'coil', 'code', 'node', 'mode')
hand = ((0, 'rely'), (1, 'relay'), (1, 'reply'))
checks['literal_engineering_fixture_and_distance_word_ties'] = (
radius_matches(words, 'rely', 1) == hand)
checks['exact_edit_operations_empty_and_transposition_not_one_edit'] = (
exact_distance('', 'aaa') == 3 and exact_distance('ab', 'ba') == 2
and exact_distance('cat', 'cut') == 1
and exact_distance('aaaa', 'bbbb') == 4
and exact_distance('relay', 'relay') == 0)
universe, graph = binary_edit_graph()
pair_count = 0
metric_ok = True
for a in universe:
for b in universe:
metric_ok &= exact_distance(a, b) == graph[a][b]
pair_count += 1
checks['independent_literal_edit_graph_all_225_pairs'] = (
bool(metric_ok) and pair_count == 225)
checks['finite_graph_metric_symmetry_identity_and_triangle'] = all(
graph[a][b] == graph[b][a] and ((graph[a][b] == 0) == (a == b))
and all(graph[a][c] <= graph[a][b] + graph[b][c] for c in universe)
for a in universe for b in universe)
queries = lexicons = 0
oracle_ok = True
for size in range(4):
for lexicon in combinations(universe[1:], size):
lexicons += 1
for query in universe:
for radius in range(3):
expected = tuple(sorted((graph[query][w], w) for w in lexicon
if graph[query][w] <= radius))
oracle_ok &= radius_matches(lexicon, query, radius) == expected
queries += 1
checks['all_subsets_up_to_three_words_vs_graph_scan_21150_queries'] = (
bool(oracle_ok) and lexicons == 470 and queries == 21150)
order_cases = 0
order_ok = True
order_words = ('a', 'ab', 'ba', 'bb', 'aba')
for lexicon in permutations(order_words):
for query in ('a', 'b', 'ab', 'ba', 'aba', 'bab'):
for radius in range(3):
expected = tuple(sorted((graph[query][w], w) for w in lexicon
if graph[query][w] <= radius))
order_ok &= radius_matches(lexicon, query, radius) == expected
order_cases += 1
checks['insertion_permutations_preserve_sorted_matches_2160_queries'] = (
bool(order_ok) and order_cases == 2160)
partition_ok = True
descendant_pairs = 0
for lexicon in (universe[1:], tuple(reversed(universe[1:]))):
nodes = _build(lexicon)
for pivot, children in nodes:
for edge, child in children.items():
pending = [child]
while pending:
cursor = pending.pop()
descendant, lower = nodes[cursor]
partition_ok &= graph[pivot][descendant] == edge
descendant_pairs += 1
pending.extend(lower.values())
checks['every_descendant_keeps_ancestor_edge_partition'] = (
bool(partition_ok) and descendant_pairs > 28)
checks['both_inclusive_triangle_window_endpoints_are_required'] = (
radius_matches(('aaa', 'abb'), 'aab', 1) == ((1, 'aaa'), (1, 'abb'))
and radius_matches(('aaaa', 'aabb'), 'abbb', 1) == ((1, 'aabb'),))
# Deliberately wrong local computation ONLY documents a negative witness.
root_distance, child_edge, r = 4, 4, 0
capped_result = None if root_distance > r else root_distance
wrong_pivot = r + 1 if capped_result is None else capped_result
checks['capped_pivot_false_negative_is_exhibited_not_used'] = (
radius_matches(('aaaa', 'bbbb'), 'bbbb', r) == ((0, 'bbbb'),)
and abs(child_edge - root_distance) <= r
and not (abs(child_edge - wrong_pivot) <= r))
checks['empty_lexicon_query_radius_zero_and_nested_match_sets'] = (
radius_matches((), '', 2) == ()
and radius_matches(('a', 'bbb'), '', 2) == ((1, 'a'),)
and radius_matches(words, 'rely', 0) == ((0, 'rely'),)
and set(radius_matches(words, 'rely', 0))
<= set(radius_matches(words, 'rely', 1))
<= set(radius_matches(words, 'rely', 2)))
class StrChild(str):
pass
class IntChild(int):
pass
class TupleChild(tuple):
pass
checks['strict_types_and_prevalidation_even_for_empty_vocabulary'] = (
all(_raises(TypeError, radius_matches, bad, 'a', 0)
for bad in ([], 'a', TupleChild(('a',))))
and all(_raises(TypeError, radius_matches, (bad,), 'a', 0)
for bad in (True, b'a', 1, StrChild('a')))
and all(_raises(TypeError, radius_matches, (), bad, 0)
for bad in (True, b'a', StrChild('a')))
and all(_raises(TypeError, radius_matches, (), 'a', bad)
for bad in (True, 1.0, '1', IntChild(1))))
checks['duplicates_alphabet_lengths_radius_and_count_rejected'] = (
_raises(ValueError, radius_matches, ('a', 'a'), 'a', 0)
and _raises(ValueError, radius_matches, ('',), '', 0)
and all(_raises(ValueError, radius_matches, (w,), 'a', 0)
for w in ('A', 'a b', 'a\x00', '\u00e9', 'a' * 9))
and all(_raises(ValueError, radius_matches, (), q, 0)
for q in ('A', 'a ' , 'a' * 9))
and all(_raises(ValueError, radius_matches, (), 'a', r)
for r in (-1, 3))
and _raises(ValueError, radius_matches, tuple('a' + chr(97 + i)
for i in range(26))
+ tuple('b' + chr(97 + i) for i in range(7)), 'a', 0))
largest = tuple(chr(97 + i // 26) + chr(97 + i % 26) for i in range(32))
before = tuple(words)
checks['inclusive_maxima_and_input_tuple_preservation'] = (
len(radius_matches(largest, '', 2)) == 32
and radius_matches(('a' * 8,), 'a' * 8, 2) == ((0, 'a' * 8),)
and exact_distance('a' * 8, 'b' * 8) == 8
and radius_matches(words, 'rely', 1) == hand and words == before)
assert all(type(ok) is bool and ok for ok in checks.values()), checks
return {
'runtime': {'python': platform.python_version(), 'dependencies': 'stdlib only'},
'contract': {'maximum_vocabulary': MAX_TERMS, 'maximum_codepoints': MAX_POINTS,
'radius_inclusive': [0, MAX_RADIUS],
'alphabet': 'exact lowercase ASCII a-z; query may be empty',
'metric': 'exact unit insertion deletion substitution count',
'ranking': 'distance ascending then raw word ascending',
'tree_rebuilt_per_query': True},
'fixture_words': words, 'fixture_query': 'rely', 'fixture_radius': 1,
'fixture_matches': radius_matches(words, 'rely', 1),
'capped_pivot_witness': {'root': 'aaaa', 'child_and_query': 'bbbb', 'radius': 0,
'exact_pivot_distance': 4, 'edge': 4,
'wrong_fallback_distance': wrong_pivot,
'correct_matches': radius_matches(('aaaa', 'bbbb'), 'bbbb', 0)},
'independent_graph_vertices': len(universe), 'independent_graph_pairs': pair_count,
'oracle_lexicons_inside_one_group': lexicons,
'oracle_queries_inside_one_group': queries,
'insertion_order_queries_inside_one_group': order_cases,
'descendant_partition_pairs_inside_one_group': descendant_pairs,
'checks': checks, 'check_count': len(checks), 'all_passed': True,
'limits': ['Finite exact raw-character reference only; no normalization or morphology',
'No timing, memory, balance, retrieval relevance or production measurement',
'No pybktree execution or copied library implementation',
'Invalid approximate metric callback is not part of this API']}
if __name__ == '__main__':
print(json.dumps(run_example(), ensure_ascii=False, indent=2))
مرجعِ مستقل از رابطهٔ برنامهنویسیِ پویا استفاده نمیکند. تمامِ پانزده رشتهٔ دودویی با طولِ صفر تا سه را رأس میگیرد و یالهای یک درج، حذف یا جایگزینی را صریح میسازد؛ سپس جستوجوی عرضی طولِ کوتاهترین مسیر را میدهد. برای این فاصله، مسیرِ بهینه میتواند از طولِ بزرگترِ دو انتها تجاوز نکند؛ بنابراین این گرافِ محدود برای همین زوجها کافی است. مقایسهٔ ۲۲۵ زوج یک گروهِ آزمون است، نه ۲۲۵ تأییدِ مستقل.
{
"runtime": {
"python": "3.14.5",
"dependencies": "stdlib only"
},
"contract": {
"maximum_vocabulary": 32,
"maximum_codepoints": 8,
"radius_inclusive": [
0,
2
],
"alphabet": "exact lowercase ASCII a-z; query may be empty",
"metric": "exact unit insertion deletion substitution count",
"ranking": "distance ascending then raw word ascending",
"tree_rebuilt_per_query": true
},
"fixture_words": [
"relay",
"delay",
"reply",
"rely",
"coil",
"code",
"node",
"mode"
],
"fixture_query": "rely",
"fixture_radius": 1,
"fixture_matches": [
[
0,
"rely"
],
[
1,
"relay"
],
[
1,
"reply"
]
],
"capped_pivot_witness": {
"root": "aaaa",
"child_and_query": "bbbb",
"radius": 0,
"exact_pivot_distance": 4,
"edge": 4,
"wrong_fallback_distance": 1,
"correct_matches": [
[
0,
"bbbb"
]
]
},
"independent_graph_vertices": 15,
"independent_graph_pairs": 225,
"oracle_lexicons_inside_one_group": 470,
"oracle_queries_inside_one_group": 21150,
"insertion_order_queries_inside_one_group": 2160,
"descendant_partition_pairs_inside_one_group": 58,
"checks": {
"literal_engineering_fixture_and_distance_word_ties": true,
"exact_edit_operations_empty_and_transposition_not_one_edit": true,
"independent_literal_edit_graph_all_225_pairs": true,
"finite_graph_metric_symmetry_identity_and_triangle": true,
"all_subsets_up_to_three_words_vs_graph_scan_21150_queries": true,
"insertion_permutations_preserve_sorted_matches_2160_queries": true,
"every_descendant_keeps_ancestor_edge_partition": true,
"both_inclusive_triangle_window_endpoints_are_required": true,
"capped_pivot_false_negative_is_exhibited_not_used": true,
"empty_lexicon_query_radius_zero_and_nested_match_sets": true,
"strict_types_and_prevalidation_even_for_empty_vocabulary": true,
"duplicates_alphabet_lengths_radius_and_count_rejected": true,
"inclusive_maxima_and_input_tuple_preservation": true
},
"check_count": 13,
"all_passed": true,
"limits": [
"Finite exact raw-character reference only; no normalization or morphology",
"No timing, memory, balance, retrieval relevance or production measurement",
"No pybktree execution or copied library implementation",
"Invalid approximate metric callback is not part of this API"
]
}
سیزده گروهِ نامدار موفقاند. مرجعِ گرافی برای ۴۷۰ زیرمجموعهٔ حداکثر سهواژهای و تمامِ پرسشها و شعاعهای مجاز، ۲۱۱۵۰ پاسخِ درخت را با پویشِ کامل مقایسه میکند. ۲۱۶۰ حالتِ ترتیبِ درج در گروهِ دیگری قرار دارند؛ تقسیمبندیِ نوادگان، دو مرزِ بازه، شاهدِ فاصلهٔ بریده و نوعهای نامعتبر هم جدا بررسی میشوند. شمارِ حالتهای حلقه، گروهِ تازه یا اجرای دوبارهٔ مقاله حساب نمیشود.
۵. چهار پرسش دربارهٔ مرزها و تفسیر

پرسش اول: با شعاعِ صفر چرا ریشهٔ دور را کافی نمیدانیم؟ پاسخ: خودِ ریشه رد میشود، اما فاصلهٔ چهارِ آن تا پرسش، شاخهٔ چهار را لازم میکند. در شاهدِ aaaa و bbbb، پاسخ bbbb با فاصلهٔ صفر است؛ علامتِ «دور» اطلاعاتِ انتخابِ شاخه را ندارد.
پرسش دوم: اگر ترتیبِ درج عوض شود، جواب عوض میشود؟ پاسخ: شکلِ درخت و ترتیبِ بازدید میتواند عوض شود، اما فهرستِ مرتبِ همهٔ تطابقها باید همان باشد. ترتیبِ نهایی، فاصلهٔ صعودی و سپس واژهٔ خامِ صعودی است. آزمونِ جایگشتها همین قرارداد را میسنجد، نه یکسانبودنِ ساختارها.
پرسش سوم: واژهٔ تکراری یا پرسشِ تهی چه میشود؟ پاسخ: تکرارِ مدخل خطا است و خودکار حذف نمیشود؛ پرسشِ تهی معتبر است. برای واژهنامهٔ a و bbb با شعاعِ دو، فقط a با فاصلهٔ یک برمیگردد. واژهنامهٔ تهی پس از اعتبارسنجی، پاسخِ تهی میدهد.
پرسش چهارم: خروجیِ خالی یا نامِ درخت، کیفیت و سرعت را ثابت میکند؟ پاسخ: خیر؛ خالی یعنی هیچ مدخلِ همین ورودی در شعاعِ تعریفشده نیست. درخت میتواند بخشِ بزرگی از مدخلها را ببیند؛ توازن و زمان و حافظه اندازهگیری نشدهاند. پروژهٔ pybktree نصب یا اجرا نشده و مقالهٔ اصلیِ تاریخی نیز مبنای ادعای خواندنِ متنِ کامل نیست. نتیجهٔ این تمرین، صحتِ قراردادِ محدود است، نه تضمینِ فهمِ پرسش یا کاراییِ محصول.
منابع و مطالعهٔ بیشتر
- NIST؛ تعریفِ فاصلهٔ لوناشتاین و عملیاتِ ویرایش
- pybktree؛ منبعِ رسمیِ ثابت و بازهٔ بستهٔ شاخهها
- pybktree؛ README رسمی، با کنارگذاشتنِ ادعاهای کارایی
بررسی منابع: ۲۸ مهر ۱۴۰۵. تحلیلها و پیشنهادهای اجرایی، جمعبندی نویسندهاند.

