Rahatara commited on
Commit
90ad295
Β·
verified Β·
1 Parent(s): 5bf1c20

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -59
app.py CHANGED
@@ -1,34 +1,44 @@
1
  # ============================================================
2
- # πŸ” Binary Search Game β€” Step-by-Step Interactive Gradio App
3
  # ============================================================
4
  # Author: Your Name
5
- # Course: CISC-121 (Intro to Computing Science)
6
  # Description:
7
- # Generates a random sorted list and performs binary search
8
- # step-by-step, showing each comparison and final result.
 
9
  # ============================================================
10
 
11
  import random
12
  import gradio as gr
13
 
14
-
15
- # ------------------------------------------------------------
16
- # Binary Search Logic (returns list, steps, and final result)
17
- # ------------------------------------------------------------
18
- def binary_search_visual(user_number):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  try:
20
  target = int(user_number)
21
- except ValueError:
22
- # Return blanks for all boxes if invalid input
23
- return (
24
- "⚠️ Please enter a valid integer.",
25
- *["" for _ in range(8)],
26
- "⚠️ Invalid input.",
27
- )
28
-
29
- # Generate a random sorted list of 10 unique numbers (1–50)
30
- arr = sorted(random.sample(range(1, 50), 10))
31
 
 
32
  steps = []
33
  low, high = 0, len(arr) - 1
34
  found = False
@@ -36,7 +46,6 @@ def binary_search_visual(user_number):
36
  while low <= high:
37
  mid = (low + high) // 2
38
  steps.append(f"Checking middle index {mid} β†’ value {arr[mid]}")
39
-
40
  if arr[mid] == target:
41
  steps.append(f"βœ… Found {target} at index {mid}")
42
  found = True
@@ -49,64 +58,60 @@ def binary_search_visual(user_number):
49
  high = mid - 1
50
 
51
  if not found:
52
- steps.append("❌ Number not found in the list.")
53
 
54
- # Pad to fill consistent 8 steps
55
- while len(steps) < 8:
56
  steps.append("")
57
 
58
- # Create a clear summary message for the last box
59
- final_message = (
60
- f"βœ… The number {target} was found!" if found else f"❌ The number {target} was not found."
61
- )
62
 
63
- # Return list display, all 8 steps, and final message
64
- return f"Random Sorted List:\n{arr}", *steps[:8], final_message
65
 
66
 
67
- # ------------------------------------------------------------
68
- # Gradio Interface
69
- # ------------------------------------------------------------
70
- with gr.Blocks(title="Binary Search Game") as demo:
71
  gr.Markdown(
72
  """
73
- # 🎯 Binary Search Game (Step-by-Step)
74
- Each time you click **Run**, a new sorted list of 10 random numbers (1–50) will be generated.
75
- Enter a number and watch **Binary Search** in action, step by step!
76
  """
77
  )
78
 
79
- # Input
80
-
81
- #show the generated list
 
 
 
 
 
 
82
  list_box = gr.Textbox(label="Generated Sorted List", lines=2, interactive=False)
83
- user_number = gr.Number(label="Enter a number to search (1–50)", value=1, precision=0)
84
- run_button = gr.Button("Run Binary Search πŸ”Ž")
85
  # Step-by-step outputs
86
- gr.Markdown("### πŸ”Ή Search Steps:")
87
- step_boxes = [gr.Textbox(label=f"Step {i+1}", lines=1, interactive=False) for i in range(8)]
88
 
89
- # Final result box
90
  result_box = gr.Textbox(label="Final Result", lines=1, interactive=False)
91
 
92
- # Button event linking
93
- run_button.click(
94
- fn=binary_search_visual,
95
- inputs=[user_number],
96
- outputs=[list_box, *step_boxes, result_box],
97
  )
98
 
99
- gr.Markdown(
100
- """
101
- ---
102
- **How Binary Search Works:**
103
- 1. The list must be sorted.
104
- 2. Compare your target with the middle element.
105
- 3. If smaller β†’ search the left half. If larger β†’ search the right.
106
- 4. Repeat until the number is found or the range is empty.
107
- """
108
  )
109
 
110
- # Run app locally or deploy to Hugging Face
111
  if __name__ == "__main__":
112
  demo.launch()
 
1
  # ============================================================
2
+ # πŸ” Binary Search Game β€” Two-Stage (Generate β†’ Search)
3
  # ============================================================
4
  # Author: Your Name
