¡Te damos la bienvenida a este reto!

1

Empezando con Python desde 0

Día 1

2

Variables, funciones y sintaxis básica

3

Tipos de datos: Numbers, Strings y Diccionarios

4

Playground - Retorna el tipo

Día 2

5

Operadores

6

Playground - Calcula la propina

Día 3

7

Condicionales

8

Playground - Averigua si un año es bisiesto

9

Ciclos

10

Playground - Dibuja un triangulo usando bucles

Día 4

11

Listas

12

Encuentra a los gatitos más famosos

13

Diccionarios

14

Obtén el promedio de los estudiantes

15

Tuplas

16

Obten la información de los paquetes

Día 5

17

Calcula la cantidad de letras en una oración

18

Encuentra el mayor palíndromo

Día 6

19

Sets

20

Encuentre la intersección de conjuntos

Día 7

21

List comprehension

22

Encuentra palabras con dos vocales

23

Dictionary Comprehension

24

Calcula la longitud de las palabras

Día 8

25

Funciones Lambda

26

Filtra mensajes de un user específico

27

Higher order functions

28

Crea tu propio método map

Día 9

29

Manejo de Errores y excepciones

30

Maneja correctamente los errores

31

Maneja las excepciones

Día 10

32

Playground - Crea un task manager usando closures

Día 11

33

Lectura de archivos de texto y CSV

Día 12

34

Programación orientada a objetos

35

Crea un auto usando clases

Día 13

36

Abstracción en Python

37

Playground - Crea un sistema de carrito de compras

38

Encapsulamiento en Python

39

Playground - Encapsula datos de los usuarios

Día 14

40

Herencia en Python

41

Playground - Jerarquía de animales usando herencia

Día 15

42

Polimorfismo en Python

43

Playground - Implementa un sistema de pagos

Día 16

44

Estructuras de datos en Python

45

Playground - Crea tu propia lista en python

46

Hash tables en Python

47

Playground - Implementación de una HashTable para Contactos

Día 17

48

Maps en Python

49

Playground - Crea un task manager con Maps

Día 18

50

Singly Linked List en Python

51

Playground - Implementación de una singly linked list

Día 19

52

Stacks en Python

53

Playground - Implementación de un stack

Día 20

54

Queues en Python

55

Playground - Implementación de una queue

Día 21

56

¡Lo lograste!

No tienes acceso a esta clase

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

Aprende Inglés, Desarrollo Web, AI, Ciberseguridad y mucho más.

Antes: $249

Currency
$209
Comienza ahora

Termina en:

0 Días
20 Hrs
39 Min
7 Seg

Playground - Implementación de una HashTable para Contactos

47/56

Aportes 20

Preguntas 0

Ordenar por:

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

