Básicos del Lenguaje

1

Guía de instalación y conceptos básicos

2

Archivos y slides del curso práctico de Python

3

IMPORTANTE: Instalando Ubuntu Bash en Windows para facilitarte el seguimiento del curso desde Windows.

4

¿Qué es la programación?

5

¿Por qué programar con Python?

6

Operadores matemáticos

7

Variables y expresiones

8

Presentación del proyecto

9

Funciones

10

Usando funciones en nuestro proyecto

11

Operadores lógicos

12

Estructuras condicionales

Uso de strings y ciclos

13

Strings en Python

14

Operaciones con Strings en Python

15

Operaciones con strings y el comando Update

16

Operaciones con strings y el comando Delete

17

Operaciones con strings: Slices en python

18

For loops

19

While loops

20

Iterators and generators

Estructuras de Datos

21

Uso de listas

22

Operaciones con listas

23

Agregando listas a nuestro proyecto

24

Diccionarios

25

Agregando diccionarios a nuestro proyecto

26

Tuplas y conjuntos

27

Tuplas y conjuntos en código

28

Introducción al módulo collections

29

Python comprehensions

30

Búsquedas binarias

31

Continuando con las Búsquedas Binarias

32

Manipulación de archivos en Python 3

Uso de objetos y módulos

33

Decoradores

34

Decoradores en Python

35

¿Qué es la programación orientada a objetos?

36

Programación orientada a objetos en Python

37

Scopes and namespaces

38

Introducción a Click

39

Definición a la API pública

40

Clients

41

Servicios: Lógica de negocio de nuestra aplicación

42

Interface de create: Comunicación entre servicios y el cliente

43

Actualización de cliente

44

Interface de actualización

45

Manejo de errores y jerarquía de errores en Python

46

Context managers

Python en el mundo real

47

Aplicaciones de Python en el mundo real

Conclusiones finales

48

Python 2 vs 3 (Conclusiones)

Clases bonus

49

Entorno Virtual en Python y su importancia: Python en el mundo real

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Continuando con las Búsquedas Binarias

31/49
Recursos

Aportes 134

Preguntas 5

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

import random

def binary_search(data, target, low, high):
    while low <= high:
        mid = (low + high) // 2
        if target == data[mid]:
            return True
        elif target < data[mid]:
            high = mid - 1
        else:
            low = mid + 1




if __name__ == '__main__':

    data = [random.randint(0, 100) for i in range(10)]
    data.sort()
    print(data)
    target = int(input('What number would you like to find?'))
    found = binary_search(data, target, 0, len(data)-1)
    if found == True:
        print('The number: {} is in the list'. format(target))
    else:
        print('The number: {} is not in the list'.format(target))```

Hola comunidad, les comento que al hacer este ejercicio me pasó de estar por una hora sin entender por qué la siguiente función recursiva no me retornaba el resultado correcto. El resultado era “None”.
Luego al compararlo con el código del profesor, me di cuenta que faltaba el “return” en el elif y el else. Comparto esto para tenerlo en cuenta a la hora de hacer funciones recursivas

def find_number(numbers, search, low, high):
	if low > high:
		return False

	middle = (low + high) // 2	

	if numbers[middle] == search:
		return True
	elif numbers[middle] > search:
		find_number(numbers, search, low, (middle - 1))
	else:
		find_number(numbers, search, (middle + 1), high)

Comparto mi solución iterativa a la búsqueda binaria

def binary_search_iterative(data, target, low, high):	
	while low<=high:
	    mid = (low + high)//2
	    if data[mid] == target:
	        return True
	    else:
	        if target < data[mid]:
	            high = mid-1
	        else:
	            low = mid+1
	
	return False

Aquí esta mi aporte si no entienden lo de Binary Search lo que tienen que hacer es

  1. Establecer “L” a 0 y “H” a la longitud del array - 1 (n - 1)
  2. si “L” > “R”, significa que debemos retornar False
  3. Establecer “m” como la mitad de (L + R) / 2 la división debe ser entera (sin decimales)
  4. Si Data[m] < Target, ahora L es igual a m + 1 y debemos volver al paso 2
  5. Si Data[m] > Target, ahora H es igual a m - 1 y debemos volver al paso 2
  6. Ahora si Target = Data[m] retornamos True
import random

def binary_search(data, target, low, high):
    
    while low <= high:
        
        if low > high:
            return False

        mid = (low + high) // 2

        if target == data[mid]:
            return True
        elif data[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
            

    return False

if __name__ == '__main__':
    data = [random.randint(1, 100) for i in range(10)]
    data.sort()
    print(data)

    target = int(input('Ingresa el número a adivinar? '))

    found = binary_search(data, target, 0, len(data) - 1)

    print(found)
def f(data,target):
  lo = 0
  hi = len(data)
  while hi - lo > 1:
    mid = (lo + hi) // 2
    if data[mid] > target: hi = mid
    else: lo = mid
  return data[lo] == target
def bin_search(data, target, low, high):
    found = True
    while(found==True):
        mid = (low + high) // 2 
        if low > high:
            return False
        elif target == data[mid]:
            found = False
            return True
        elif target < data[mid]:
            high = mid -1
        else:
            low = mid + 1```

Solución con un for

import random

def loop_search(target, data):
    found = False
    
    for i in data:
        if i == target:
            found = True

    return found


if __name__ == '__main__':
    data = [random.randint(0, 100) for i in range(20)]
    data.sort()
    print(data)

    target = int(input('What number would you like to find? '))

    found = loop_search(target, data)

    print(found)

Reto:

import random

def binary_search(data,target): # low_idx indice y high_idx indice mayor de la lista
    low_idx = 0
    high_idx= len(data)-1
    solve = False
    while  low_idx <= high_idx:
        mid = (low_idx + high_idx)//2
        if target == data[mid]:
            solve = True
            break
        else:
            if target < data[mid]:
                high_idx = mid -1
            elif target > data[mid]:
                low_idx = mid + 1
    return solve

if __name__ =='__main__':

    data = [random.randint(0,10) for _ in range(10)]
    data.sort()
    print(data)
    target = int(input('What number would you like to find? '))
    found = binary_search(data,target)
    print(found)

Mi solución, solo un detalle tenía y es que en ciertas ocasiones enviaba False a pesar de estar el elemento, pero solo es colocar mayor o igual o menor igual(depende de como se realice) y se soluciona el problema

import random


def binary_search(data, target, low, high):
    if low > high:
        return False
    
    mid = (low + high) // 2
    
    if target == data[mid]:
        return True
    elif target < data[mid]:
        return binary_search(data, target, low, mid - 1)
    else:
        return binary_search(data, target, mid + 1, high)


def binary_search_with_while(data, target):
    low = 0
    high = len(data) - 1
    while low <= high:
        mid = (low + high) // 2
        if target == data[mid]:
            return True
        elif target >= data[mid]:
            low = mid + 1
        else:
            high = mid - 1
    return False