5
+ # Course: CISC-121
6
  # Description:
7
+ # 1) Click "Generate List" to create a random sorted list.
8
+ # 2) Enter a number and click "Run Binary Search".
9
+ # UI shows the list, step-by-step decisions, and final result.
10
  # ============================================================
11
 
12
  import random
13
  import gradio as gr
14
 
15
+ MAX_STEPS = 8 # number of step boxes to show
16
+
17
+ # -------------------------
18
+ # Stage 1: Generate the list
19
+ # -------------------------
20
+ def generate_list():
21
+ arr = sorted(random.sample(range(1, 50), 10)) # 10 unique ints in [1..49]
22
+ display = f"Random Sorted List:\n{arr}"
23
+ return display, arr
24
+
25
+ # -------------------------
26
+ # Stage 2: Run the search
27
+ # -------------------------
28
+ def binary_search_on_state(user_number, arr_state):
29
+ # If user hasn't generated a list yet
30
+ if not arr_state:
31
+ list_msg = "⚠️ Please click 'Generate List' first."
32
+ # Return list warning, blank steps, and final result message
33
+ return list_msg, *["" for _ in range(MAX_STEPS)], "⚠️ No list to search."
34
+
35
+ # Validate input
36
  try:
37
  target = int(user_number)
38
+ except (TypeError, ValueError):
39
+ return f"Random Sorted List:\n{arr_state}", *["" for _ in range(MAX_STEPS)], "⚠️ Enter a valid integer."
 
 
 
 
 
 
 
 
40
 
41
+ arr = arr_state[:] # copy for safety
42
  steps = []
43
  low, high = 0, len(arr) - 1
44
  found = False
 
46
  while low <= high:
47
  mid = (low + high) // 2
48
  steps.append(f"Checking middle index {mid} β†’ value {arr[mid]}")
 
49
  if arr[mid] == target:
50
  steps.append(f"βœ… Found {target} at index {mid}")
51
  found = True
 
58
  high = mid - 1
59
 
60
  if not found:
61
+ steps.append(f"❌ The number {target} was not found.")
62
 
63
+ # Pad steps to fill UI boxes consistently
64
+ while len(steps) < MAX_STEPS:
65
  steps.append("")
66
 
67
+ final_msg = f"βœ… The number {target} was found!" if found else f"❌ The number {target} was not found."
68
+ list_display = f"Random Sorted List:\n{arr}"
 
 
69
 
70
+ return list_display, *steps[:MAX_STEPS], final_msg
 
71
 
72
 
73
+ # -------------------------
74
+ # UI
75
+ # -------------------------
76
+ with gr.Blocks(title="Binary Search Game β€” Two-Stage") as demo:
77
  gr.Markdown(
78
  """
79
+ # 🎯 Binary Search Game β€” Two-Stage
80
+ **Step 1:** Click **Generate List** to create a random sorted list (10 numbers in 1–49).
81
+ **Step 2:** Enter a number and click **Run Binary Search** to see each step and the final result.
82
  """
83
  )
84
 
85
+ # App state to hold the generated list across button clicks
86
+ arr_state = gr.State([])
87
+
88
+ with gr.Row():
89
+ gen_btn = gr.Button("Generate List 🎲", variant="secondary")
90
+ user_number = gr.Number(label="Enter a number to search (1–49)", value=1, precision=0)
91
+ run_btn = gr.Button("Run Binary Search πŸ”Ž", variant="primary")
92
+
93
+ # List display
94
  list_box = gr.Textbox(label="Generated Sorted List", lines=2, interactive=False)
95
+
 
96
  # Step-by-step outputs
97
+ gr.Markdown("### πŸ”Ή Search Steps")
98
+ step_boxes = [gr.Textbox(label=f"Step {i+1}", lines=1, interactive=False) for i in range(MAX_STEPS)]
99
 
100
+ # Final result
101
  result_box = gr.Textbox(label="Final Result", lines=1, interactive=False)
102
 
103
+ # Wire up events
104
+ gen_btn.click(
105
+ fn=generate_list,
106
+ inputs=[],
107
+ outputs=[list_box, arr_state],
108
  )
109
 
110
+ run_btn.click(
111
+ fn=binary_search_on_state,
112
+ inputs=[user_number, arr_state],
113
+ outputs=[list_box, *step_boxes, result_box],
 
 
 
 
 
114
  )
115
 
 
116
  if __name__ == "__main__":
117
  demo.launch()