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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -17
app.py CHANGED
@@ -1,12 +1,16 @@
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
@@ -29,56 +33,81 @@ 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
45
 
 
 
 
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
 
 
52
  break
53
  elif arr[mid] < target:
54
- steps.append(f"{arr[mid]} is smaller β†’ searching right half")
55
  low = mid + 1
 
56
  else:
57
- steps.append(f"{arr[mid]} is larger β†’ searching left half")
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
 
@@ -93,10 +122,12 @@ with gr.Blocks(title="Binary Search Game β€” Two-Stage") as demo:
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
 
@@ -110,7 +141,7 @@ with gr.Blocks(title="Binary Search Game β€” Two-Stage") as demo:
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__":
 
1
  # ============================================================
2
+ # πŸ” Binary Search Game β€” Two-Stage with Remaining Range View
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:
10
+ # β€’ the list,
11
+ # β€’ per-step decision,
12
+ # β€’ per-step remaining range (selected half),
13
+ # β€’ final result.
14
  # ============================================================
15
 
16
  import random
 
33
  # If user hasn't generated a list yet
34
  if not arr_state:
35
  list_msg = "⚠️ Please click 'Generate List' first."
36
+ # Return list warning, blank step messages, blank ranges, and final result message
37
+ return (
38
+ list_msg,
39
+ *["" for _ in range(MAX_STEPS)], # step messages
40
+ *["" for _ in range(MAX_STEPS)], # range messages
41
+ "⚠️ No list to search."
42
+ )
43
 
44
  # Validate input
45
  try:
46
  target = int(user_number)
47
  except (TypeError, ValueError):
48
+ return (
49
+ f"Random Sorted List:\n{arr_state}",
50
+ *["" for _ in range(MAX_STEPS)],
51
+ *["" for _ in range(MAX_STEPS)],
52
+ "⚠️ Enter a valid integer."
53
+ )
54
 
55
  arr = arr_state[:] # copy for safety
56
  steps = []
57
+ ranges = []
58
  low, high = 0, len(arr) - 1
59
  found = False
60
 
61
+ # Record initial range before any check (optional but helpful)
62
+ ranges.append(f"Initial range [low={low}, high={high}] β†’ {arr[low:high+1]}")
63
+
64
  while low <= high:
65
  mid = (low + high) // 2
66
+ steps.append(f"Check middle index {mid} β†’ value {arr[mid]}")
67
+
68
  if arr[mid] == target:
69
  steps.append(f"βœ… Found {target} at index {mid}")
70
  found = True
71
+ # After finding, remaining range is just the match
72
+ ranges.append(f"Remaining range [low={mid}, high={mid}] β†’ [{arr[mid]}]")
73
  break
74
  elif arr[mid] < target:
 
75
  low = mid + 1
76
+ ranges.append(f"Move right β†’ new range [low={low}, high={high}] β†’ {arr[low:high+1] if low <= high else []}")
77
  else:
 
78
  high = mid - 1
79
+ ranges.append(f"Move left β†’ new range [low={low}, high={high}] β†’ {arr[low:high+1] if low <= high else []}")
80
 
81
  if not found:
82
  steps.append(f"❌ The number {target} was not found.")
83
 
84
+ # Pad to fill consistent UI boxes
85
  while len(steps) < MAX_STEPS:
86
  steps.append("")
87
+ while len(ranges) < MAX_STEPS:
88
+ ranges.append("")
89
 
90
  final_msg = f"βœ… The number {target} was found!" if found else f"❌ The number {target} was not found."
91
  list_display = f"Random Sorted List:\n{arr}"
92
 
93
+ # Return:
94
+ # 1 list box,
95
+ # MAX_STEPS step messages,
96
+ # MAX_STEPS range messages,
97
+ # 1 final result box
98
+ return list_display, *steps[:MAX_STEPS], *ranges[:MAX_STEPS], final_msg
99
 
100
 
101
  # -------------------------
102
  # UI
103
  # -------------------------
104
+ with gr.Blocks(title="Binary Search Game β€” Two-Stage + Range View") as demo:
105
  gr.Markdown(
106
  """
107
+ # 🎯 Binary Search Game β€” Two-Stage (with Remaining Range)
108
+ **Step 1:** Click **Generate List** (10 unique numbers in 1–49).
109
+ **Step 2:** Enter a number and click **Run Binary Search**.
110
+ See each decision and the *remaining range* after every step.
111
  """
112
  )
113
 
 
122
  # List display
123
  list_box = gr.Textbox(label="Generated Sorted List", lines=2, interactive=False)
124
 
125
+ gr.Markdown("### πŸ”Ή Search Steps (Decision Trace)")
 
126
  step_boxes = [gr.Textbox(label=f"Step {i+1}", lines=1, interactive=False) for i in range(MAX_STEPS)]
127
 
128
+ gr.Markdown("### πŸ”Έ Remaining Range After Each Step")
129
+ range_boxes = [gr.Textbox(label=f"Range {i+1}", lines=1, interactive=False) for i in range(MAX_STEPS)]
130
+
131
  # Final result
132
  result_box = gr.Textbox(label="Final Result", lines=1, interactive=False)
133
 
 
141
  run_btn.click(
142
  fn=binary_search_on_state,
143
  inputs=[user_number, arr_state],
144
+ outputs=[list_box, *step_boxes, *range_boxes, result_box],
145
  )
146
 
147
  if __name__ == "__main__":