二分搜索函数因比较计数器失效导致测试失败
测试失败详情
FAIL: test_small_all_common_comparisons (__main__.SmallTestsBinary) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/pg/Downloads/2023s2_cosc122_assignment1 (3)/student_files/tests.py", line 221, in test_small_all_common_comparisons self.comparisons_test(test_file) File "/Users/pg/Downloads/2023s2_cosc122_assignment1 (3)/student_files/tests.py", line 163, in comparisons_test super().comparisons_test(test_file_name, File "/Users/pg/Downloads/2023s2_cosc122_assignment1 (3)/student_files/tests.py", line 115, in comparisons_test self.assertIn(student_count, valid_count_range, message_if_wrong) AssertionError: 10 not found in range(38, 53) : 你的代码报告使用了10次Gene比较,但实际应满足38 <= 比较次数 < 53。
相关代码
from classes import GeneList def binary_search(arr, target): """二分搜索辅助函数""" left, right = 0, len(arr) - 1 while left <= right: middle = (left + right) // 2 if arr[middle] == target: return True, middle # 找到Gene,返回True和索引 elif arr[middle] < target: left = middle + 1 else: right = middle - 1 return False, None # 未找到Gene,返回False和None def binary_gene_match(first_genome, second_genome): comparisons = 0 common_genes = GeneList() for gene in first_genome: # 调用二分搜索辅助函数 found, _ = binary_search(second_genome, gene) if found: common_genes.append(gene) comparisons += 1 # 每找到一个基因就递增比较计数器 return common_genes, comparisons
问题分析
当前代码的comparisons计数器仅在成功匹配Gene时递增,未统计二分搜索过程中每次的基因比较操作,导致统计值远低于测试预期范围,引发测试断言错误。
修复方案
修改binary_search函数,让它追踪并返回搜索过程中的比较次数,再在主函数中累加每次搜索的计数:
from classes import GeneList def binary_search(arr, target): """二分搜索辅助函数,返回(是否找到, 索引, 比较次数)""" left, right = 0, len(arr) - 1 comparisons = 0 while left <= right: middle = (left + right) // 2 comparisons += 1 # 每次和目标基因比较都计数 if arr[middle] == target: return True, middle, comparisons elif arr[middle] < target: left = middle + 1 else: right = middle - 1 return False, None, comparisons def binary_gene_match(first_genome, second_genome): total_comparisons = 0 common_genes = GeneList() for gene in first_genome: # 获取搜索结果和本次搜索的比较次数 found, _, search_comparisons = binary_search(second_genome, gene) total_comparisons += search_comparisons # 累加所有搜索的比较次数 if found: common_genes.append(gene) return common_genes, total_comparisons
内容的提问来源于stack exchange,提问作者RBX neYeN
相关产品推荐
相关产品推荐

