Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667681 unmodified line70717273747576777879808182# ============================================================# π§ 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) // 2steps.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 + 1else:steps.append(f"{mid} is too high. Searching lower...")high = mid - 1steps.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 GameTry 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)1 unmodified linegr.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()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677781 unmodified line80818283848586878889909192# ============================================================# π 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)1 unmodified linegr.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()
app.py+46-36