隆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

Playground - Crea tu propia lista en python

45/56

Aportes 19

Preguntas 1

Ordenar por:

驴Quieres ver m谩s aportes, preguntas y respuestas de la comunidad?

o inicia sesi贸n.

Me han gustado las practicas del reto, estan chevveres para practicar, y recomendaria un curso de poo para python unicamente

class MyList:

  def __init__(self):
    self.data: dict = {}
    self.length: int = 0


  def append(self, item): 
    self.data[self.length] = item
    self.length +=1
     

  def pop(self):
    self.length -=1
    return self.data.pop(max(self.data.keys())) 


  def shift(self):
    self.length -=1
    first = self.data[0]
    self.data = {key-1: value for key, value in self.data.items() if key != 0}

    return first


  def unshift(self, item):
    self.length += 1
    self.data = {key+1: value for key, value in self.data.items()}
    self.data[0] = item


  def map(self, func):
    map_list = MyList()
    for idx in range(len(self.data)):
        map_list.append(func(self.data[idx]))
    return map_list


  def filter(self, func):
    map_list = MyList()
    for idx in range(len(self.data)):
        if func(self.data[idx]):
          map_list.append(self.data[idx])
    return map_list


  def join(self, character=","):
    result = ""
    for idx in range(len(self.data)):
      if result == "":
        result += str(self.data[idx])
      else:
        result += character + str( self.data[idx]) 

    return result

Mi aporte, sin usar m茅todos nativos de las listas
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

class MyList:
  def __init__(self):
    # Tu c贸digo aqu铆 馃憞
    self.data = {}
    self.length = 0
    pass

  def append(self, item):
    # Tu c贸digo aqu铆 馃憞
    self.data[self.length] = item
    self.length += 1
    pass

  def pop(self):
    # Tu c贸digo aqu铆 馃憞
    rData = self.data[self.length - 1]
    del self.data[self.length - 1]
    self.length -= 1
    return rData
    pass

  def shift(self):
    # Tu c贸digo aqu铆 馃憞
    rData = self.data[0]
    for i in range(0, self.length - 1):
      self.data[i] = self.data[i + 1]
    del self.data[self.length - 1]
    self.length -= 1
    return rData
    pass

  def unshift(self, item):
    # Tu c贸digo aqu铆 馃憞
    if item != None:
      for i in range(self.length, 0, -1):
        self.data[i] = self.data[i - 1]
      self.data[0] = item
      self.length += 1
    return self.length
    pass

  def map(self, func):
    # Tu c贸digo aqu铆 馃憞
    rMap = MyList()
    for i in range(0, self.length):
      rMap.append(func(self.data[i]))
    return rMap
    pass

  def filter(self, func):
    # Tu c贸digo aqu铆 馃憞
    rFilter = MyList()
    for i in range(0, self.length):
      if func(self.data[i]):
        rFilter.append(self.data[i])
    return rFilter
    pass

  def join(self, character = ','):
    # Tu c贸digo aqu铆 馃憞
    rJoin = ''
    for i in range(0, self.length):
      rJoin += str(self.data[i])
      if i < self.length - 1:
        rJoin += character
    return rJoin
    pass

馃洝锔忦煕★笍Escudo anti-spoilers馃洝锔忦煕★笍

Mi soluci贸n al reto:
En este reto, no termine de leer el ultimo parrafo de las indicaciones para completarlo, asi que cuando ya tenia el c贸digo terminado sin usar metodos built-in de las listas, me di cuenta que mi propiedad se tenia que llamar 鈥榙ata鈥 y tenia que ser un diccionario鈥 Me dio pereza rehacerlo y mejor use lo aprendido y enga帽e a las pruebas usando getters y setters, y converti mi lista a un dict.

class MyList:
  def __init__(self):
    self.list = []
    self.length = 0

  def append(self, item):
    self.list += [item]
    self.length += 1

  def pop(self):
    poped = self.list[-1] 
    self.list = self.list[:-1]
    self.length -= 1
    return poped 

  def shift(self):
    shifted = self.list[0]
    self.list = self.list[1:] 
    self.length -= 1
    return shifted 

  def unshift(self, item):
    self.list = [item] + self.list
    self.length += 1 

  def map(self, func):
    newList = MyList()
    newList.list = [ func(e) for e in self.list ]
    newList.length = len(newList.data)
    return newList

  def filter(self, func):
    filteredList  = MyList()
    filteredList.list =  [ e for e in self.list if func(e) ]
    filteredList.length = len(filteredList.data)
    return filteredList

  def join(self, character=','):
    newString = "" 
    for e in self.list:
      newString = newString + str(e) + str(character)
    return newString[:-1]

  @property
  def data(self):
    return { i:v for (i,v) in enumerate(self.list)}
  
  @data.setter
  def data(self,v):
    self.list = v


