You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调用二分查找(binary search)函数10次以获取绘图数据?

Solution: Call Binary Search 10 Times and Generate a Chart

Let's fix your code to implement the required functionality step by step:

1. Modify Binary Search to Track Steps

We'll update the binary_search function to count comparison steps—this gives meaningful data for the chart.

2. Execute 10 Binary Search Calls

Loop through each entry in your sorted dictionary to run a search for every value, collecting data points for plotting.

3. Fix the Graph Function

Correct typos and adjust parameters to properly visualize the collected data.

Corrected Full Code

import matplotlib.pyplot as plt
import operator

def binary_search(rodun, gildi):
    lo, hi = 0, len(rodun) - 1
    steps = 0
    while lo <= hi:
        steps += 1
        mid = (lo + hi) // 2
        if rodun[mid][1] < gildi:         
            lo = mid + 1
        elif gildi < rodun[mid][1]:      
            hi = mid - 1
        else:
            return mid, steps  # Return index and step count
    return -1, steps  # Fallback for non-existent values

def graph(x_labels, y_values):
    try:
        plt.close()
        fig, ax = plt.subplots(figsize=(8,4))
        ax.bar(x_labels, y_values)
        
        # Adjust axis limits for better visibility
        plt.xlim(-0.5, len(x_labels)-0.5)
        plt.ylim(0, max(y_values) + 1)
        
        # Add labels and title
        plt.xlabel('Words')
        plt.ylabel('Binary Search Steps')
        plt.title('Steps to Find Each Word via Binary Search')
        
        # Rotate x-axis labels to prevent overlap
        plt.xticks(rotation=45)
        plt.grid(axis='y')
        plt.tight_layout()
        plt.show()
    except Exception as e:
        print(f"Úps! {type(e).__name__} occurred: {str(e)}")
    return

def main():
    y1 = {'the':3460,'and':3192,'to':2384, 'of':1797, 'that': 1389,'was':1353,'a': 1253,
         'he': 1157,'in':995,'his':944}
    sorted_by_value_y1 = sorted(y1.items(), key=operator.itemgetter(1))      
    
    x_data = []  # Words for x-axis
    y_data = []  # Step counts for y-axis
    
    # Run binary search 10 times (once per entry)
    for word, count in sorted_by_value_y1:
        index, steps = binary_search(sorted_by_value_y1, count)
        x_data.append(word)
        y_data.append(steps)
        print(f"Searched for '{word}' (count: {count}) → Found at index {index} in {steps} steps")
    
    graph(x_data, y_data)

if __name__ == "__main__":
    main()
else:
    print("Er inporrterað. Ekki þetta main fall")

Key Changes Explained

  • Step Tracking: Added a steps counter in binary_search to measure how many comparisons each search requires.
  • 10 Search Executions: The loop over sorted_by_value_y1 (which contains exactly 10 entries) ensures we call binary_search 10 times, once for each word's count.
  • Graph Fixes:
    • Replaced invalid x_aslim/y_aslim with proper xlim/ylim calls.
    • Fixed bar plot parameters to use actual data labels and values.
    • Added axis labels, a title, and rotated x-axis labels for readability.
    • Improved error handling to display specific exception details.
  • Entry Point Fix: Corrected the __name__ check to properly run the main function when the script is executed directly.

Output

When you run the script:

  1. You'll see console output with each search's results.
  2. A bar chart will appear where each bar represents a word, and its height corresponds to the number of steps the binary search took to find that word's count in the sorted list.

内容的提问来源于stack exchange,提问作者halló

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 20:50:26