if __name__ == '__main__':
    data = [random.randint(0,100) for i in range(10)]
    
    data.sort()
    
    print(data)
    
    target = int(input("What number would you like to find? "))
    #found = binary_search(data, target, 0, len(data) - 1)
    found = binary_search_with_while(data, target)
    
    print(found, target)```

Reto:

from random import randint

def binary_search(list: list, objective: int, start: int, final: int):
    sorted_list = sorted(list)    

    while start <= final:
        mid = (start + final) // 2
        if objective > sorted_list[mid]:
            start = mid + 1
        elif objective < sorted_list[mid]:
            final = mid - 1
        elif objective == sorted_list[mid]:
            return 1
    else:
        return 0

if __name__ == '__main__':
    #test example
    list = [randint(0,20) for _ in range(0, 10)]
    print(bool(binary_search(list, 15, 0, len(list))))

Que hermosa es la recurtion

Asi me quedo a mi 😃

Este es mi código del reto, agradezco a toda la comunidad porque me apoyé del código de todos y no me acuerdo de quién lo tomé exactamente xD. (Sí, al final lo hice yo solo, aunque sí me ayudaron).

import random

def binarySearch(d, t, s, e):
    x = False
    m = 0

    if s > e:
        x = False

    while s <= e:
        m = (s + e) // 2

        if t == d[m]:
            x = True
            return m
            break
        elif t < d[m]:
            e = m - 1
        else:
            s = m + 1

    return x



if __name__ == '__main__':
    """data = [random.randint(0, 100) for i in range(10)]"""
    d = []

    for i in range(10):
        d.append(random.randint(0, 100))

    d.sort()
    print(d)

    t = int(input("Number: "))
    found = binarySearch(d, t, 0, len(d) - 1)
    print("{} number is at {} position".format(t, found))

hi comunidad, aquí mi solución!

<

def binary_search(data, target):
    low, hight = 0, len(data) -1

    while low <= hight:
        mid = (low + hight) // 2

        if target == data[mid]:
            return True
            break
        elif target < data[mid]:
            hight = mid -1
        else:
            low = mid +1

    return False

>

Mi solucion:

import random

def binary_search(data, target, low, higth):
    mid = (low + higth) // 2
    #print(mid)
    ok = True

    while ok:
        if low > higth:
            ok = False
            return False

        if target == data[mid]:
            ok = False
            return True
        elif target < data[mid]:
            higth = mid - 1
        else:
            low = mid + 1        
        mid = (low + higth) // 2
        #print(mid)

    return False

if __name__ == '__main__':
    data = [random.randint(0, 100) for i in range(10)]
    data.sort()
    print(data)

    target = int(input('What number would you like to find? '))
    found = binary_search(data, target, 0, len(data) - 1)
    print(found)

def binary_search_without_recursion(data, target, low, high):
    while low <= high:
        mid = (low + high) // 2

        if target == data[mid]:
            return True
        elif target < data[mid]:
            high = mid - 1
        else :
            low = mid + 1 
    return False

Encontré este algoritmo un poco más sencillo de ver, por si a alguien le funciona.

def busquedaBinaria(unaLista, item):
	    primero = 0
	    ultimo = len(unaLista)-1
	    encontrado = False
	
	    while primero<=ultimo and not encontrado:
	        puntoMedio = (primero + ultimo)//2
	        if unaLista[puntoMedio] == item:
	            encontrado = True
	        else:
	            if item < unaLista[puntoMedio]:
	                ultimo = puntoMedio-1
	            else:
	                primero = puntoMedio+1
	
	    return encontrado

Esta es mi solución usando loops, como la ven?

import random


def binary_search(number_list):
    found = False
    low, high = 0, len(number_list) - 1
    mid = (low + high) // 2
    target = int(input('What number would you like to find?: '))

    while not found:
        if mid <= low or mid >= high:
            print('El número NO se encuentra en la lista.')
            break
        if target == number_list[mid]:
            found = True
        elif target < number_list[mid]:
            mid = (low + mid - 1) // 2
        elif target > number_list[mid]:
            mid = (mid + high + 1) // 2

    if found:
        print('El número si se encuentra en la lista.')


if __name__ == '__main__':
    number_list = [random.randint(1, 21) for i in range(21)]
    number_list.sort()
    print(number_list)
    binary_search(number_list)

Mi solución al reto:

import random


def binarySearch(data, target):
    data = sorted(data)
    min, max = 0, len(data) - 1

    while min <= max:
        actual_index = (min + max) // 2

        if target == data[actual_index]:
            return True
        elif target < data[actual_index]:
            max = actual_index - 1
        else:
            min = actual_index + 1
    return False


if __name__ == '__main__':
    random_numbers = [random.randint(0, 100) for i in range(20)]

    print(random_numbers)

    found = binarySearch(random_numbers, int(input('What number would you like to found? ')))

    print(found)
<code>
import random



def binary_search(n_list, obj, low, high):
    if low > high:
        return False

    for n in n_list:
        mid = (low + high) // 2
        if obj == n_list[mid]:
            return True

        elif obj < n_list[mid]:
            high = mid - 1 
            
        else:
            low = mid + 1
            
    


if __name__ == "__main__":
    n_list = [random.randint(0,100) for n in range(20)]
    n_list.sort()

    print(n_list)

    obj = int(input('Number to find: '))

    found = binary_search(n_list, obj, 0, len(n_list)-1)
    
    if found:
        print(f'I Found the number {obj}!')

    else:
        print(f'I don\'t found the number {obj}')

Aqui mi versión


def busqueda_binaria(data, target, low, high):
    while True:
        if low > high:
            return False
        mid = (low + high) /2
        mid = int(mid)

        if target == data[mid]:
            return True
        elif target < data[mid]:
            high = mid -1
        else:
            low = mid +1

Esta es la solución que encontré sin usar recursividad:

import random

def binary_search(sorted_data, target, low_index, high_index):
    status = False

    if low_index > high_index:
        return status

    while not low_index > high_index:
        mid_index = (low_index + high_index) // 2

        if target == sorted_data[mid_index]:
            status = True
            return (status, mid_index)
        elif target < sorted_data[mid_index]:
            low_index = low_index
            high_index = mid_index - 1
            continue
        elif target > sorted_data[mid_index]:
            low_index = mid_index + 1
            high_index = high_index
            continue

    return status
        

if __name__ == "__main__":
    data = [random.randint(0,100) for i in range(10)]
    print(f'Data: {data}')
    
    sorted_data = sorted(data)
    print(f'Sorted data: {sorted_data}')

    target = int(input('What number would you like to find? '))
    found = binary_search(sorted_data, target, 0, len(sorted_data) - 1)

    print(found)
    ```

