Rahatara commited on
Commit
1a55a2e
Β·
verified Β·
1 Parent(s): 0104725

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -36
app.py CHANGED
@@ -1,68 +1,78 @@
1
  # ============================================================
2
- # 🧠 Binary Search Interactive App
3
  # ============================================================
4
- # Course: CISC-121 (Intro to Computing Science)
5
- # Project: Searching & Sorting Algorithms
6
  # Author: Your Name
 
7
  # Description:
8
- # This Gradio app demonstrates how Binary Search works
9
- # step-by-step in an interactive "guess the number" style game.
 
10
  # ============================================================
11
 
12
- import gradio as gr
13
  import random
 
14
 
15
- # --------------------------
16
- # Binary Search Logic
17
- # --------------------------
18
- def binary_search_game(target, low=1, high=100):
19
  steps = []
 
 
 
 
 
20
  while low <= high:
21
  mid = (low + high) // 2
22
- steps.append(f"Checking middle value: {mid}")
23
- if mid == target:
24
- steps.append(f"βœ… Found the number {target}!")
 
25
  return "\n".join(steps)
26
- elif mid < target:
27
- steps.append(f"{mid} is too low. Searching higher...")
 
28
  low = mid + 1
 
29
  else:
30
- steps.append(f"{mid} is too high. Searching lower...")
31
  high = mid - 1
32
- steps.append("❌ Number not found (out of range).")
 
33
  return "\n".join(steps)
34
 
35
 
36
- # --------------------------
37
- # Wrapper for Gradio
38
- # --------------------------
39
  def play_binary_search(user_number):
40
  try:
41
  user_number = int(user_number)
42
- if not (1 <= user_number <= 100):
43
- return "⚠️ Please choose a number between 1 and 100."
44
  except ValueError:
45
  return "⚠️ Please enter a valid number."
46
 
47
- result = binary_search_game(user_number)
 
 
 
48
  return result
49
 
50
 
51
- # --------------------------
52
  # Gradio Interface
53
- # --------------------------
54
- with gr.Blocks(title="Binary Search Simulator") as demo:
55
  gr.Markdown(
56
  """
57
- # πŸ” Binary Search Game
58
- Try to see how **Binary Search** finds your chosen number step by step!
59
- Pick any number between 1 and 100 and watch how the algorithm narrows down the range.
60
  """
61
  )
62
 
63
  with gr.Row():
64
- user_number = gr.Textbox(label="Enter a number (1–100)")
65
- output_box = gr.Textbox(label="Search Progress", lines=10)
66
 
67
  run_button = gr.Button("Run Binary Search πŸ”Ž")
68
  run_button.click(play_binary_search, inputs=user_number, outputs=output_box)
@@ -70,13 +80,13 @@ with gr.Blocks(title="Binary Search Simulator") as demo:
70
  gr.Markdown(
71
  """
72
  ---
73
- **How it works:**
74
- 1. Binary Search always checks the middle of the range.
75
- 2. If the guess is too high or too low, it halves the range again.
76
- 3. It continues until it finds your number!
 
77
  """
78
  )
79
 
80
- # Run app locally or on Hugging Face
81
  if __name__ == "__main__":
82
  demo.launch()
 
1
  # ============================================================
2
+ # πŸ” Binary Search Game (Interactive Gradio App)
3
  # ============================================================
 
 
4
  # Author: Your Name
5
+ # Course: CISC-121 (Intro to Computing Science)
6
  # Description:
7
+ # This app randomly generates a sorted list of numbers and
8
+ # performs binary search on it based on the user's guess.
9
+ # It shows each step of the search in the UI.
10
  # ============================================================
11
 
 
12
  import random
13
+ import gradio as gr
14
 
15
+ # ------------------------------------------------------------
16
+ # Binary Search Function
17
+ # ------------------------------------------------------------
18
+ def binary_search_steps(arr, target):
19
  steps = []
20
+ low, high = 0, len(arr) - 1
21
+
22
+ steps.append(f"List: {arr}")
23
+ steps.append(f"Searching for: {target}\n")
24
+
25
  while low <= high:
26
  mid = (low + high) // 2
27
+ steps.append(f"πŸ”Ή Checking middle index {mid} (value {arr[mid]})")
28
+
29
+ if arr[mid] == target:
30
+ steps.append(f"βœ… Found {target} at position {mid}!")
31
  return "\n".join(steps)
32
+
33
+ elif arr[mid] < target:
34
+ steps.append(f"{arr[mid]} is less than {target} β†’ searching right half")
35
  low = mid + 1
36
+
37
  else:
38
+ steps.append(f"{arr[mid]} is greater than {target} β†’ searching left half")
39
  high = mid - 1
40
+
41
+ steps.append("❌ Not found. Try again!")
42
  return "\n".join(steps)
43
 
44
 
45
+ # ------------------------------------------------------------
46
+ # Function to handle user interaction
47
+ # ------------------------------------------------------------
48
  def play_binary_search(user_number):
49
  try:
50
  user_number = int(user_number)
 
 
51
  except ValueError:
52
  return "⚠️ Please enter a valid number."
53
 
54
+ # Generate random sorted list of numbers (unique)
55
+ arr = sorted(random.sample(range(1, 50), 10))
56
+
57
+ result = binary_search_steps(arr, user_number)
58
  return result
59
 
60
 
61
+ # ------------------------------------------------------------
62
  # Gradio Interface
63
+ # ------------------------------------------------------------
64
+ with gr.Blocks(title="Binary Search Game") as demo:
65
  gr.Markdown(
66
  """
67
+ # 🎯 Binary Search Game
68
+ The computer will randomly generate a sorted list of numbers (1–50).
69
+ Try guessing a number (default: 1) and see how **binary search** works step by step!
70
  """
71
  )
72
 
73
  with gr.Row():
74
+ user_number = gr.Number(label="Enter a number to search (1–50)", value=1, precision=0)
75
+ output_box = gr.Textbox(label="Search Steps", lines=12, interactive=False)
76
 
77
  run_button = gr.Button("Run Binary Search πŸ”Ž")
78
  run_button.click(play_binary_search, inputs=user_number, outputs=output_box)
 
80
  gr.Markdown(
81
  """
82
  ---
83
+ **How Binary Search Works:**
84
+ 1. Start with a sorted list.
85
+ 2. Compare your number to the middle element.
86
+ 3. If it's smaller, search the left half; if larger, search the right.
87
+ 4. Continue halving the range until the number is found or the list is empty.
88
  """
89
  )
90
 
 
91
  if __name__ == "__main__":
92
  demo.launch()