Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233341 unmodified line363738394041426 unmodified lines495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112# ============================================================# π Binary Search Game β Step-by-Step Interactive Gradio App# ============================================================# Author: Your Name# Course: CISC-121 (Intro to Computing Science)# Description:# Generates a random sorted list and performs binary search# step-by-step, showing each comparison and final result.# ============================================================import randomimport gradio as gr# ------------------------------------------------------------# Binary Search Logic (returns list, steps, and final result)# ------------------------------------------------------------def binary_search_visual(user_number):try:target = int(user_number)except ValueError:# Return blanks for all boxes if invalid inputreturn ("β οΈ Please enter a valid integer.",*["" for _ in range(8)],"β οΈ Invalid input.",)# Generate a random sorted list of 10 unique numbers (1β50)arr = sorted(random.sample(range(1, 50), 10))steps = []low, high = 0, len(arr) - 1found = False1 unmodified linewhile 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}")found = True6 unmodified lineshigh = mid - 1if not found:steps.append("β Number not found in the list.")# Pad to fill consistent 8 stepswhile len(steps) < 8:steps.append("")# Create a clear summary message for the last boxfinal_message = (f"β The number {target} was found!" if found else f"β The number {target} was not found.")# Return list display, all 8 steps, and final messagereturn f"Random Sorted List:\n{arr}", *steps[:8], final_message# ------------------------------------------------------------# Gradio Interface# ------------------------------------------------------------with gr.Blocks(title="Binary Search Game") as demo:gr.Markdown("""# π― Binary Search Game (Step-by-Step)Each time you click **Run**, a new sorted list of 10 random numbers (1β50) will be generated.Enter a number and watch **Binary Search** in action, step by step!""")# Input#show the generated listlist_box = gr.Textbox(label="Generated Sorted List", lines=2, interactive=False)user_number = gr.Number(label="Enter a number to search (1β50)", value=1, precision=0)run_button = gr.Button("Run Binary Search π")# Step-by-step outputsgr.Markdown("### πΉ Search Steps:")step_boxes = [gr.Textbox(label=f"Step {i+1}", lines=1, interactive=False) for i in range(8)]# Final result boxresult_box = gr.Textbox(label="Final Result", lines=1, interactive=False)# Button event linkingrun_button.click(fn=binary_search_visual,inputs=[user_number],outputs=[list_box, *step_boxes, result_box],)gr.Markdown("""---**How Binary Search Works:**1. The list must be sorted.2. Compare your target with the middle element.3. If smaller β search the left half. If larger β search the right.4. Repeat until the number is found or the range is empty.""")# Run app locally or deploy to Hugging Faceif __name__ == "__main__":demo.launch()12345678910111213141516171819202122232425262728293031323334353637383940414243441 unmodified line4647484950516 unmodified lines585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# ============================================================# π Binary Search Game β Two-Stage (Generate β Search)# ============================================================# Author: Your Name# Course: CISC-121# Description:# 1) Click "Generate List" to create a random sorted list.# 2) Enter a number and click "Run Binary Search".# UI shows the list, step-by-step decisions, and final result.# ============================================================import randomimport gradio as grMAX_STEPS = 8 # number of step boxes to show# -------------------------# Stage 1: Generate the list# -------------------------def generate_list():arr = sorted(random.sample(range(1, 50), 10)) # 10 unique ints in [1..49]display = f"Random Sorted List:\n{arr}"return display, arr# -------------------------# Stage 2: Run the search# -------------------------def binary_search_on_state(user_number, arr_state):# If user hasn't generated a list yetif not arr_state:list_msg = "β οΈ Please click 'Generate List' first."# Return list warning, blank steps, and final result messagereturn list_msg, *["" for _ in range(MAX_STEPS)], "β οΈ No list to search."# Validate inputtry:target = int(user_number)except (TypeError, ValueError):return f"Random Sorted List:\n{arr_state}", *["" for _ in range(MAX_STEPS)], "β οΈ Enter a valid integer."arr = arr_state[:] # copy for safetysteps = []low, high = 0, len(arr) - 1found = False1 unmodified linewhile 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}")found = True6 unmodified lineshigh = mid - 1if not found:steps.append(f"β The number {target} was not found.")# Pad steps to fill UI boxes consistentlywhile len(steps) < MAX_STEPS:steps.append("")final_msg = f"β The number {target} was found!" if found else f"β The number {target} was not found."list_display = f"Random Sorted List:\n{arr}"return list_display, *steps[:MAX_STEPS], final_msg# -------------------------# UI# -------------------------with gr.Blocks(title="Binary Search Game β Two-Stage") as demo:gr.Markdown("""# π― Binary Search Game β Two-Stage**Step 1:** Click **Generate List** to create a random sorted list (10 numbers in 1β49).**Step 2:** Enter a number and click **Run Binary Search** to see each step and the final result.""")# App state to hold the generated list across button clicksarr_state = gr.State([])with gr.Row():gen_btn = gr.Button("Generate List π²", variant="secondary")user_number = gr.Number(label="Enter a number to search (1β49)", value=1, precision=0)run_btn = gr.Button("Run Binary Search π", variant="primary")# List displaylist_box = gr.Textbox(label="Generated Sorted List", lines=2, interactive=False)# Step-by-step outputsgr.Markdown("### πΉ Search Steps")step_boxes = [gr.Textbox(label=f"Step {i+1}", lines=1, interactive=False) for i in range(MAX_STEPS)]# Final resultresult_box = gr.Textbox(label="Final Result", lines=1, interactive=False)# Wire up eventsgen_btn.click(fn=generate_list,inputs=[],outputs=[list_box, arr_state],)run_btn.click(fn=binary_search_on_state,inputs=[user_number, arr_state],outputs=[list_box, *step_boxes, result_box],)if __name__ == "__main__":demo.launch()
app.py+64-59