Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines456789101112131415161718192021222324252627282930311 unmodified line3334353637382 unmodified lines414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485861 unmodified line8889909192939495969798991003 unmodified lines# 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) // 21 unmodified lineif 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")2 unmodified linessteps.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])1 unmodified line"""---**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()3 unmodified lines456789101112131415161718192021222324252627282930311 unmodified line333435363738392 unmodified lines42434445464748495051525354555657585960616263646566676869707172737475767778798081828384851 unmodified line878889909192939495969798993 unmodified lines# 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 in separate boxes.# ============================================================import randomimport gradio as gr# ------------------------------------------------------------# Binary Search Function# ------------------------------------------------------------def binary_search_visual(user_number):try:target = int(user_number)except ValueError:return "β οΈ Please enter a valid integer.", *["" for _ in range(8)]# 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) - 1found = Falsewhile low <= high:mid = (low + high) // 21 unmodified lineif 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")2 unmodified linessteps.append(f"{arr[mid]} is larger β searching left half")high = mid - 1if not found:steps.append("β Not found. Try again!")# Pad steps so each step textbox is filled consistentlywhile len(steps) < 8:steps.append("")# Return: one string for list, then 8 step stringsreturn f"Random Sorted List:\n{arr}", *steps[:8]# ------------------------------------------------------------# 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 see how **Binary Search** checks values step-by-step!""")# Inputuser_number = gr.Number(label="Enter a number to search (1β50)", value=1, precision=0)run_button = gr.Button("Run Binary Search π")# Output: list displaylist_box = gr.Textbox(label="Generated Sorted List", lines=2, interactive=False)# Step outputsgr.Markdown("### πΉ Search Steps:")step_boxes = [gr.Textbox(label=f"Step {i+1}", lines=1, interactive=False) for i in range(8)]# Link logicrun_button.click(fn=binary_search_visual,inputs=[user_number],outputs=[list_box, *step_boxes])1 unmodified line"""---**How it works:**1. Binary Search divides the sorted list into halves.2. It compares your number with the middle value.3. If smaller β searches left half. If larger β searches right half.4. Repeats until the number is found or range is empty.""")# Run the app locally or deploy to Hugging Faceif __name__ == "__main__":demo.launch()
app.py+25-26