Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Balloons | Problems
Binary Search in Python

book
Balloons

Imagine you have this figure:

And you want to fill this figure with balloons!

If you have 3 balloons you will need 2 columns to fill them with balloons.

If you have 6 balloons you will need 3 columns to fill them with balloons.

If you have 7 balloons you will need 3 columns to fill them with balloons(in our problem).

Now we will implement the program, which will decide how many columns you need to locate the n number of ballons!

Look at the explanation of the task! How does it work?

Use hints if needed! Be careful with the tabulation!

Tehtävä

Swipe to start coding

  1. Set while loop to work while the left + 1 is lower than right.
  2. Set the middle variable. The middle equals the (left + right) // 2.
  3. Update the left. The left equals the middle.
  4. Update the right. The right equals the middle.

Ratkaisu

def balloons_binarySearch(left, right, n):
# Set while loop to work while the 'left + 1' is lower than 'right'
while left + 1 < right:
# Set the 'middle' variable
middle = (left + right) // 2
if middle * middle <= n * 2:
# Update the 'left'
left = middle
else:
# Update the 'right'
right = middle

return left if left * (left + 1) <= 2 * n else left - 1

# Testing
n = 10
print(balloons_binarySearch(0, n * 2, n))

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 4
def balloons_binarySearch(left, right, n):
# Set while loop to work while the 'left + 1' is lower than 'right'
while _ _ _:
# Set the 'middle' variable
_ _ _ = _ _ _
if middle * middle <= n * 2:
# Update the 'left'
_ _ _
else:
# Update the 'right'
_ _ _

return left if left * (left + 1) <= 2 * n else left - 1

# Testing
n = 10
print(balloons_binarySearch(0, n * 2, n))

Kysy tekoälyä

expand
ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

some-alt