.
.
.
.
.
.
.
.
.
.

Mi c贸digo:

class MyList:
    def __init__(self):
        self.data = {}  # Ser谩 un Diccionario, no una lista
        self.length = 0

    def append(self, item):
        self.data[self.length] = item
        self.length += 1

    def pop(self):
        if self.length > 0:
            self.length -= 1
            return self.data.pop(self.length, None)
        else:
            return None

    def shift(self):
        if self.length > 0:
            item = self.data[0]
            temp_data = {}
            for i in range(1, self.length):
                temp_data[i - 1] = self.data[i]
            self.data = temp_data
            self.length -= 1
            return item
        else:
            return None

    def unshift(self, item):
        temp_data = {}
        temp_data[0] = item
        for i in range(self.length):
            temp_data[i + 1] = self.data[i]
        self.data = temp_data
        self.length += 1

    def map(self, func):
        new_list = MyList()
        for i in range(self.length):
            new_list.append(func(self.data[i]))
        return new_list

    def filter(self, func):
        new_list = MyList()
        for i in range(self.length):
            if func(self.data[i]):
                new_list.append(self.data[i])
        return new_list

    def join(self, character=","):
        if self.length == 0:
            return ""
        joined_string = str(self.data[0])
        for i in range(1, self.length):
            joined_string += character + str(self.data[i])
        return joined_string

Es un diccionario, no una lista, que confundido me pusieron con eso

Vaya hasta que nos ponen algo ya mas f谩cil y tranqui


.
.
.
.
.
.
.
.
.
.

Mi Soluci贸n:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

class MyList:
    def __init__(self):
        self.data = {}
        self.length = 0

    def _reasignar_keys(self):
        """Re-ordena las keys para que inicien en 0 y terminen en length"""
        new_data = {}
        index = 0

        # If insert item at 0
        if -1 in self.data:
            new_data[0] = self.data.pop(-1)
            index = 1
        
        # if remove item at 0
        for key in self.data:
            new_data[index] = self.data[key]
            index += 1
        self.data = new_data


    def append(self, item):
        """Agrega un elemento item al final de la lista"""
        self.data[self.length] = item
        self.length += 1

    def pop(self):
        """Elimina el 煤ltimo elemento de la lista y lo retorna"""
        val = self.data.pop(self.length - 1)
        self.length -= 1
        return val
        

    def shift(self):
        """Elimina el primer elemento de la lista y lo retorna"""
        val = self.data.pop(0)
        self.length -= 1
        self._reasignar_keys()
        return val

    def unshift(self, item):
        """Agrega un elemento item al inicio de la lista"""
        self.data[-1] = item
        self.length += 1
        self._reasignar_keys()
        

    def map(self, func):
        """ itera sobre cada elemento de nuestra estructura aplicando
        la funci贸n func a cada uno de ellos y devuelve una nueva lista 
        (que ser谩 una instancia de MyList"""

        new_list = MyList()
        for key in self.data:
            new_list.append(func(self.data[key]))
        return new_list

    def filter(self, func):
        """ itera sobre cada elemento de nuestra estructura filtr谩ndolos 
        seg煤n lo que indique la funci贸n func y devuelve una lista con los 
        elementos filtrados (tambi茅n una instancia de MyList)."""

        new_list = MyList()
        for key in self.data:
            if func(self.data[key]):
                new_list.append(self.data[key])
        return new_list

    def join(self, character = ','):
        """concatena todos los elementos de nuestra estructura de datos en 
        un string, separ谩ndolos por el car谩cter indicado (character). Si no 
        se proporciona un car谩cter, el separador por defecto ser谩 una coma ","."""
        string = ''
        for item in self.data.values():
            string += str(item) + character
        return string[:-len(character)]