También le agregué que retorne la posición donde está el elemento que se busca. Maneja una variable status que es la que se retorna con True o False si se encontró o no el elemento. :D
```js import random def busqueda_binaria(arreglo, objetivo): arreglo = sorted(arreglo) minimo = 0 maximo = len(arreglo) while minimo < maximo: # Revisa el elemento en la mitad de min y max mitad = (maximo + minimo) // 2 val = arreglo[mitad] if val == objetivo: # Encontramos el objetivo print("Número encontrado en la posición") return mitad elif objetivo < val: # En este caso, buscamos los elementos # a la izquierda del objetivo maximo = mitad elif objetivo > val: # Esta línea es para evitar un bucle infinito if minimo == mitad: break # El objetivo es más que el valor de la mitad, # entonces seguimos buscando con los elementos # a la derecha minimo = mitad # No encontramos el objetivo return "Número no Encontrado" # Genera una lista de 50 números aleatorios únicos entre 1 y 200 arreglo = random.sample(range(1, 200), 50) arreglo_ordenado=sorted(arreglo) print(arreglo_ordenado) print(busqueda_binaria(arreglo, 3)) ```import random def busqueda\_binaria(arreglo, objetivo):    arreglo =  sorted(arreglo)    minimo = 0    maximo = len(arreglo)     while minimo < maximo:        # Revisa el elemento en la mitad de min y max        mitad = (maximo + minimo) // 2        val = arreglo\[mitad]         if val == objetivo:            # Encontramos el objetivo            print("Número encontrado en la posición")            return mitad        elif objetivo < val:            # En este caso, buscamos los elementos            # a la izquierda del objetivo            maximo = mitad        elif objetivo > val:            # Esta línea es para evitar un bucle infinito            if minimo == mitad:                break            # El objetivo es más que el valor de la mitad,            # entonces seguimos buscando con los elementos            # a la derecha            minimo = mitad     # No encontramos el objetivo    return "Número no Encontrado" \# Genera una lista de 50 números aleatorios únicos entre 1 y 200arreglo = random.sample(range(1, 200), 50)arreglo\_ordenado=sorted(arreglo)print(arreglo\_ordenado)print(busqueda\_binaria(arreglo, 3))
```python nums = [5, 19, 10, 2, 9, 4, 14, 15, 16, 3] order_nums = sorted(nums) print(order_nums) def binary_search(arr, num_interest): xi = 0 xf = len(arr) - 1 while xi <= xf: mitad = xi +( xf - xi )// 2 print(mitad) if num_interest == arr[mitad]: return mitad elif num_interest > arr[mitad]: xi = mitad + 1 elif num_interest < arr[mitad]: xf = mitad - 1 elemento = binary_search(order_nums, 19) print(f'Tu numero esta en la posición {elemento}') ```
```js nums = [5, 19, 10, 2, 9, 4, 14, 15, 16, 3] order_nums = sorted(nums) print(order_nums) def binary_search(arr, num_interest): xi = 0 xf = len(arr) - 1 while xi <= xf: mitad = xi +( xf - xi )// 2 print(mitad) if num_interest == arr[mitad]: return mitad elif num_interest > arr[mitad]: xi = mitad + 1 elif num_interest < arr[mitad]: xf = mitad - 1 elemento = binary_search(order_nums, 19) print(f'Tu numero esta en la posición {elemento}') ```nums = \[5, 19, 10, 2, 9, 4, 14, 15, 16, 3] order\_nums = sorted(nums) print(order\_nums) def binary\_search(arr, num\_interest): xi = 0 xf = len(arr) - 1 while xi <= xf: mitad = xi +( xf - xi )// 2 print(mitad) if num\_interest == arr\[mitad]: return mitad elif num\_interest > arr\[mitad]: xi = mitad + 1 elif num\_interest < arr\[mitad]: xf = mitad - 1 elemento = binary\_search(order\_nums, 19) print(f'Tu numero esta en la posición {elemento}')
Solución: ```js nums = [5, 19, 10, 2, 9, 4, 14, 15, 16, 3] order_nums = sorted(nums) print(order_nums) def binary_search(arr, num_interest): xi = 0 xf = len(arr) - 1 while xi <= xf: mitad = xi +( xf - xi )// 2 print(mitad) if num_interest == arr[mitad]: return mitad elif num_interest > arr[mitad]: xi = mitad + 1 elif num_interest < arr[mitad]: xf = mitad - 1 elemento = binary_search(order_nums, 19) print(f'Tu numero esta en la posición {elemento}') ```nums = \[5, 19, 10, 2, 9, 4, 14, 15, 16, 3] order\_nums = sorted(nums) print(order\_nums) def binary\_search(arr, num\_interest): xi = 0 xf = len(arr) - 1 while xi <= xf: mitad = xi +( xf - xi )// 2 print(mitad) if num\_interest == arr\[mitad]: return mitad elif num\_interest > arr\[mitad]: xi = mitad + 1 elif num\_interest < arr\[mitad]: xf = mitad - 1 elemento = binary\_search(order\_nums, 19) print(f'Tu numero esta en la posición {elemento}')
Comparto la forma, según orientación del profe:import random def binary\_search(data, target):    low = 0    high = len(data) - 1     while low <= high:        mid = (low + high) // 2         if target == data\[mid]:            return True        elif target < data\[mid]:            high = mid - 1        else:            low = mid + 1     return False if \_\_name\_\_ == '\_\_main\_\_':    data = \[random.randint(0,100) for \_ in range(10)]     data.sort()     print(data)     target = int(input('What is the number to search?: '))    found = binary\_search(data, target)     print(found) ```js import random def binary_search(data, target): low = 0 high = len(data) - 1 while low <= high: mid = (low + high) // 2 if target == data[mid]: return True elif target < data[mid]: high = mid - 1 else: low = mid + 1 return False if __name__ == '__main__': data = [random.randint(0,100) for _ in range(10)] data.sort() print(data) target = int(input('What is the number to search?: ')) found = binary_search(data, target) print(found) ```
Como decirlo? el código es hermoso y se entiende fácil cuando se va paso por paso, pero creo que si me ponen a hacerlo a mi no se cuando lo termine. Que Pro David.
```python import random def binary_search_iterative(data, target): low, high = 0, len(data) - 1 while low <= high: mid = (low + high) // 2 if target == data[mid]: return True elif target < data[mid]: high = mid - 1 else: low = mid + 1 return False if __name__ == '__main__': data = [random.randint(0, 100) for _ in range(100)] data.sort() print(data) target = int(input("¿Qué número te gustaría encontrar? ")) found = binary_search_iterative(data, target) print(found) ``````js ``` import random def binary\_search\_iterative(data, target): low, high = 0, len(data) - 1 while low <= high: mid = (low + high) // 2 if target == data\[mid]: return True elif target < data\[mid]: high = mid - 1 else: low = mid + 1 return False if \_\_name\_\_ == '\_\_main\_\_': data = \[random.randint(0, 100) for \_ in range(100)] data.sort() print(data) target = int(input("¿Qué número te gustaría encontrar? ")) found = binary\_search\_iterative(data, target) print(found)
```js import random if __name__ == '__main__': data = [random.randint(0,100) for i in range (10)] # generate (10 times) random number from 0 to 100 data.sort() #order the number from least to greatest print(data) #variables target = int (input ('What number would you like to find?')) found = False # Variable para rastrear si se encuentra el número for number in data: if number == target: found = True break # Imprimir el resultado if found: print(f'The number {target} was found in the list.') else: print(f'The number {target} was not found in the list.') ```
```python import random if __name__ == '__main__': data = [random.randint(0,100) for i in range (10)] # generate (10 times) random number from 0 to 100 data.sort() #order the number from least to greatest print(data) #variables target = int (input ('What number would you like to find?')) found = False # Variable para rastrear si se encuentra el número for number in data: if number == target: found = True break # Imprimir el resultado if found: print(f'The number {target} was found in the list.') else: print(f'The number {target} was not found in the list.') ```import random if \_\_name\_\_ == '\_\_main\_\_':    data = \[random.randint(0,100) for i in range (10)]   # generate (10 times) random number from 0 to 100     data.sort() #order the number from least to greatest    print(data)        #variables     target = int (input ('What number would you like to find?'))    found = False  # Variable para rastrear si se encuentra el número for number in data:    if number == target:        found = True        break \# Imprimir el resultadoif found:    print(f'The number {target} was found in the list.')else:    print(f'The number {target} was not found in the list.')```js ```
`import random` `if __name__ == '__main__':    data = [random.randint(0,100) for i in range (10)]   # generate (10 times) random number from 0 to 100` `    data.sort() #order the number from least to greatest    print(data)        #variables` `    target = int (input ('What number would you like to find?'))    found = False  # Variable para rastrear si se encuentra el número` `for number in data:    if number == target:        found = True        break` `# Imprimir el resultadoif found:    print(f'The number {target} was found in the list.')else:    print(f'The number {target} was not found in the list.')`
Usé este método en Fortran, para calcular qué eje centroidal satisface la condición de equilibrio para las fuerzas, en una sección rectangular de concreto reforzado. Yo la conocí como método de la disección, aunque sabía que este método era básico, comparado con el de Newton.
import random

vector = [random.randint(0, 100) for i in range(10)]
vector.sort()
print(vector)

numero_buscado = int(input('Dame el valor a buscar: \n'))

primero = 0 
ultimo = len(vector) -1
while (primero <= ultimo):
    medio = (primero + ultimo)//2
    if (vector[medio] < numero_buscado):
        primero = medio + 1
    elif (vector[medio] == numero_buscado):
        print(numero_buscado, "encontado la posicion")
        print(medio)
        primero = 2*ultimo #para salir del siclo
    else:
        ultimo = medio
        medio = (primero + ultimo)/2
    
if numero_buscado not in vector:
    print('Numero no encontrado')
import random

def binary_search(data, target, low_index, hig_index):
    if low_index > hig_index:
        return False
    mid_index = (low_index + hig_index)//2

    if target == data[mid_index]:
        return True
    elif target < data[mid_index]:
        return binary_search(data, target, low_index, mid_index - 1)
    else:
        return binary_search(data, target, mid_index + 1, hig_index)
    