![](https://static.platzi.com/media/user_upload/hashtable-938d2c52-9534-4d4e-b950-89518c913491.jpg)

Mi aporte

class ContactList:
  def __init__(self, size):
    self.size = size
    self.contact_list = [[] for _ in range(self.size)]
 
  def hash(self, key):
    return hash(key) % self.size

  def insert(self, name, phone):
    index = self.hash(name)
    # print(index)
    self.contact_list[index].append((name, phone))

  def get(self, name):
    index = self.hash(name)
    for key, value in self.contact_list[index]:
      if key == name:
        return value
      return None

  def retrieveAll(self):
    # return self.contact_list
    all_values = []
    for contact in self.contact_list:
      for key, value in contact:
        all_values.append(list((key, value)))
    return all_values

  def delete(self, name):
    index = self.hash(name)
    for key, value in self.contact_list[index]:
      if key == name:
        del self.contact_list[index]
    return None
Aportesito: \- \- \- \- \- \- \- \- \- ```js class ContactList: def __init__(self, size): self.length = size self.buckets = [[] for _ in range(size)] def hash(self, key): return hash(key) % self.length def insert(self, name, phone): hash_key = self.hash(name) if not self.buckets[hash_key]: self.buckets[hash_key].append([name, phone]) else: for bucket in self.buckets[hash_key]: if bucket[0] == name: bucket[1] = phone def get(self, name): hash_key = self.hash(name) for bucket in self.buckets[hash_key]: if bucket[0] == name: return bucket[1] def retrieveAll(self): array = [] for buckets in self.buckets: if buckets: array.append(buckets[0]) return array def delete(self, name): hash_key = self.hash(name) for bucket in self.buckets[hash_key]: if bucket[0] == name: self.buckets[hash_key] = [] else: return [] ```

Mi aporte:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

class ContactList:
  def __init__(self, size):
    # Tu código aquí 👇
    self.size = size
    self.buckets = [[] for _ in range(size)]
    pass
 
  def hash(self, key):
    # Tu código aquí 👇
    return hash(key) % self.size
    pass

  def insert(self, name, phone):
    # Tu código aquí 👇
    index = self.hash(name)
    self.buckets[index].append([name, phone])
    pass

  def get(self, name):
    # Tu código aquí 👇
    index = self.hash(name)
    for n, p in self.buckets[index]:
      if n == name:
        return p
    return None
    pass

  def retrieveAll(self):
    # Tu código aquí 👇
    contacts = []
    for bucket in self.buckets:
      if isinstance(bucket, list):
        contacts.extend(bucket)
      else:
        contacts.append(bucket)
    return contacts
    pass

  def delete(self, name):
    # Tu código aquí 👇
    index = self.hash(name)
    for i, (n, p) in enumerate(self.buckets[index]):
      if n == name:
        del self.buckets[index][i]
        return
    pass```

🛡️🛡️Escudo anti-spoilers🛡️🛡️

Mi solución al reto:

class ContactList:
  def __init__(self, size):
    self.size = size
    self.buckets = [[] for _ in range(size)]
 
  def hash(self, key):
    return hash(key) % self.size 

  def insert(self, name, phone):
    index = self.hash(name)
    self.buckets[index].append([name,phone])
    pass

  def get(self, name):
    index = self.hash(name)
    for k, v in self.buckets[index]:
      if k == name:
        return v
    return None

  def retrieveAll(self):
    result = []
    for b in self.buckets:
      if isinstance(b, list) :
        result.extend(b)
      else:
        result.append(b)
    return result 

  def delete(self, name):
    index = self.hash(name)
    for b, (k, v) in enumerate(self.buckets[index]):
      if k == name:
        del self.buckets[index][b]
        return


.
.
.
.
.
.
.
.
.
.

Mi código:

class ContactList:
    def __init__(self, size):
        self.size = size
        self.buckets = [[] for _ in range(size)]

    def hash(self, key):
        return hash(key) % self.size

    def insert(self, name, phone):
        index = self.hash(name)
        self.buckets[index].append((name, phone))

    def get(self, name):
        index = self.hash(name)
        return next((phone for k, phone in self.buckets[index] if k == name), None)

    def retrieveAll(self):
        return [[key, value] for bucket in self.buckets for key, value in bucket]

    def delete(self, name):
        index = self.hash(name)
        self.buckets[index] = [(k, v) for k, v in self.buckets[index] if k != name]

class ContactList:
  def __init__(self, size):
    self.size = size
    self.buckets = [[] for _ in range(size)]
 
  def hash(self, key):
    return hash(key) % self.size

  def insert(self, name, phone):
    index = self.hash(name)
    if self.get(name) is None:
      return self.buckets[index].append((name, phone))
    self.delete(name)
    self.insert(name, phone)     

  def get(self, name):
    index = self.hash(name)
    for k, v in self.buckets[index]:
      if k == name:
        return v
      return None

  def retrieveAll(self):
    all_values = []
    for bucket in self.buckets:
      for name, phone in bucket:
        all_values.append([name, phone])
    return all_values

  def delete(self, name):
    index = self.hash(name)
    for i, (k, v) in enumerate(self.buckets[index]):
      if k == name:
        del self.buckets[index][i]


.
.
.
.
.
.
.
.
.
.
.

Solución 😄…
.

.
.
.
.

class ContactList:
  def __init__(self, size):
    self.size = size
    self.buckets = [[] for _ in range(size)]
 
  def hash(self, key):
    return hash(key) % self.size

  def insert(self, name, phone):
    index = self.hash(name)
    self.buckets[index].append((name, phone))

  def get(self, name):
    index = self.hash(name)
    for k, v in self.buckets[index]:
      if k == name:
        return v
    return None

  def retrieveAll(self):
    all_values = []
    for bucket in self.buckets:
      for name, phone in bucket:
        all_values.append([name, phone])
    return all_values

  def delete(self, name):
    index = self.hash(name)
    for i, (k, v) in enumerate(self.buckets[index]):
      if k == name:
        del self.buckets[index][i]
        return
    return None
class ContactList:
  def __init__(self, size):
    self.size = size
    self.contacts = [[] for _ in range(size)]
 
  def hash(self, key):
    return hash(key) % self.size

  def insert(self, name, phone):
    index =  self.hash(name)
    self.contacts[index].append((name, phone))

  def get(self, name):
    index = self.hash(name)
    for key, value in self.contacts[index]:
      if key == name:
        return value
    return None

  def retrieveAll(self):
    all_values = []
    for contact in self.contacts:
      for key, value in contact:
        all_values.append([key, value])
    return all_values

  def delete(self, name):
    index = self.hash(name)
    for i, (key, value) in enumerate(self.contacts[index]):
      if key == name:
        del self.contacts[index][i]
        return
class ContactList:
  def __init__(self, size):
    self.buckets = [[] for _ in range(size)]
 
  def hash(self, key):
    return hash(key) % len(self.buckets)

  def insert(self, name, phone):
    index = self.hash(name)
    self.buckets[index].append((name, phone))

  def get(self, name):
    index = self.hash(name)
    for contact in self.buckets[index]:
      if contact[0] == name:
        return contact[1]

  def retrieveAll(self):
    elements = []
    for bucket in self.buckets:
      for contact in bucket:
        elements.append(list(contact))
    return elements

  def delete(self, name):
    index = self.hash(name)
    for contact in self.buckets[index]:
      if contact[0] == name:
        self.buckets[index].remove(contact)

class ContactList:
    def __init__(self, size):
        self.size = size
        self.buckets = [[] for _ in range(size)]

    def hash(self, key):
        return hash(key) % self.size

    def insert(self, name, phone):
        index = self.hash(name)
        self.buckets[index].append((name, phone))

    def get(self, name):
        index = self.hash(name)
        for key, value in self.buckets[index]:
            if key == name:
                return value

        return None

    def retrieveAll(self):
        all_values = []
        for bucket in self.buckets:
            for name, phone in bucket:
                all_values.append([name, phone])

        return all_values

    def delete(self, name):
        index = self.hash(name)
        for i, (k, v) in enumerate(self.buckets[index]):
            if k == name:
                del self.buckets[index][i]
            return

        return None
test_insert_new_contact

test_insert_multiple_contacts_same_index

test_get_phone_number_of_contact

test_return_null_if_contact_not_found

test_return_empty_array_if_no_contacts

test_return_array_with_all_contacts

test_delete_contact_from_hash_table

test_return_null_if_contact_not_found_when_deleting

¡Felicidades, todas las pruebas pasaron!
contactList = ContactList(10)
contactList.insert("Mr michi", "123-456-7890")

print(contactList.retrieveAll())  # Output: [["Mr michi", "123-456-7890"]]

phone_number = contactList.get("Mr michi")
print(phone_number)  # Output: "123-456-7890"

result = contactList.delete("Mr michi")
print(result)  # Output: True

phone_number = contactList.get("Mr michi")
print(phone_number)  # Output: None

mi solución:
+
+
+
+
+
+
+
+
+

class ContactList:
  def __init__(self, size):
    # Tu código aquí 👇
    self.size = size
    self.buckets = [[] for _ in range(size)]
   
 
  def hash(self, key):
    # Tu código aquí 👇
    return hash(key) % self.size
    

  def insert(self, name, phone):
    # Tu código aquí 👇
    index = self.hash(name)
    self.buckets[index].append((name, phone))
    

  def get(self, name):
    # Tu código aquí 👇
    index = self.hash(name)
    for k, v in self.buckets[index]:
      if k == name:
        return v
    return None
    

  def retrieveAll(self):
    # Tu código aquí 👇
    all_values = []
    for bucket in self.buckets:
      for key, value in bucket:
        all_values.append([key,value])
    return all_values
  
  def delete(self, name):
    index =self.hash(name)
    for i,(k,v) in enumerate(self.buckets[index]):
      if k == name:
        del self.buckets[index][i]
        return

o
o
o
o
o
o

class ContactList:
  def __init__(self, size):
    self.size = size
    self.lista_fija = [[] for _ in range(size)]
 
  def hash(self, key):
    return hash(key) % self.size

  def insert(self, name, phone):
    key = name
    index = self.hash(key)
    self.lista_fija[index].append(key)
    self.lista_fija[index].append(phone)


  def get(self, name):
    key = name
    index = self.hash(key)
    if len(self.lista_fija[index]) > 0:
      return self.lista_fija[index][1]
    else:
      return None 

  def retrieveAll(self):
    salida = [elemento for elemento in self.lista_fija if len(elemento) > 0]
    return salida  

  def delete(self, name):
    key = name
    index = self.hash(key)
    if len(self.lista_fija[index]) > 0:
      self.lista_fija[index].pop(1)
      self.lista_fija[index].pop(0)
      return name
    else:
      return None  
    
  def devuelvaTodos(self):
    return self.lista_fija


.
.
.
.
.


.
.
.
.
.

class ContactList:
  def __init__(self, size):
    self._contacts = [[] for _ in range(size)]
    self._size = size

  def _hash(self, key):
    total = 0
    for char in key:
      total += ord(char)
    return total % self._size

  def insert(self, name, phone):
    index = self._hash(name)
    if self._contacts[index] is None:
      self._contacts[index] = []
    for i, contact in enumerate(self._contacts[index]):
      if contact[0] == name:
        self._contacts[index][i] = [name, phone]
        return
    self._contacts[index].append([name, phone])

  def get(self, name):
    index = self._hash(name)
    if self._contacts[index] is not None:
      for contact in self._contacts[index]:
        if contact[0] == name:
          return contact[1]
    return None

  def retrieveAll(self):
    all_contacts = []
    for bucket in self._contacts:
      if bucket is not None:
        all_contacts.extend(bucket)
    return all_contacts

  def delete(self, name):
    index = self._hash(name)
    if self._contacts[index] is not None:
      for i, contact in enumerate(self._contacts[index]):
        if contact[0] == name:
          del self._contacts[index][i]
          return
    return None

SPOILER
.
.
.
.
.
.
.

.
.
.

class ContactList:
  def __init__(self, size):
    # Tu código aquí 👇
    self.size = size
    self.contactList = [[] for _ in range(size)]
    pass
 
  def hash(self, key):
    # Tu código aquí 👇
    return hash(key) % self.size
    pass

  def insert(self, name, phone):
    # Tu código aquí 👇
    index = self.hash(name)
    self.contactList[index].append((name, phone))
    pass

  def get(self, name):
    # Tu código aquí 👇
    index = self.hash(name)
    for k, v in self.contactList[index]:
      if k == name:
        return v
    return None
    pass

  def retrieveAll(self):
    # Tu código aquí 👇
    all_values = []
    for contact in self.contactList:
      for key, value in contact:
        all_values.append([key, value])
    all_values.reverse()
    return all_values
    pass

  def delete(self, name):
    # Tu código aquí 👇
    index = self.hash(name)
    for i, (k, v) in enumerate(self.contactList[index]):
      if k == name:
        del self.contactList[index][i]
        return
    pass

contactList = ContactList(10)
contactList.insert("Mr michi", "123-456-7890")

print(contactList.retrieveAll())

undefined