Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111216 unmodified lines29303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848 unmodified lines939495969798991001011027 unmodified lines110111112113114115116# ============================================================# π 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 random16 unmodified lines# 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 = Falsewhile 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 = Truebreakelif 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 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.""")8 unmodified lines# 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)7 unmodified linesrun_btn.click(fn=binary_search_on_state,inputs=[user_number, arr_state],outputs=[list_box, *step_boxes, result_box],)if __name__ == "__main__":1234567891011121314151616 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121138 unmodified lines1221231241251261271281291301311321337 unmodified lines141142143144145146147# ============================================================# π Binary Search Game β Two-Stage with Remaining Range View# ============================================================# 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,# β’ per-step decision,# β’ per-step remaining range (selected half),# β’ final result.# ============================================================import random16 unmodified lines# If user hasn't generated a list yetif not arr_state:list_msg = "β οΈ Please click 'Generate List' first."# Return list warning, blank step messages, blank ranges, and final result messagereturn (list_msg,*["" for _ in range(MAX_STEPS)], # step messages*["" for _ in range(MAX_STEPS)], # range messages"β οΈ 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)],*["" for _ in range(MAX_STEPS)],"β οΈ Enter a valid integer.")arr = arr_state[:] # copy for safetysteps = []ranges = []low, high = 0, len(arr) - 1found = False# Record initial range before any check (optional but helpful)ranges.append(f"Initial range [low={low}, high={high}] β {arr[low:high+1]}")while low <= high:mid = (low + high) // 2steps.append(f"Check middle index {mid} β value {arr[mid]}")if arr[mid] == target:steps.append(f"β Found {target} at index {mid}")found = True# After finding, remaining range is just the matchranges.append(f"Remaining range [low={mid}, high={mid}] β [{arr[mid]}]")breakelif arr[mid] < target:low = mid + 1ranges.append(f"Move right β new range [low={low}, high={high}] β {arr[low:high+1] if low <= high else []}")else:high = mid - 1ranges.append(f"Move left β new range [low={low}, high={high}] β {arr[low:high+1] if low <= high else []}")if not found:steps.append(f"β The number {target} was not found.")# Pad to fill consistent UI boxeswhile len(steps) < MAX_STEPS:steps.append("")while len(ranges) < MAX_STEPS:ranges.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:# 1 list box,# MAX_STEPS step messages,# MAX_STEPS range messages,# 1 final result boxreturn list_display, *steps[:MAX_STEPS], *ranges[:MAX_STEPS], final_msg# -------------------------# UI# -------------------------with gr.Blocks(title="Binary Search Game β Two-Stage + Range View") as demo:gr.Markdown("""# π― Binary Search Game β Two-Stage (with Remaining Range)**Step 1:** Click **Generate List** (10 unique numbers in 1β49).**Step 2:** Enter a number and click **Run Binary Search**.See each decision and the *remaining range* after every step.""")8 unmodified lines# List displaylist_box = gr.Textbox(label="Generated Sorted List", lines=2, interactive=False)gr.Markdown("### πΉ Search Steps (Decision Trace)")step_boxes = [gr.Textbox(label=f"Step {i+1}", lines=1, interactive=False) for i in range(MAX_STEPS)]gr.Markdown("### πΈ Remaining Range After Each Step")range_boxes = [gr.Textbox(label=f"Range {i+1}", lines=1, interactive=False) for i in range(MAX_STEPS)]# Final resultresult_box = gr.Textbox(label="Final Result", lines=1, interactive=False)7 unmodified linesrun_btn.click(fn=binary_search_on_state,inputs=[user_number, arr_state],outputs=[list_box, *step_boxes, *range_boxes, result_box],)if __name__ == "__main__":
app.py+48-17