def binary_search_recursive(data, target):
  """
  Realiza una búsqueda binaria en una lista ordenada.

  Args:
    data: La lista ordenada donde se va a buscar.
    target: El elemento que se busca.

  Returns:
    True si el elemento es encontrado, o False si no se encuentra.
  """
  if len(data) == 0:
    return False

  mid_index = len(data) // 2
  if data[mid_index] == target:
    return True
  elif data[mid_index] < target:
    return binary_search_recursive(data[mid_index + 1:], target)
  else:
    return binary_search_recursive(data[:mid_index], target)

def binary_search_loop(data, target):
  """
  Realiza una búsqueda binaria en una lista ordenada.

  Args:
    data: La lista ordenada donde se va a buscar.
    target: El elemento que se busca.

  Returns:
    El índice del elemento encontrado, o False si no se encuentra.
  """
  low_index = 0
  high_index = len(data) - 1
  while low_index <= high_index:
    middle_index = (low_index + high_index) // 2
    if data[middle_index] == target:
      return middle_index
    elif data[middle_index] < target:
      low_index = middle_index + 1
    else:
      high_index = middle_index - 1

  return False

if __name__ == '__main__':
    data = [random.randint(0,100) for i in range(10)]
    print(data)
    sorted_data = sorted(data)
    print(data)
    print(sorted_data)
    data.sort()
    print(data)

    target = int(input('What number would you like to find?'))
    found = binary_search(data, target , 0 , len(data)- 1 )
    print(found)

    found = binary_search_recursive(data,target)
    print(found)

    found = binary_search_loop(data,target)
    print(found)

mientras haya una condición While loop es la mejor opción para no recorrer todas las posibilidades.
La teoría clara, pero al momento de entender cada parte del código si me llevo tiempo.

def buscar(data, find): 
    steps = 0
    lower = 0
    higher = len(data) -1
    
    while lower <= higher:
        steps += 1
        middle = (lower + higher) // 2

        if data[middle] == find: 
            return 'el valor {} fue encontrado en {} pasos '.format(find, steps)
        if data[middle] > find:
            higher = middle -1
        if data[middle] < find:
            lower = middle +1
    return 'elemento {} no encontrado'.format(find)


def main(): 
    data = [i for i in range(20 +1)]
    position = buscar(data, 20)
    print(position)


if __name__ == '__main__':
    main()

soy del futuro y le pedi a la IA de chat GPT la misma funcion y me creó esto:

import random

def busqueda_binaria(lista, objetivo):
    inicio = 0
    fin = len(lista) - 1

    while inicio <= fin:
        medio = (inicio + fin) // 2
        if lista[medio] == objetivo:
            return medio
        elif lista[medio] < objetivo:
            inicio = medio + 1
        else:
            fin = medio - 1

    return -1

# Generar una lista de 10 números aleatorios ordenados
numeros = sorted(random.sample(range(1, 101), 10))

# Imprimir la lista generada
print("Lista generada:", numeros)

# Solicitar al usuario un número objetivo para buscar
objetivo = int(input("Ingrese un número para buscar en la lista: "))

# Realizar la búsqueda binaria
resultado = busqueda_binaria(numeros, objetivo)

# Imprimir el resultado
if resultado != -1:
    print("El número", objetivo, "se encuentra en la posición", resultado)
else:
    print("El número", objetivo, "no se encuentra en la lista.")
def binary_search_loop(data, target, init, final):
    pivot = False
    while pivot != True:
        if init > final:
            return False
        mid = (init + final) // 2
        print('Initial: ' + str(init))
        print('Middle: ' + str(mid))
        print('Final: ' + str(final) + '\n -----------')
        if target == data[mid]:
            pivot = True
            return True
        elif target < data[mid]:
            final = mid - 1
            init = 0
        else: 
            init = mid + 1

Mi aporte con un For Loop

def binary_search(data, target, low, high):
    mid = high + low // 2
    for i in range(len(data)):
        if data[mid] == target:
            return True
        elif data[mid] > target:
            mid = mid//2
        else:
            mid = (mid + len(data)-1)//2
    return False
import random

def encuentra_numero(data, numero, inicio, fin):
    x = 0
    encontrado = False
    while x ==0:
        if inicio > fin:
            x=1
        
        mitad = (inicio + fin) //2
        
        if numero == data[mitad]:
            x =1
            encontrado = True
        elif numero > data[mitad]:
            inicio = mitad+1
        else:
            fin = mitad-1

    return encontrado

if __name__ == '__main__':
    numero_aleatorio = []
    for i in range(100):
        numero_aleatorio.append(random.randint(1,100))
    numero_ordenado = sorted(numero_aleatorio)
    print(numero_ordenado)

    numero1 = int(input('Que numero quieres buscar? '))    
    encontrado = encuentra_numero(numero_ordenado, numero1, 0, len(numero_ordenado)-1)
    print(encontrado)

Lo hice así mediante un ciclo While.

Por aca mi aporte al reto:

from random import randint

def binary_search(data, target, low_idx, high_idx):

while low_idx <= high_idx:
    mid_idx = int((high_idx + low_idx) / 2)

    if target == data[mid_idx]:
        return True
    elif target < data[mid_idx]:  
        return binary_search(data, target, low_idx, mid_idx - 1)    
    else:
         return binary_search(data, target, mid_idx + 1, high_idx)
        
return False 

def run():
print("=" * 50)
print(“Binary search alogrithm!!!”)
print("=" * 50)

data = list(randint(0, 500) for i in range(100)) 
data.sort()
print(data)

target = int(input("What number would you like to find?: "))
found = binary_search(data, target, 0, len(data) - 1)     

print(found)
if found is True:
    print("The objective has been found!!")
else:
    print("The objective is not on the list")
print("=" * 50)

if name == ‘main’:
run()

Propuesta del Reto

import random


def binary_search(data, target):
    low = 0
    high = len(data) - 1
    result = False

    while True:
        if low > high:
            result = False
            break

        mid = (low + high) // 2

        if target == data[mid]:
            result = True
            break
        elif target < data[mid]:
            high = mid - 1
        else:
            low = mid + 1

    if result:
        return f'El numero {target} se encuentra en la posicion {mid}'
    else:
        return f'El numero {target} no se encuentra en la lista'


def run():
    data = [random.randint(0,100) for i in range(10)]
    data.sort()
    print(data)

    target = int(input('What number would you like to find?: '))
    found = binary_search(data, target)

    print(found)


if __name__ == '__main__':
    run()
import random
import time


def binary_search(data, target, low_index, high_index):

    while True:
        if low_index > high_index:
            found = False
            break

        mid_index = (low_index + high_index) // 2
        if data[mid_index] == target:
            found = True
            break
        elif data[mid_index] > target:
            high_index = mid_index - 1
        elif data[mid_index] < target:
            low_index = mid_index + 1

    return found, mid_index


if __name__ == "__main__":
    data = [random.randint(0, 100) for i in range(10)]
    data.sort()
    print(data)
    while True:
        try:
            target = input('What number would you like to find? ')
            found, index = binary_search(data, int(target), 0, len(data) - 1)
            if found:
                print(f'Number {target} found at index {index}')
            else:
                print(f'Number {target} not found')
            break

        except:
            if target == 'exit':
                break
            print("Please enter an integer number")

Solución con bucles

from random import randint


#def binary_search(data, target, low, high):
#    if low > high:
#        return False
#    
#    mid = (low + high) // 2
#    
#    if target == data[mid]:
#        return True
#    elif target < data[mid]:
#        return binary_search(data, target, low, mid - 1)
#    else:
#        return binary_search(data, target, mid + 1, high)

def binary_search(data, target, low, high):
    while low <= high:
        mid = (low + high) // 2
        
        if target == data[mid]:
            return True
        elif target < data[mid]:
            high = mid - 1
        else:
            low = mid + 1
    
    return False


def run():
    data: list = [randint(0, 100) for i in range(10)]
    data.sort()
    
    print(data)

    target = int(input("What number would you like to find? "))
    found = binary_search(data, target, 0, len(data) - 1)
    
    print(found)