class MyList:
  def __init__(self):
    self.data = {}
    self.length = 0

  def append(self, item):
    self.data[self.length] = item
    self.length += 1

  def pop(self):
    self.length -= 1
    to_return = self.data[self.length]
    del self.data[self.length]
    return to_return

  def shift(self):
    item_index = 0
    to_return = self.data[item_index]
    while item_index < self.length - 1:
      self.data[item_index] = self.data[item_index + 1]
      item_index += 1
    self.pop()
    return to_return


  def unshift(self, item):
    item_index = self.length
    while item_index > 0:
      self.data[item_index] = self.data[item_index - 1]
      item_index -= 1
    self.data[item_index] = item
    self.length += 1

  def map(self, func):
    data_with_map = MyList()
    item_index = 0
    while item_index < self.length:
      data_with_map.append(func(self.data[item_index]))
      item_index += 1
    return data_with_map

  def filter(self, func):
    data_with_filter = MyList()
    item_index = 0
    while item_index < self.length:
      if func(self.data[item_index]):
        data_with_filter.append(self.data[item_index])
      item_index += 1
    return data_with_filter

  def join(self, character=","):
    item_index = 0
    string = ""
    while item_index < self.length - 1:
      string += f"{self.data[item_index]}{character}"
      item_index += 1
    return string + f"{self.data[item_index]}"

Soluci贸n 馃槃鈥
.

.
.
.
.

class MyList:
  def __init__(self):
    self.data = {}
    self.length = 0

  def append(self, item):
    self.data[self.length] = item
    self.length += 1

  def pop(self):
    self.length -= 1
    return self.data.pop(self.length)

  def shift(self):
    self.length -= 1
    self.data = {
      key-1: self.data[key] 
      for key in self.data
      }
    return self.data.pop(-1)
  
  def unshift(self, item):
    self.length += 1
    self.data = {
      key+1: self.data[key]
      for key in self.data
    }
    self.data = {**{0:item}, **self.data}

  def map(self, func):
    newList = MyList()
    newList.data = {
      key: func(self.data[key]) 
      for key in self.data
      }
    newList.length = len(newList.data)
    return newList

  def filter(self, func):
    newList = MyList()
    index = 0
    for key in self.data:
      if func(self.data[key]):
        newList.data[index] = self.data[key]
        index += 1
    newList.length = len(newList.data)
    return newList

  def join(self, character=","):
    return character.join([
      str(value) 
      for value in self.data.values()
      ])
class MyList:
    def __init__(self):
        self.data = {}
        self.length = 0

    def append(self, item):
        self.data[self.length] = item
        self.length += 1

    def pop(self):
        element = None
        if self.data != {}:
            element = self.data[self.length - 1]
            del self.data[self.length - 1]
            self.length -= 1
        return element

    def shift(self):
        element = None
        if self.data != {}:
            element = self.data[0]
            del self.data[0]
            self.data = {item - 1: value for item, value in self.data.items()}            
            self.length -= 1
        return element

    def unshift(self, item):
        if self.data != {}:
            aux = {0: item}
            for item, value in self.data.items():
                aux[item + 1] = value
            self.data = aux
            self.length += 1

    def map(self, func): 
        payload = MyList.__new__(MyList)
        payload.data = {}
        payload.length = self.length
        for item, value in self.data.items():
            payload.data[item] = func(value)
        return payload if payload else None

    def filter(self, func):
        payload = MyList.__new__(MyList)
        payload.data = {}
        payload.length = 0
        for item, value in self.data.items():
            if func(value):
                payload.data[payload.length] = value
                payload.length += 1
        return payload if payload else None

    def join(self, character = ','):
        string = ''
        if self.data != {}:
            for key, value in self.data.items():
                if key == self.length-1:
                    string += f'{value}'
                else:
                    string += f'{value}{character}'
        return string


Aqu铆 mi soluci贸n. Espero les ayude:

class MyList:
  def __init__(self):
    self.data = {}
    self.length:int = 0

  def append(self, item):
    if self.length == 0:
      self.data[0]=item
      self.length = 1
    else: 
      self.data[self.length]=item
      self.length += 1

  def pop(self):
    if self.length>0:
      last_item=self.data[self.length-1]
      del self.data[self.length-1]
      self.length-=1
      return last_item
    else: return

  def shift(self):
    if self.length>0:
      first_item=self.data[0]
      del self.data[0]
      self.data={index-1:self.data[index] for index in self.data}
      self.length-=1
      return first_item
    else: return


  def unshift(self, item):
    if self.length>0:
      self.data={index+1:self.data[index] for index in self.data}
      self.data[0]=item
      self.length+=1      
    else: return

  def map(self, func):
    if self.length>0:
      new_list=MyList()
      for item in self.data:
        new_list.append(func(self.data[item]))
      return new_list   
    else: return

  def filter(self, func):
    if self.length>0:
      new_list = MyList()
      for index in range(self.length):
        if func(self.data[index]):
          new_list.append(self.data[index])
      return new_list   
    else: return

  def join(self, character=","):
    if self.length>0:
      new_string=f"{self.data[0]}"
      for index in range(self.length-1):
        new_string+=f"{character}{self.data[index+1]}"
      return new_string   
    else: return
    
myList = MyList()
myList.append("Platzinauta")
myList.unshift("Hola!")
myList.append("Como esta?")

print(myList.data)
print(myList.length)
print(myList.join(' '))
print(myList.filter(lambda x:len(x)>=10))
myList.shift()
print(myList.join(' '))


print(myList.data)

# Output: {0: 'a', 1: 'b', 2: 'c'}

mapped_list = myList.map(lambda x: x.upper())
print(mapped_list.data)
# Output: {0: 'A', 1: 'B', 2: 'C'}

filtered_list = myList.filter(lambda x: x != "b")
print(filtered_list.data)
# Output: {0: 'a', 2: 'c'}

joined_string = myList.join("-")
print(joined_string)
# Output: 'a-b-c'

popped_item = myList.pop()
print(popped_item)
# Output: 'c'

shifted_item = myList.shift()
print(shifted_item)
# Output: 'a'

myList.unshift("d")
print(myList.data)
# Output: {0: 'd', 1: 'b'}

Me toco con ayuda 鈽癸笍 de hecho nunca hab铆a usado shift, unshift, y tambi茅n pens茅 que no se pod铆a utilizar append.

Mi soluci贸n :

.
.
.
.
.
.
.
.

.
.

class MyList:
  def __init__(self):
    self.data = {}
    self.length =0
    pass

  def append(self, item):
    self.data[self.length]= item
    self.length +=1

  def pop(self):
    response = self.data[self.length-1]
    del self.data[self.length-1]
    self.length -=1
    return response
    pass

  def shift(self):
    response = self.data[0]
    del self.data[0]
    new ={valor-1:self.data[valor] for valor in self.data}
    self.data = new
    self.length -=1   
    return response

  def unshift(self, item):
    new = {valor+1:self.data[valor] for valor in self.data}
    new[0]= item
    new_2 = {key:new[key] for key in sorted(new)}
    self.data = new_2
    self.length +=1
    

  def map(self, func):
    new = MyList()
    for i in self.data:
      new.append(func(self.data[i]))
    return new
    

  def filter(self, func):
    new = MyList()
    for i in self.data:
      if func(self.data[i]):
        new.append(self.data[i])
    return new

  def join(self, character=","):
    text = ""
    for i in self.data:
      text +=f"{self.data[i]}" +f"{character}"
    return text[:-1]

Mi soluci贸n

al principio no entend铆 que las repuesta debian ser diccionario y lo hice todo con listas, luego me toco modificar todo mi codigo
*
*
*
*
*
*
*
*
*

class MyList:
  def __init__(self):
    # Tu c贸digo aqu铆 馃憞
    self.data = {}
    self.length = 0
   

  def append(self, item):
    # Tu c贸digo aqu铆 馃憞
    self.data[self.length] = item
    self.length +=1
   
  

  def pop(self):
    # Tu c贸digo aqu铆 馃憞
    last_item = self.data[self.length-1]
    del self.data[self.length-1]
    self.length -=1
    return last_item

  def shift(self):
    # Tu c贸digo aqu铆 馃憞
    first_item =self.data[0]
    for i in range(1, self.length):
      self.data[i-1] = self.data[i]
    del self.data[self.length-1]
    self.length -=1
    return first_item  

  def unshift(self, item):
    for i in range(self.length,0,-1):
      self.data[i]=self.data[i-1]
    self.data[0]=item
    self.length+=1

  def map(self, func):
    # Tu c贸digo aqu铆 馃憞
    newList =MyList()
    for i in self.data:
      newList.append(func(self.data[i]))
    return newList

    
  def filter(self, func):
    # Tu c贸digo aqu铆 馃憞
    newList =MyList()
    for i in self.data:
      if func(self.data[i]):
        newList.append(self.data[i])
    return newList
    

  def join(self, character=','):
    # Tu c贸digo aqu铆 馃憞
    string =''
    for i in self.data:
      if i < self.length-1:
        string += str(self.data[i])+character
      else:
        string +=  str(self.data[i])
    return string 

