Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192# ============================================================# π Binary Search Game (Interactive Gradio App)# ============================================================# Author: Your Name# Course: CISC-121 (Intro to Computing Science)# Description:# This app randomly generates a sorted list of numbers and# performs binary search on it based on the user's guess.# It shows each step of the search in the UI.# ============================================================import randomimport gradio as gr# ------------------------------------------------------------# Binary Search Function# ------------------------------------------------------------def binary_search_steps(arr, target):steps = []low, high = 0, len(arr) - 1steps.append(f"List: {arr}")steps.append(f"Searching for: {target}\n")while low <= high:mid = (low + high) // 2steps.append(f"πΉ Checking middle index {mid} (value {arr[mid]})")if arr[mid] == target:steps.append(f"β Found {target} at position {mid}!")return "\n".join(steps)elif arr[mid] < target:steps.append(f"{arr[mid]} is less than {target} β searching right half")low = mid + 1else:steps.append(f"{arr[mid]} is greater than {target} β searching left half")high = mid - 1steps.append("β Not found. Try again!")return "\n".join(steps)# ------------------------------------------------------------# Function to handle user interaction# ------------------------------------------------------------def play_binary_search(user_number):try:user_number = int(user_number)except ValueError:return "β οΈ Please enter a valid number."# Generate random sorted list of numbers (unique)arr = sorted(random.sample(range(1, 50), 10))result = binary_search_steps(arr, user_number)return result# ------------------------------------------------------------# Gradio Interface# ------------------------------------------------------------with gr.Blocks(title="Binary Search Game") as demo:gr.Markdown("""# π― Binary Search GameThe computer will randomly generate a sorted list of numbers (1β50).Try guessing a number (default: 1) and see how **binary search** works step by step!""")with gr.Row():user_number = gr.Number(label="Enter a number to search (1β50)", value=1, precision=0)output_box = gr.Textbox(label="Search Steps", lines=12, interactive=False)run_button = gr.Button("Run Binary Search π")run_button.click(play_binary_search, inputs=user_number, outputs=output_box)gr.Markdown("""---**How Binary Search Works:**1. Start with a sorted list.2. Compare your number to the middle element.3. If it's smaller, search the left half; if larger, search the right.4. Continue halving the range until the number is found or the list is empty.""")if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100# ============================================================# π Binary Search Game β Step-by-Step Interactive Gradio App# ============================================================# Author: Your Name# Course: CISC-121 (Intro to Computing Science)# Description:# This app generates a random sorted list of numbers and lets# the user guess a target value. Binary Search runs step-by-step,# showing the list separately from each search step.# ============================================================import randomimport gradio as gr# ------------------------------------------------------------# Binary Search (returns list + steps)# ------------------------------------------------------------def binary_search_visual(user_number):try:target = int(user_number)except ValueError:return "β οΈ Please enter a valid integer.", [], []# Generate a random sorted list of 10 unique numbers between 1β50arr = sorted(random.sample(range(1, 50), 10))steps = []low, high = 0, len(arr) - 1while low <= high:mid = (low + high) // 2steps.append(f"Checking middle index {mid} β value {arr[mid]}")if arr[mid] == target:steps.append(f"β Found {target} at index {mid}")breakelif arr[mid] < target:steps.append(f"{arr[mid]} is smaller β searching right half")low = mid + 1else:steps.append(f"{arr[mid]} is larger β searching left half")high = mid - 1if not any("β " in s for s in steps):steps.append("β Not found. Try again!")# Return values for displaylist_display = f"Random Sorted List:\n{arr}"step_texts = [gr.Textbox.update(value=step) for step in steps]# Fill remaining boxes with blanks to keep layout consistentwhile len(step_texts) < 8:step_texts.append(gr.Textbox.update(value=""))return list_display, *step_texts# ------------------------------------------------------------# Gradio Interface Layout# ------------------------------------------------------------with gr.Blocks(title="Binary Search Game") as demo:gr.Markdown("""# π― Binary Search Game (Step-by-Step)This app generates a **random sorted list (1β50)** each time.Enter a number and watch how **Binary Search** checks values step-by-step.""")# Input sectionuser_number = gr.Number(label="Enter a number to search (1β50)", value=1, precision=0)run_button = gr.Button("Run Binary Search π")# Output: show list in one boxlist_box = gr.Textbox(label="Generated Sorted List", lines=2, interactive=False)# Create separate boxes for each stepgr.Markdown("### πΉ Search Steps:")step_boxes = [gr.Textbox(label=f"Step {i+1}", lines=1, interactive=False) for i in range(8)]# Click eventrun_button.click(fn=binary_search_visual,inputs=user_number,outputs=[list_box, *step_boxes])gr.Markdown("""---**How it works:**1. Binary Search divides the list in half each time.2. Compares the middle element to your target.3. Moves left or right based on the result.4. Repeats until it finds your number or the range is empty.""")# Run appif __name__ == "__main__":demo.launch()
app.py+54-46