if __name__ == '__main__':
    run() 

Bueno otra manera de hacerlo usando un ciclo seria la siguiente:

import random

# this creates a unordered ramdomized list of integers  from 1 to 20
random_list = [random.randint(1, 20) for _ in range(20)]

ordered_list = sorted(random_list)

def binary_search(ordered_list, number_to_find, low, high):
    if low > high:
        return False
    mid = (low + high) // 2
    if number_to_find == ordered_list[mid]:
        return True
    elif number_to_find < ordered_list[mid]:
        return binary_search(ordered_list, number_to_find, low, mid - 1)
    else:
        return binary_search(ordered_list, number_to_find, mid + 1, high)

# Another way to do this using loops
def binary_search_loop(ordered_list, number_to_find):
    low = 0
    high = len(ordered_list) - 1
    while low <= high:
        mid = (low + high) // 2
        if number_to_find == ordered_list[mid]:
            return True
        elif number_to_find < ordered_list[mid]:
            high = mid - 1
        else:
            low = mid + 1
    return False



if __name__ == "__main__":
    print(random_list)
    print(ordered_list)
    number_to_find = int(input("What number would you like to find? "))
    found = binary_search(ordered_list, number_to_find, 0, len(ordered_list) - 1)
    print(found)
    found = binary_search_loop(ordered_list, number_to_find)
    print(found)

My challenge:

import random

def create_list():

    _list = [random.randint(1,50) for n in range(10)]
    _list.sort()

    return _list

def binary_search(_list, search_number):
    lowest = 0
    highest = max(0, len(_list) - 1)
    
    while abs(lowest + highest) >= 0:
        middle = (lowest + highest) // 2

        if _list[middle] == search_number:
            return True
        if _list[middle] > search_number:
            highest = middle - 1        
        else:
            lowest = middle + 1

    return False


if __name__ == '__main__':
    n_list = create_list()

    print(n_list)
    find = int(input('Buscar: '))

    print(binary_search(n_list, find))
            
def datos():
    n = int(input('Dame el numero de elementos de la lista: '))
    vector= [None]*n

    for i in range(n):
        print('Dame el numero ')
        vector[i] = int(input())

    return vector


def _numerobuscado():
    numero_buscado = int(input('Dame un numero para buscar: '))

    return numero_buscado


def binary_search(vector, buscado):
    if buscado not in vector:
        print ('Numero no encontrado')
        
    primero = 1
    ultimo = buscado
    medio = (primero + ultimo) // 2 
    while(primero <= ultimo):
        if (vector[medio] < buscado):
            primero = medio + 1 
        elif (vector[medio] == buscado):
            print (buscado, 'Numero encontrado ')
            break
        else:
            ultimo = medio
            medio = (primero + ultimo) // 2


if __name__ == '__main__':

    lista = datos()
    buscado = _numerobuscado()
    binary_search(lista, buscado)
    

Una solución más fácil:

 from bisect import bisect_left # Python built-in function

