Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Sqrt(n) | Problems
Binary Search in Python

book
Sqrt(n)

In this section, we will practice with the BS algorithm.

The first task will be to find the square root of the number.

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

Use hints if needed! Be careful with the tabulation!

Let's practice!

Завдання

Swipe to start coding

  1. Set condition if the x equals 0 or 1.
  2. Set the while loop to work while the left is lower or equals the right.
  3. Set condition if the square of the middle elements equals x.
  4. Set condition if the square of the middle elements is lower than x.
  5. Update the left. The left equals the middle + 1.
  6. Update the result. The result equals the middle.
  7. Update the right. The right equals the middle - 1.
  8. Test the function.

Рішення

def sqrt_binarySearch(x):
# Set condition if the 'x' equals 0 or 1
if (x == 0 or x == 1):
return x
left, right = 1, x
# Set the while loop to work while the 'left' is lower or equals the 'right'
while (left <= right):
middle = (left + right) // 2
# Set condition if the square of the middle elements equals 'x'
if (middle * middle == x):
return middle
# Set condition if the square of the middle elements is lower than 'x'
elif (middle * middle < x):
# Update the 'left'
left = middle + 1
# Update the 'result'
result = middle
else:
# Update the 'right'
right = middle - 1

return result

# Testing
x = 11
# Test the function with the 'x' variable
test = sqrt_binarySearch(x)
print(test)

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 1
single

single

def sqrt_binarySearch(x):
# Set condition if the 'x' equals 0 or 1
if (x == _ _ _ or _ _ _ == _ _ _):
return x
left, right = 1, x
# Set the while loop to work while the 'left' is lower or equals the 'right'
_ _ _ (_ _ _ <= _ _ _):
middle = (left + right) // 2
# Set condition if the square of the middle elements equals 'x'
if (_ _ _ == x):
return middle
# Set condition if the square of the middle elements is lower than 'x'
elif (_ _ _ < x):
# Update the 'left'
_ _ _ = middle + _ _ _
# Update the 'result'
result = _ _ _
else:
# Update the 'right'
right = _ _ _

return result

# Testing
x = 11
# Test the function with the 'x' variable
test = _ _ _(_ _ _)
print(test)

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

We use cookies to make your experience better!
some-alt