Spaces:
Sleeping
Sleeping
Create app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# ============================================================# π§ Binary Search Interactive App# ============================================================# Course: CISC-121 (Intro to Computing Science)# Project: Searching & Sorting Algorithms# Author: Your Name# Description:# This Gradio app demonstrates how Binary Search works# step-by-step in an interactive "guess the number" style game.# ============================================================
import gradio as grimport random
# --------------------------# Binary Search Logic# --------------------------def binary_search_game(target, low=1, high=100): steps = [] while low <= high: mid = (low + high) // 2 steps.append(f"Checking middle value: {mid}") if mid == target: steps.append(f"β
Found the number {target}!") return "\n".join(steps) elif mid < target: steps.append(f"{mid} is too low. Searching higher...") low = mid + 1 else: steps.append(f"{mid} is too high. Searching lower...") high = mid - 1 steps.append("β Number not found (out of range).") return "\n".join(steps)
# --------------------------# Wrapper for Gradio# --------------------------def play_binary_search(user_number): try: user_number = int(user_number) if not (1 <= user_number <= 100): return "β οΈ Please choose a number between 1 and 100." except ValueError: return "β οΈ Please enter a valid number."
result = binary_search_game(user_number) return result
# --------------------------# Gradio Interface# --------------------------with gr.Blocks(title="Binary Search Simulator") as demo: gr.Markdown( """ # π Binary Search Game Try to see how **Binary Search** finds your chosen number step by step! Pick any number between 1 and 100 and watch how the algorithm narrows down the range. """ )
with gr.Row(): user_number = gr.Textbox(label="Enter a number (1β100)") output_box = gr.Textbox(label="Search Progress", lines=10)
run_button = gr.Button("Run Binary Search π") run_button.click(play_binary_search, inputs=user_number, outputs=output_box)
gr.Markdown( """ --- **How it works:** 1. Binary Search always checks the middle of the range. 2. If the guess is too high or too low, it halves the range again. 3. It continues until it finds your number! """ )
# Run app locally or on Hugging Faceif __name__ == "__main__": demo.launch()app.pyAdded+82