if __name__ == '__main__':
    ...
    i = bisect_left(data, target)
    if i != len(data) and data[i] == target:
        print(f'The number: {target} is in the list'
    else:
        print(f'The number: {target} is not in the list'

Aquí está el reto:

import random


def binary_search(data, target, low_index, high_index):
    while low_index <= high_index:
        if low_index == high_index:
            if target == data[low_index]:
                return True
            else:
                return False
            break
        mid_index = (low_index + high_index) // 2

        if target == data[mid_index]:
            return True
            break
        else:
            if target < data[mid_index]:
                high_index = mid_index -1
            else:
                low_index = mid_index + 1


if __name__ == '__main__':
    data = [random.randint(0,100) for i in range(10)]

    data.sort()

    print(data)
    target = int(input('What number would you like to find? '))
    found = binary_search(data, target, 0, len(data) - 1)
    
    print(found)

import random

def run():
numero_aleatorio= random.randint(1, 400)
numero_elegido= int(input(“ingresa un número, por favor: “))
while numero_elegido != numero_aleatorio:
if numero_elegido < numero_aleatorio:
print(” elige un número mas grande”)
elif numero_elegido > numero_aleatorio:
print(" elije un número mas pequeño")

      numero_elegido= int(input("Intenta con otro numero por favor: "))

if numero_elegido== numero_aleatorio:
    
    print("Elegiste el número correcto")

if name== “main”:
run()

Reto

Si alguien tiene alguna sugerencia lo agradecería.

from typing import List


def binary_search(target: int, source: List[int]) -> bool:
    """Checks if a number is in the provided list.
    
    Time Complexity: O(log n)
    Space Complexity: O(1)

    Returns:
        bool: Returns True if the number is in the provided list. Otherwise, it returns False.
    """

    length = len(source)

    if length == 0:
        return False

    left = 0
    right = length
    middle = -1

    while left < right and right >= 1 and middle < length - 1:
        middle = left + (right // 2)

        if source[middle] == target:
            return True

        if target > source[middle]:
            left = middle - 1
        else:
            right = middle

    return False


if __name__ == '__main__':

    import unittest
    from typing import Tuple

    from ddt import ddt  # type: ignore
    from ddt import unpack  # type: ignore
    from ddt import data  # type: ignore


    @ddt
    class BinarySearchTestCaseç(unittest.TestCase):

        @data(
            ((1, [1, 2, 3, 4]), True),
            ((2, [1, 2, 3, 4]), True),
            ((3, [1, 2, 3, 4]), True),
            ((4, [1, 2, 3, 4]), True),
            ((5, [1, 2, 3, 4]), False),
            ((6, [1, 2, 3, 4]), False),
            ((7, [1, 2, 3, 4]), False),
            ((8, [1, 2, 3, 4]), False),
            ((9, [1, 2, 3, 4]), False),
            ((10, [1, 2, 3, 4]), False),
        )
        @unpack
        def test_binary_search(self, args: Tuple[int, List[int]], expected_result: bool):
            result = binary_search(*args)
            self.assertEqual(result, expected_result)

    unittest.main(verbosity=2)

Procedo a mostrar mi código para la búsqueda binaria sin recursividad. Este usa una idea algo diferente en la que no se centra en encontrar explícitamente el número, sino en separar la lista en 2 partes. Una que contenga al valor que quiero (si es que existe) y la otra el resto de los números. Pueden ver más detalles de esta lógica e implementación acá.

def binary_search(numbers_list, target):
    bl = -1
    br = len(numbers_list)
    while br - bl > 1:
        bh = (bl + br) // 2
        if numbers_list[bh] <= target:
            bl = bh
        else:
            br = bh
    return numbers_list[bl] == target

Lo lindo de esta manera es que no solo sirve para buscar un valor específico en un arreglo, sino para optimizar funciones. Otras implementaciones claro que lo pueden hacer, pero esta ayuda a razonar mejor el código al implementarlo.


import random

def binary_search(lis,target,low,ligh):

	while True:
		if low>ligh:
			return False
			break
		mid=(low+ligh)//2

		if target==lis[mid]:
			return True
			break

		elif target < lis[mid]:
			ligh=mid-1
			
		else:

			low=mid+1
	 	

if __name__ == '__main__':
	
	lis=[random.randint(1,1000) for i in range(10)]
	lis.sort()
	print(lis)

	target=int(input('what number would you like to find? '))

	valor=binary_search(lis,target,0,len(lis)-1)

	print(valor)

Hice esto:

import random


def busqueda(data, target):

    if target in data:
        return True
    else:
        return False


if __name__ == '__main__':
    data = [random.randint(1,100) for i in range(10)]

    data.sort()

    print(data)

    target = int(input('Qué número buscas'))
    found = busqueda(data,target)
    print(found)

aqui esta mi codigo sin utilizar recursividad

    high = len(lista) - 1
    low = 0
    indice = high // 2
    
    
       
def busqueda_binaria(lista , target):
    high = len(lista) - 1
    low = 0
    indice = high // 2
    
    
       
    while True:
        if low > high:
            return False
            break
        if target == lista[indice]:
            return True   
            break          
        if target > lista[indice]:
            low = indice + 1 
        if target < lista[indice]:
            high = indice  - 1        
        indice = (low + high) // 2  
            

el -1 sirve en caso de que el numero a buscar sea mas grande que el numero mas grande de la lista, de otra manera no sirve , este tipo de cosas me gustaria que el maestro las dijera , luego deducirlas no es dificil pero tampoco facil

Búsqueda binaria sin recursión:

import random


def binary_search(data, target):
    while True:
        if len(data) == 0:
            return False

        mid = len(data) // 2
        if data[mid] == target:
            return True
        else:
            if target < data[mid]:
                data = data[:mid]
            elif target > data[mid]:
                data = data[mid + 1:]


if __name__ == '__main__':
    data = [random.randint(0, 100) for _ in range(10)]
    data.sort()

    print(data)

    target = int(input('Enter a number to search: '))
    found = binary_search(data, target)

    print(found)

Busqueda binaria optimizada

Una forma de optimizar la busqueda binaria es estableciendo el numero de pasos que debe de dar a partir del low para llegar al medio del arreglo. Esto evita problemas de desbordamiento del valor maximo de los enteros.

En vez de calcular:

mid = (low + high) // 2

Optimizalo

mid = low + (high - low)//2

Finalmente el codigo queda como a continuacion:

import random

def binary_search(data:list, target:int):
    low = 0
    high = len(data) - 1

    while low <= high:
        mid = low + (high - low)//2

        if data[mid] == target:
            return True
        elif data[mid] > target:
            high = mid - 1
        else:
            low = mid + 1
    
    return False

if __name__ == '__main__':
    data = sorted([random.randint(0,100) for _ in range(45)])
    
    print(f"Data\n{data}")

    targetA = random.randint(0,100)  
    targetB = random.randint(0,100)

    print(f"Number {targetA} exists in data: {binary_search(data, targetA)}")
    print(f"Number {targetB} exists in data: {binary_search(data, targetB)}")

Aquí dejo mi solución de búsqueda binaria sin recursividad…

import random

def run():
    numeros = [random.randint(0,100) for number in range(0,10)]
    numeros.sort()
    print(numeros)

    target = int(input('What is the number you would like to find: '))

    low = 0
    high = len(numeros)
    mid = (high + low)//2

    found = False

    while(high>low):
        
        if numeros[mid]==target:
            found = True
            break
        elif numeros[mid]>target:
            high = mid -1
        else:
            numeros[mid]<target
            low = mid +1

        mid = (high + low)//2

    print(f"Lo sentimos...el número {target} {'SI' if found else 'NO'} se encuentra en la lista.")

if __name__ == '__main__':
    run()

Así es como lo hice, usando bucle while. Genera un objetivo aleatorio entre los posibles para obtener cualquier resultado

import random

numList = [random.randint(10,100) for i in range(0,10)]
numList.sort()
objetivo = random.randint(10,100)
print(f'{numList}\n{objetivo}')

def binary_search(numList, objetivo, min, max):
    while (min<=max):
        med = (min+max)//2
        if (objetivo == numList[med]):
            return ("el numero esta en la lista")
        elif(objetivo < numList[med]):
            max = med-1
        else:
            min = med+1
    else:
        return (f"El numero no esta en la lista :c")

print(binary_search(numList,objetivo,0,len(numList)-1))

Búsqueda binaria recursiva:


#Búsqueda binaria recursiva

import random


def binary_search(data, target, low, high):
  if low > high:
    return False

  mid = (low + high) // 2

  if target == data[mid]:
    return True
  elif target < data[mid]:
    return binary_search(data, target, low, mid - 1)
  elif target > data[mid]:
    return binary_search(data, target, mid + 1, high)


if __name__ == '__main__':
  data = [random.randint(0,100) for i in range(10)]

  data.sort()

  print(data)

  target = int(input('What number would you like to find?: '))
  found = binary_search(data, target, 0, len(data)-1)

  print(found)
def binary_search_2(data, target):
    if target in data:
        return True
    else:
        return False


def binary_search_3(data, target):
    for item in data:
        if item == target:
            return True
    return False

def binary_search_without_recursivity(data, number_to_find, min, max):

    number_found = None

    while not number_found:
        if min > max:
            number_found = False
            break

        mid = (min + max) // 2

        if data[mid] == number_to_find:
            number_found = True
        elif data[mid] > number_to_find:
            max = mid - 1
        else:
            min = mid + 1


    return number_found```

Yo le hice algunos cambios para no pasar low y high como parámetros ya que se pueden extraer de la lista directamente

def search(objective, my_list):
    size = len(my_list)
    
    if size == 0:
        return False
    
    mid = size // 2
    
    if my_list[mid] == objective:
        return True
    elif objective < my_list[mid]:
        return search(objective, my_list[:mid])
    elif mid + 1 != size:
        return search(objective, my_list[mid+1:])
    else:
        return False

My solución usando ciclos

def binary_search(objective, my_list):
    match = False
    
    floor = 0
    roof = len(my_list) - 1
    
    while floor <= roof:
        mid = (roof + floor) // 2
        
        if objective == my_list[mid]:
            match True
            break
        elif objective < my_list[mid]:
            roof = mid -1
        else:
            floor = mid + 1
    
    return match

Busqueda biaria combinado con quicksort

import random
import os

# The use of 'print()' is for aesthetic purpuse

def _random_even_number_list_generator():

    number_list = [] # Empty list

    lenght = int(input('Insert the desired lenght of the list: '))

    for i in range(lenght):

        number = random.randint(0,100) # Generates a random number between 0 and 100

        number_list.append(number) 

    even_numbers_list = [number for number in number_list if number % 2 == 0] 
    # ↑ appends only the even numbers of the list generated above(ps : i'm in love with list comprehension) 

    return even_numbers_list # Final random even number list  (disordered)


def quicksort_algorithm(number_list):

    if len(number_list) <= 1:

        return number_list # if the lenght of the list is equal to one it means that the number has been sorted

    else:

        pivot = number_list.pop() # pics the last item of the list as our pivot point
        higher_numbers = [] # here goes the numbers higher then pivot
        lower_numbers = [] # here goes the numbers lower or equal to the pivot

        for i in number_list:

            if i > pivot:

                higher_numbers.append(i)
            
            else:

                lower_numbers.append(i)
    
        return quicksort_algorithm(lower_numbers) + [pivot] + quicksort_algorithm(higher_numbers)
        # here we use recursion until our logic breaks ↑


def binary_search(sorted_list,target,low,high):
    """[Binary search]

    Args:
        sorted_list ([LIST]): [a list of numbers alredy sorted]
        target ([INT]): [The number we are looking for]
        low ([INT]): [The lowest number in a list (it starts at 0) and increses by one until we find (or not) the target]
        high ([INT]): [The highest number in a list (it starts at the bottom of the list) and decreses by one until we find (or not) the target]
    """

    found = False


    while low != high:

        mid = (low + high)//2 #this is our pivot point, the middle of the list


        if target == sorted_list[mid]:

            found = True
            break

        elif target < sorted_list[mid]:

            high = mid - 1 # this makes our 'highest item' closer to the target
        
        elif target > sorted_list[mid]:

            low = mid + 1 # this makes our 'lowes item' closer to the target

    if found:

        print('Your number was found on the list!!')
    
    else: 

        print("Your number wasn't found on the list")


if __name__ == '__main__':

    os.system('cls') # Cleans our console

    target = int(input('Insert the even number to look for(it must be between 0 and 100): ')) # The even number we are looking for
    print() 
    sorted_list = quicksort_algorithm(_random_even_number_list_generator())
    print()

    binary_search(sorted_list,target, 0, len(sorted_list))

    print()

    print('used list: ')
    print('-'*10)
    print()
    print(sorted_list)
    print()

Mi solución, búsqueda binaria con loops

import random

def binary_search(data, target):
    low=0
    high=len(data)-1
    found=False
    while low <= high:
        mid = (low + high) // 2
        if target == data[mid]:
            found=True
            break
        elif target < data[mid]:
            high = mid - 1
        else:
            low = mid + 1
    return found


def run():
    data = [random.randint(0, 100) for i in range(10)]
    data.sort()
    print(data)
    target = int(input('What number would you like to find? '))
    found = binary_search(data, target)
    if found == True:
        print(f'The number: {target} is in the list')
    else:
        print(f'The number: {target} is not in the list')



if __name__ == '__main__':
    run()

Con este método no se cicla la ejecución

Mi reto cumplido

def binary_search(data, target, low, high):
    
    mid = (low + high) // 2
    
    while target != data[mid]:
    
        if low > high: 
            return False

        mid = (low + high) // 2
        
        if target < data[mid]:
            high = mid - 1
        else:
            low = mid + 1

    else:
        return True

Os comparto mi código 😄

Hola a todos yo resolví la búsqueda binaria ocupando slices (no creo que sea tan optimo) pero es otra forma de hacerlo , saludos!

def binary_search(list,element,step = 0):
    a = len(list) // 2
    step+=1
    if a == 1 and list[a] != element:
        return False
    if element > list[a]:
        binary_search(list[a:],element,step)
    elif element < list[a]:
        binary_search(list[:a], element, step)
    else:
        print(f'{element} found {step} steps needed!')
        return True

Mi solución

def binary_search(numbers, number_to_find):
    numbers_length = len(numbers)
    middle_index = numbers_length//2
    middle_number = numbers[middle_index]

    if middle_number == number_to_find:
        return 'Lo encontre'

    if not (number_to_find >= numbers[0] and number_to_find <= numbers[-1]):
        return 'El numero no esta'

    if number_to_find > middle_number:
        return binary_search(numbers[middle_index:], number_to_find)
    elif number_to_find < middle_number:
        return binary_search(numbers[:middle_index], number_to_find)

print(binary_search([2, 4, 6, 8, 10], 6))

Hola, esta es mi solución con un loop while. Saludos

def binary_search(data, target, low, high):
  pasos = 0

  while pasos <= (len(data) - 1) // 2:
    pasos += 1
    mid = (low + high) // 2

    if target == data[mid]:
      return True
    elif target < data[mid]:
      high = mid - 1
    else:
      low = mid + 1
  
  return False
import random

def binary_search(data,target,low,high):
    number_found=False;
    while low<=high:
        mid = (low+high)//2
        if target==data[mid]:
            number_found=True
            return number_found
        elif target<data[mid]:
            high=mid-1
        else:
            low=mid+1

    return number_found        



if __name__=='__main__':
    data = [random.randint(0,100) for i in range(10)]
    data.sort()
    print(data)
    target=int(input('what number would you like to found?'))
    found=binary_search(data,target,0,len(data)-1)
    print(found)```

Mi código. Me esta costando aprender pero lo logré!!!

def binary_search(data, target, low, high):
	while low <= high:
		
		mid = (low + high) // 2

		if target == data[mid]:
			return True

		elif target > data[mid]:
			low = mid + 1

		else:
			high = mid - 1

	return False

Mi tarea:

import random

def binary_search(data, target, low, high):
    while target:
        if target == data[low]:
            return True
        if target == data[high]:
            return True
        mid = (low + high) // 2
        if target == data[mid]:
            return True
        elif tarfeg < data[mid]:
            high = mid
        else:
            low = mid


if __name__ == '__main__':
    data = [random.randint(0, 100) for i in range(10)]
    sorted_data = sorted(data)
    print(sorted_data)
    target =int(input('What number would you like to find? :'))
    found = binary_search(sorted_data, target, 0, len(sorted_data) - 1)
    print(found)

Hola, en lo personal no me agrada que los limites inferior y superior deban ser definidos fuera de la función así que los calcule dentro de ella, he agregado una bandera de iteraciones y un print cuando se encuentra el valor, creo que es ilustrativo, lo recomiendo pues te permite apreciar cuantas iteraciones tomo encontrar un valor X en una posición Y

import random

def binary_search(sorted_list, term):
    iterations = 0
    min_limit = 0
    max_limit = len(sorted_list) - 1
    while min_limit <= max_limit:
        iterations += 1
        mid_point = (max_limit + min_limit) // 2
        if sorted_list[mid_point] == term:
            print('{} found in {} iterations at position {}'.format(term, iterations, mid_point))
            return mid_point
        elif sorted_list[mid_point] < term:
            min_limit = mid_point + 1
        else:
            max_limit = mid_point - 1
    return None


if __name__ == '__main__':
    sorted_list = [random.randint(0,200) for n in range(20)]
    sorted_list.sort()
    print('Thes list is: ', sorted_list)
    number = int(input('Which number would you like to search? '))
    binary_search(sorted_list=sorted_list, term=number)

Utilizando la función index y evaluando el error con try / except

import random


def binary_search(data, target, low, high):
    if low > high:
        return False
    
    mid = (low + high) // 2
    
    if target == data[mid]:
        return True
    elif target < data[mid]:
        return binary_search(data, target, low, mid - 1)
    else:
        return binary_search(data, target, mid + 1, high)


def cycle_search(data, target):
    try:
        return data.index(target)
    except ValueError:
        return None


#Punto de ingreso
if __name__ == '__main__':
    data = [random.randint(0, 100) for i in range(10)] # Esto es un list comprehension

    data.sort()

    print(data)

    target = int(input('What number would you like to find? '))
    found = cycle_search(data, target)

    if found is not None:
        print('The number {target} was found in the position number {index}'.format(target = target, index = found + 1))
    else:
        print('The number {target} wasn\'t found in any position.'.format(target = target))

Les comparto mi código…

import random

def my_binary_search(data,target,low,high):
	response = False
	if low > high:
		return False

	while low <= high:
		mid = (low + high )  // 2
		if target == data[mid]:
			response = True
			return response
		elif target < data[mid]:
			#return binary_search(data,target,low, mid - 1)
			high = mid - 1
		else:
			#return binary_search(data,target,mid + 1, high)
			low = mid + 1
	return response


if __name__ == '__main__':
	data = [random.randint(0,100) for i in range(10)]
	#data.sort() #solo ordena en la lista
	#sorted_data = sorted(data) #crea una nueva lista ya ordenada
	data.sort()
	print(data)
	target = int(input('What number would you line to find?'))
	#found = binary_search(data,target,0,len(data) -1)
	found = my_binary_search(data,target,0,len(data) -1)
	print("Numero {response} esta en la lista".format( response = 'Si' if found else'no')) # validar para que diga si esta o no en la lista

	

Mi solución

def binary_search_2(data, target):
    high = len(data) -1
    low = 0
    found = False

    while not found:
        if low > high:
            return False
        mid = (low + high) // 2
        if target == data[mid]:
            found = True
        elif target > data[mid]:
            low = mid + 1
        else:
            high = mid - 1

    return found

if __name__ == '__main__':
    data = list(set([random.randint(0, 100) for i in range(10)]))

    data.sort()
    print(data)

    target = int(input('What number would you like to find?: '))
    found = binary_search_2(data, target)

    print(found)

Compañeros mi código para este ejercicio agregando que el usuario puede elegir le rango de números y ademas estos en la lista de data no se repiten.

import random

def binary_search(nData,target,low,high):
    while low <= high:
        mid = (low + high)//2   
        if target == nData[mid]:
            return True
        elif target < nData[mid]:
           high = mid - 1
        else:
            low = mid + 1            

if __name__ == '__main__':
    range_user = int(input('what is the range of numbers that would you like?'))
    data = [random.randint(0,100) for i in range(range_user)]    
    nData = list({numero for numero in data})
    nData.sort()   

    print(nData)

    target = int(input('What number would yuu like to find?'))    
    found = binary_search(nData, target, 0, len(nData) - 1)
    
    if found:
        print('The number {} is in the list'.format(target))
    else:
        print('The number {} is not in the list'.format(target))
    ```

Genial!! increible clase!

este es mi código al reto, saludos

# -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 19:38:03 2019

@author: USUARIO
"""

import random

def binary_search (data, target, low_index, high_index):
    
    for i in data:
        if low_index > high_index:
            return False
    
        mid = (low_index + high_index)//2 # división de enteros
    
        if target == data[mid]:
            return True
        elif target < data[mid]:
            high_index = mid-1
        else:
            low_index = mid +1

if __name__ == '__main__':
    data = [random.randint(0,100) for i in range(10)]
    data.sort()
    
    print(data)
    target = int(input('What number would you like to find?'))
    found = binary_search(data, target, 0 , len(data)-1) 
    
    print (found)```

Aqui Mi codigo.

import random

def binary_search(data, value, low, high):
    status_search = False 
    while(low < high):
        mid = (low + high) // 2

        if value == data[mid]:
            status_search = True
            break
        elif value < data[mid]: 
            high = mid - 1
        else:
            low = mid + 1


if __name__ == '__main__':
    data = [ random.randint(0,100) for i in range(10) ]

    data.sort()

    print(data)
    
    search_value = int(input('What number would you find to?' ))
    found = binary_search(data, search_value, 0, len(data) - 1 )
    print(found)

Estoy intentando correr código solo con loops, pero no en que falla… 😦 Algún feedback por ahí?.. Se los agradecería…

import random

def loops_search(data, target, low, high):

    while low > high is False:

        mid = (low + high) // 2

        if target == data:
            return True
        elif target < data:
            return loops_search(data, target, low , mid -1)
        else:
            return loops_search(data, target, mid + 1, high)

if __name__ == '__main__':
    for i in range(10):
        data = random.randint(0, 100)
        print(data)

    target = int(input('What is number?: '))
    found = loops_search(data, target, 0, data - 1)
    print (found)

def binary_search_while(data, target, low, high):
        
        while low <= high:
                mid = (low + high) // 2

                if target == data[mid]:
                        return True
                elif target < data[mid]:
                        high = mid - 1
                else:
                        low = mid + 1

        if low > high:
                return False
import random
""" binary search sin recursion... usando ciclos """
def binary_search(data, target, low, high):
    if target == data[high] or target == data[low]:
        return True
    if target > data[high] | target < data[low]:
        return False

    finish =  True
    while finish:
        mid = (low + high)//2
        if target == data[mid]:
            return True
        elif target > data[mid]:
            low = mid
        else:
            high = mid

        if high - low == 1:
            return False
            
        
        




if __name__ == '__main__':
    data = [random.randint(0,100) for i in range(10)]
    sorted_data = sorted(data)
    found = False
    print(sorted_data)
    target = int(input('what number would you like to find?'))
    found = binary_search(sorted_data, target, 0, len(sorted_data) - 1)
    print(found)

al principio de la funcion valido que el numero que busco no este en los extremos del array, porque si se fijan en el codigo de david resulta en un peque;o bug… si buscan el numero que esta el en extremo derecho del array te arroja False sin importar si el numero realmente esta en la lista

import random

def buscar_numero(numero):
    global ind_ini,ind_fin,ind_med
    num_ind = 0

    if ordenados[ind_ini] == numero:
        num_ind = numero

    elif ordenados[ind_fin] == numero:
        num_ind = numero

    else:
        while num_ind != numero:

            if ind_fin != ind_ini + 2:
                ind_med = int((ind_ini+ind_fin)/2)
                num_ind = ordenados[ind_med]
                print(f'{num_ind} y {numero}')
                if num_ind == numero:
                    print(f'{num_ind} y {numero}')
                    print('El número se encontró :) :) !!!!!!')
                elif num_ind > numero:
                    ind_ini = ind_ini
                    ind_fin = ind_med
                elif num_ind < numero:
                    ind_ini = ind_med
                    ind_fin = ind_fin
            elif ordenados[ind_ini+1] == numero:
                num_ind = numero
                print(f'{num_ind} y {numero}')
                print('El número se encontró :) !!!!!!')
            else:
                print('No se encontró en número :( ')
                num_ind = numero
                #break

if __name__ == '__main__':
    pass
    numeros = [random.randint(0,10000) for i in range(570)]
    ordenados = sorted(numeros)
    ind_ini = 0
    ind_fin = len(ordenados)-1
    print(f'{ind_fin}')
    ind_med = 0
    print(ordenados)
    busca = input('Ingrese el número que busca, que esté estre 0 y 10000 ')
    pasos = buscar_numero(int(busca))```
    while low <= high:
        mid = (low+high) // 2
        if target == data[mid]:
            print('The number {} is in the order {}'. format(target, mid))
            return True
        elif target < data[mid]:
            high = mid -1
        else:
            low = mid + 1
        if low > high:
            print('The number doesn\'t exist in the list')
            return False

Mi solución

import random


def binary_search(data_search, target_search, low, high):
    if low > high:
        return False
    mid = (low + high) // 2

    if target_search == data_search[mid]:
        return True
    elif target_search < data_search[mid]:
        return binary_search(data_search, target_search, low, mid - 1)
    else:
        return binary_search(data_search, target_search, mid + 1, high)


def binay_search_loop(data_search, target_search, low, high):
    not_found = True

    while not_found:

        mid = (low + high) // 2

        if target_search == data_search[mid]:
            not_found = False
            return True

        if target_search < data_search[mid]:
            high = mid - 1
            continue

        if low > high:
            not_found = False
            return not_found

        else:
            low = mid + 1


if __name__ == '__main__':
    data = [random.randint(0, 100) for i in range(10)]
    data.sort()
    print(data)
    target = int(input('What number would you like to find?'))

    # found = binary_search(data, target, 0, len(data) - 1)
    found = binay_search_loop(data, target, 0, len(data) - 1)
    print(found)

import random

lista = []
num = 0
for h in range(1000000):
    num = random.randint(num,num+130)
    lista.append(num)

def binarySearch(num):
    last = len(lista)-1
    first = 0
    while first <= last:
        mid = (last+first)//2
        if lista[mid] == num:
            print(f"el numero '{lista[mid]}' se encontro en el indice: {mid}")
            return num
        else:
            if num > lista[mid]:
                first = mid+1
            else:
                last = mid-1

Les comparto el código de la clase

import random

def binary_search(data, target, low, high):
    if low > high:
        return False

    mid = (low + high) // 2

    if target == data[mid]:
        return True
    elif target < data[mid]:
        return binary_search(data, target, low, mid -1)
    else:
        return binary_search(data, target, mid + 1, high)

if __name__ == '__main__':
    data = [random.randint(0, 100) for i in range(10)]

    data.sort()

    print(data)

    target = int(input('What number would you like to find?'))
    found = binary_search(data,target, 0 , len(data)-1)

    print(found)

Hola, les dejo mi solución al reto usando un for loop:

def search_loop (data, target, high):
    for i in range(high + 1):
        if target == data[i]:
            return True
        if i >= high:
            return False

Mi solución para usar búsqueda binaria con loops:

import random


def binary_search_loop(data,target,low,high):
	found = False
	
	while not found:
		if low > high:
			print('el numero {}, no se encontro'.format(target))
			return False
			
		mid =(low+high)// 2
		if target == data[mid]:
			found = True
			print('el numero {}, se encontro en el indice {}'.format(target,mid))
		elif target < data[mid]:
			high=mid-1
			
		else:
			low=mid+1
			
	return found


if __name__ == '__main__':
	data = [random.randint(0,100) for i in range(10)]

	data.sort()
	print(data)

	target=int(input('What number would you like to find?'))

	found = binary_search_loop(data, target, 0, len(data)-1) ## Mi funcion recibe como parametros la data ORDENADA, el valor a buscar, el indice de origen y el indice final
	print(found)

Tengo un problema, aunque utilice el operador /, el resultado que me regresa es un entero como s estuviera utilizando el operador //.
Alguien sabe porque sucede eso? estoy usando python 2.7