o
o
o
o
o
o
o
o

class MyList:
  def __init__(self):
    self.data   = dict()
    self.length = 0
  
  def append(self, item):
    self.data[self.length] = item
    self.length += 1

  def pop(self):
    if self.length > 0:
      dato_eliminado = self.data[self.length - 1]
      self.data.pop(self.length - 1)
      self.length -= 1
      return dato_eliminado

  def shift(self):
    if self.length > 0:
      dato_eliminado = self.data[0]
      self.data.pop(0)
      self.length -= 1
      for i in range(1, self.length + 1):
        self.data[i-1] = self.data[i]
      self.data.pop(self.length) 
      self.data = dict(sorted(self.data.items()))
      return dato_eliminado

  def unshift(self, item):
    for i in range(self.length, 0,  -1):
      self.data[i] = self.data[i-1]
    self.data[0] = item
    self.length += 1

  def map(self, func):
    salida = MyList()
    for i in range(self.length):
      salida.append(func(self.data[i]))
    return salida  

  def filter(self, func):
    salida = MyList()
    for i in range(self.length):
      if func(self.data[i]) == True:
        salida.append(self.data[i])
    return salida    

  def join(self, character=","):
    salida = ""
    for i in range(self.length):
      salida += str(self.data[i]) + character 
    return salida[0:-1]
lista = MyList()
print(type(lista))
lista.append("a")
lista.append("b")
lista.append("c")
lista.append("d")
lista.append("e")
lista.append("f")

print("original")
print(lista.data)
print(lista.length)
print("")

print("operacion pop")
print(lista.pop())
print(lista.data)
print(lista.length)
print("")

print("operacion shift")
print(lista.shift())
print(lista.data)
print(lista.length)
print("")

print("operacion unshift")
print(lista.unshift("aa"))
print(lista.data)
print(lista.length)
print("")

print("operacion map")
lista1 = lista.map(lambda x: x * 3)
print(lista.data)
print(lista.length)
print("mapeada")
print(lista1.data)
print(lista1.length)
print("")

print("operacion filter")
lista2 = lista.filter(lambda x: True if len(x) > 3 else False)
print(lista.data)
print(lista.length)
print("filtrada")
print(lista2.data)
print(lista2.length)
print("")

print("operacion join")
print(lista.join("_"))
print(lista.data)
print(lista.length)
print("")

No comprendo, si estamos trabando con listas porque las respuestas de los test deben ser diccionarios?


.
.
.
.
.

class MyList:
  def __init__(self):
    self._data = {} 
    self._length = 0 

  @property
  def data(self):
    return self._data
  
  @property
  def length(self):
    return self._length

  def append(self, item):
    self.data[self._length] = item
    self._length += 1

  def pop(self):
    if self._length == 0:
      return None
    last_item = self._data[self._length - 1]
    del self.data[self._length - 1]
    self._length -= 1
    return last_item

  def shift(self):
    if self._length == 0:
      return None
    first_item = self._data[0]
    for i in range(1, self._length):
      self._data[i - 1] = self._data[i]
      
    del self.data[self._length - 1]
    self._length -= 1
    return first_item

  def unshift(self, item):
    for i in range(1, self._length):
      self._data[i] = self._data[i - 1]
    self._data[0] = item
    self._length += 1

  def map(self, func):
    response = MyList()
    for i in range(self._length):
      response.append(func(self._data[i]))
      
    return response

  def filter(self, func):
    response = MyList()
    for i in range(self._length):
      if func(self._data[i]):
        response.append(self._data[i])
        
    return response

  def join(self, character=","):
    response = ""
    for i in range(self._length):
      response += str(self._data[i]) + character
    
    return response[:-1]
undefined