No tienes acceso a esta clase

隆Contin煤a aprendiendo! 脷nete y comienza a potenciar tu carrera

Arrays de dos dimensiones

8/23
Recursos

Aportes 69

Preguntas 9

Ordenar por:

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

o inicia sesi贸n.

Solucion al reto 2 sin aplicar la clase Grid:

clase Cube:

main:

Primer profesor desde que estoy en Platzi que explica medio pelo鈥

Me parece curioso que el m茅todo str de laguna manera es el m茅todo que se ejecuta cuando se usa la funci贸n print()
Si se fijan cualquier modificaci贸n que le hagan a este m茅todo se ver谩 reflejada en el print() que le hagan al objeto de la clase Grid.

Pru茅benlo y ver谩n lo que suede. Metan alg煤n print(鈥渉ola mundo鈥) en el str y se dar谩n cuenta.

Mi soluciones al reto.

1ra Parte - Incorpora un m茅todo para poblar sus slots

from array_clase import Array
import random


class Grid():
    def __init__(self, rows, columns, fill_value=None):
        self.data = Array(rows)
        for row in range(rows):
            self.data[row] = Array(columns, fill_value=fill_value)

    def get_height(self):
        return len(self.data)

    def get_width(self):
        return len(self.data[0])

    def __getitem__(self, index):
        return self.data[index]

    def __str__(self):
        result = ""

        for row in range(self.get_height()):
            for col in range(self.get_width()):
                result += str(self.data[row][col]) + " "

            result += "\n"

        return str(result)

    def random_fill(self, min, max):
        for i in range(self.get_height()):
            for j in range(self.get_width()):
                self[i][j] = random.randint(min, max)

Prueba del reto

from array2D import Grid
matrix = Grid(3,3)
matrix.random_fill(1,100)
print(matrix)

Salida

72 97 45 
33 97 65
18 11 100

2掳 parte del reto
Array 3D

from array2D import Grid
from array_clase import Array
import random


class Array3D():
    def __init__(self,depth, rows, columns,fill_value=None):
        self.data = Grid(rows, columns)
        for row in range(rows):
            for column in range(columns):
                self.data[row][column] = Array(depth, fill_value=fill_value)

    def get_rows(self):
        return self.data.get_height()

    def get_columns(self):
        return self.data.get_width()

    def get_depth(self):
        return len(self.data[0][0])
    
    def __getitem__(self, index):
        return self.data[index]

    def __str__(self):
        result = ""

        for depth in range(self.get_depth()):
            result += f'index depth: [{depth}] \n'
            for row in range(self.get_rows()):
                for column in range(self.get_columns()):
                    result += f'   {self.data[row][column][depth]} '
                result += "\n"
            result += "\n"
        return str(result)

    def random_fill3D(self, min, max):
        for i in range(self.get_rows()):
            for j in range(self.get_columns()):
                for x in range(self.get_depth()):
                    self[i][j][x] = random.randint(min, max)


Prueba de la clase

from array3D import Array3D

tensor3D =  Array3D(depth=2,rows=4,columns=3)
print(tensor3D.get_rows())
print(tensor3D.get_columns())
print(tensor3D.get_depth())
print()
print(tensor3D)

tensor3D.random_fill3D(0,9)
print(tensor3D)

Salida

4
3
2

index depth: [0]
   None    None    None
   None    None    None
   None    None    None
   None    None    None

index depth: [1]
   None    None    None
   None    None    None
   None    None    None
   None    None    None


index depth: [0]
   7    0    7
   9    0    5
   9    4    6
   1    5    0

index depth: [1]
   4    2    2
   6    4    5
   7    7    2
   5    5    4

Pesima forma de hacerse entender.

algun video de yt mejor explicado?

Podemos resolver el reto, utilizando las estructuras anteriores y llamando a sus metodos.

Este es mi aporte:

Salida:

Se me hace m谩s c贸modo entender los valores de ancho y alto de la matriz, de forma inversa a como lo operacionaliza el profesor.

Soluci贸n al reto:

from custom_arrays import Array
import random

class Cube:
    def __init__(self, rows: int, columns: int, layers: int, fill_value=None):
        """Generate a Cube from an array of rows, columns and layers.
        Args:
            rows (int): rows number by layer. X axis dimension.
            columns (int): columns number by row. Y axis dimesion.
            layers (int): number of layers. Z axis dimension.
            fill_value (NoneType, optional): Fill created cube with given value. Defaults to None.
        """
        self.data = Array(layers)
        for layer in range(layers):
            self.data[layer] = Array(rows, fill_value)
            for row in range(rows):
                self.data[layer][row] = Array(columns, fill_value)

    def get_layers(self):
        return len(self.data)

    def get_height(self, layer):
        return len(self.data[layer])

    def get_width(self, layer):
        return len(self.data[layer][0])

    def __getitem__(self, index):
        return self.data[index]

    def __str__(self):
        result = "\n"
        for layer in range(self.get_layers()):
            for row in range(self.get_height(layer)):
                for col in range(self.get_width(layer)):
                    result += str(self.data[layer][row][col]) + " "

                result += "\n"
            result += "\n"
        return str(result)
    
    def fill_none_values(self, start=1, end=100):
        for layer in range(self.get_layers()):
            for row in range(self.get_height(layer)):
                for col in range(self.get_width(layer)):
                    if self[layer][row][col] == None:
                        self[layer][row][col] = random.randint(start, end)

Un ejemplo:

cube_array = Cube(4,4,3)
cube_array.fill_none_values()
print(cube_array)

37 68 44 16
83 58 52 66
89 31 39 45
48 75 94 95

67 5 49 85
51 31 58 44
5 91 46 98
31 88 48 6

73 13 61 93
34 87 12 94
63 32 40 12
35 38 10 26

Reto 2:
Archivo MiCubo

from MiGrid import Grid
from MiArray import Array

class Cubo():

    def __init__(self, depth, rows, cols, value=None):
        self.__depth__ = depth
        self.__rows__ = rows
        self.__cols__ = cols

        self.cube = Array(depth, value)

        for depth in range(depth):
            self.cube.__setitem__(depth, Grid(rows, cols, value))
        

    def __getdepth__(self):
        return len(self.cube)

    def __getheight__(self):
        return self.cube.__getitem__(0).__getheight()
    
    def __getwidth__(self):
        return self.cube.__getitem__(0).__getwidth()

    def __getitem__(self, index):
        return self.cube.__getitem__(index)

    def __setitem__(self, deep, row, col, value):
        self.cube.__getitem__(deep).__setitem__(row, col, value)

    def __getvalue__(self, deep, row, col):
        return self.cube.__getitem__(deep).__getvalue__(row, col)
    
    def __populate__(self, random_number_end):
        for depth in range(self.__depth__):
            self.cube.__getitem__(depth).__populate__(random_number_end)

    def __str__(self):
        result = ''
        result += self.cube.__str__() + '\n\r'
        result += '[\n\r'
        for deep in range(self.__depth__):
            result += '\t' + self.cube.__getitem__(deep).__str__() + '\n\r'
        result += ']'
        return result
    


Despu茅s de dos d铆as completos repasando clases anteriores y practicando con bucles anidados lo logr茅, aqu铆 mi c贸digo:

from grid import Grid
from arreglo import Arreglo
import random


class Cube():
    def __init__(self, height, width, depth, fill_value='None'):
        self.height = height
        self.width = width
        self.depth = depth
        self.elements = Arreglo(depth)
        for element in range(depth):
            self.elements[element] = Grid(height, width, fill_value)
        
            
    
    def adding_idx(self):
        for d in range(self.depth):
            for h in range(self.height):
                for w in range(self.width):
                    element = self.elements[d].data[h].items[w]
                    self.elements[d].data[h].items[w] = element+str(h+1)+str(w+1)+str(d+1)
    
    def adding_random(self, lower, upper):
        for d in range(self.depth):
            for h in range(self.height):
                for w in range(self.width):
                    self.elements[d].data[h].items[w] = random.randint(lower,upper)


    def __show_values__(self):
        print('-----'*5)
        for element in self.elements:
            print(element)
        print('-----'*5)

le agregu茅 un 铆ndice en uno de los m茅todos.

Aporte al primer reto

import random

class Array:
    def __init__(self, capacity, fill_value=None):
        self.capacity = capacity
        self.items = list()
        for i in range(capacity):
            self.items.append(fill_value)

    def __len__(self):
        return len(self.items)

    def __str__(self):
        return str(self.items)

    def __iter__(self):
        return iter(self.items)

    def __get__(self, index):
        return self.items[index]

    def __setitem__(self, index, new_item):
        self.items[index] = new_item

    def __insert_data__(self):
        for i in range(len(self)):
            self.items[i] = random.randint(0,len(self))

    def __suma__(self):
        suma = 0
        for i in range(len(self)):
            suma += self.items[i]
        return suma

    def __sumados__(self):
        suma = sum(self.items)
        return suma

    def __encontrar_maximo__(self):
        maximo = max(self.items)
        return maximo

    def __calcula_promedio__(self):
        promedio = sum(self.items) / len(self)
        return promedio

solucion reto

from array import Array

class Cube:
    def __init__(self, rows, columns, depth, fill_value=None):
        self.data = Array(rows)
        for row in range(rows):
            self.data[row] = Array(columns)
            for column in range(columns):
                self.data[row][column] = Array(depth, fill_value)

    def populate(self, value):
        for row in range(len(self.data)):
            for column in range(len(self.data[row])):
                for depth in range(len(self.data[row][column])):
                    self.data[row][column][depth] = value

    def get_height(self):
        return len(self.data)

    def get_width(self):
        return len(self.data[0])

    def get_depth(self):
        return len(self.data[0][0])

    def __getitem__(self, index):
        return self.data[index]

Crea la clase sin usar las clases previas:

Sinceramente me toco con Bing, eso s铆 entend铆 todo 馃檰鈥嶁檪锔忦煇ю煇, al principio ten铆a la idea, pero si me demoro mucho tiempo por aprendizaje prefiero buscar ayudar, porqu茅 estaba como homero en la tercera dimensi贸n jaja.

Este es el resultado:

aplicando Cube, le agregue el metodo split para dividir las dimesiones si se desea.

esta fue la forma en que solucione

# el reto

# reto 1 y 2

class GridReto():
    def __init__(self, rows, columns, fill_value=None):
        self.data = Array(rows)
        for row in range(rows):
            self.data[row] = Array(columns, fill_value)

    def get_height(self):
        return len(self.data)

    def  get_width(self):
        return len(self.data[0])
    
    def __getitem__(self, index):
        return self.data[index]
    
    def __str__(self):
        result = ""

        for row in range(self.get_height()):
            for col in range(self.get_width()):
                result += str(self.data[row] [col]) + " "

            result += "\n"
        
        return str(result)
    
    def random_items(self):
        for row in range(self.get_height()):
            for col in range(self.get_width()):
                self[row][col] = randint(0, 10)
    

# reto 3

class Cube():
    def __init__(self, rows, columns, cloak, fill_value=None):
     self.data = Array(rows)
     for fil in range(rows):
         self.data[fil] = Array(columns)
         for col in range(columns):
             self.data[fil][col] = Array(cloak, fill_value)

    def get_height(self):
        return len(self.data)
    
    def get_width(self):
        return len(self.data[0])

    def get_depth(self):
        return len(self.data[0][0])
    
    def __getitem__(self, index):
        return self.data[index]
    
    def __str__(self):
        result = ""

        for row in range(self.get_height()):
            for col in range(self.get_width()):
                for fil in range(self.get_depth()):
                    result += str(self.data[row][col][fil]) + " "

                result += "\n"

        return str(result)
    
    def random_items(self):
        for row in range(self.get_height()):
            for col in range(self.get_width()):
                for fil in range(self.get_depth()):
                    self[row][col][fil] = randint(0, 100)

Listo! Excelente challenge! Class Cube construida y funcionando perfectamente鈥

El codigo:

from my_array import Array
import random

class Cube():
    # Metodo constructor del Cube
    def __init__(self, rows, columns, depth, fill_value=None):
        self.data = Array(rows)
        for row in range(rows):
            self.data[row] = Array(columns)
            for column in range(columns):
                self.data[row][column] = Array(depth)

    # Metodo para obtener la altura del Cube = cant de filas:
    def __getheight__(self):
        return len(self.data)
    
    # Metodo para obtener el ancho del Cube = cant de columnas:
    def __getwidth__(self):
        return len(self.data[0])
    
    # Metodo para obtener la profundidad del Cube
    def __getdepth__(self):
        return len(self.data[0][0])
    
    # Metodo para obtener un valor en particular:
    def __getitem__(self, r_index, c_index, d_index):
        return self.data[r_index][c_index][d_index]
    
    # Metodo para cambiar un valor en particular:
    def __setitem__(self, r_index, c_index, d_index, value):
        self.data[r_index][c_index][d_index] = value

    # Metodo para devolver los valores en string:
    def __str__(self):
        result = ""
        for row in range(self.__getheight__()):
            if result != "":
                result += "\n"
            for column in range(self.__getwidth__()):
                if result != "":
                    result += "\n"
                for face in range(self.__getdepth__()):
                    if self.data[row][column][face] == None:
                        result += str(self.data[row][column][face]) + " | "
                    else:
                        if self.data[row][column][face] < 10:
                            result += " " + str(self.data[row][column][face]) + " | "
                        else:
                            result += str(self.data[row][column][face]) + " | "
        return result
    
    # Metodo para rellenar con numeros random mi cubo:
    def __randomdata__(self):
        for row in range(self.__getheight__()):
            for column in range(self.__getwidth__()):
                for face in range(self.__getdepth__()):
                    self.data[row][column][face] = random.randint(0,100)
    
    # Metodo para sumar todos los valores:
    def __sumdata__(self):
        sum = 0
        for row in range(self.__getheight__()):
            for column in range(self.__getwidth__()):
                for face in range(self.__getdepth__()):
                    sum += self.data[row][column][face]
        return sum

Ejemplo de outputs obtenidos trabajando con Cubos:

20:36:49 馃懡 with 馃 mgobea 馃惗 in develop/python/data_structs_python took 1m 20.2s 鈥
鉃 python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from cube import Cube
>>> my_cube = Cube(5,4,3)
>>> print(my_cube)
None | None | None |
None | None | None |
None | None | None |
None | None | None |

None | None | None |
None | None | None |
None | None | None |
None | None | None |

None | None | None |
None | None | None |
None | None | None |
None | None | None |

None | None | None |
None | None | None |
None | None | None |
None | None | None |

None | None | None |
None | None | None |
None | None | None |
None | None | None |
>>> my_cube.__randomdata__()
>>> print(my_cube)
17 | 56 | 84 |
27 | 73 | 49 |
 6 | 53 | 81 |
37 | 78 | 81 |

 8 | 47 | 67 |
16 | 54 | 67 |
43 | 68 | 40 |
37 | 92 |  7 |

39 | 22 | 28 |
21 | 86 | 31 |
88 | 92 | 89 |
14 | 15 | 71 |

61 | 70 | 30 |
98 | 67 | 92 |
 2 | 78 | 41 |
34 | 30 | 80 |

71 | 71 | 19 |
82 | 88 | 47 |
52 | 57 | 46 |
19 | 73 | 41 |
>>> print(my_cube.__sumdata__())
3133

Espero les guste!!!

El primer reto se podr铆a resolver con el siguiente metodo:

    # Primer reto: 
    # Metodo para rellenar con numeros random:
    def __randomdata__(self):
        for row in range(self.__getheight__()):
            for column in range(self.__getwidth__()):
                self.data[row][column] = random.randint(0,100)

Antes del reto dejo como arm茅 el metodo str para que imprima con formato de matriz con separadores y todo y una imagen de como se puede ver:

Code:

    # Metodo para devolver los valores en string:
    def __str__(self):
        result = ""
        for row in range(self.__getheight__()):
            if result != "":
                result += "\n"
            for column in range(self.__getwidth__()):
                if self.data[row][column] == None:
                    result += str(self.data[row][column]) + " | "
                else:
                    if self.data[row][column] < 10:
                        result += " " + str(self.data[row][column]) + " | "
                    else:
                        result += str(self.data[row][column]) + " | "
        return result

Se ve as铆:

La parte 2 del reto tambi茅n la apliqu茅 en la clase 鈥楥ube鈥, por lo que pas贸 solo este c贸digo, al m茅todo lo llam茅 鈥fill鈥.
En mi caso de array se llama Challenge mi clase debido al reto de hace dos videos atr谩s.

from grid import Grid
from arrays import Challenge
import random

class Cube():
  def __init__(self, rows, columns, layers, fill_value=None):
    self.data = Challenge(rows)
    for row in range(rows):
      self.data[row] = Challenge(columns)
      for column in range(columns):
        self.data[row][column]= Challenge(layers, fill_value)

  def get_height(self):
    return len(self.data)
  
  def get_width(self):
    return len(self.data[0])

  def get_depth(self):
    return len(self.data[0][0])

  def __getitem__(self, index):
    return self.data[index]

  def __str__(self):
    result=""
    for row in range(self.get_height()):
      for column in range(self.get_width()):
        for layer in range(self.get_width()):
          result += str(self.data[row][column][layer]) + " "
        result += " "
      result += '\n'
    return str(result)
    
  def __fill__(self):
    for row in range(self.get_height()):
      for column in range(self.get_width()):
        for layer in range(self.get_depth()):
          self.data[row][column][layer] = random.randint(1,100)

Este es mi aporte del reto

from Array import Array
from Grid import Grid

class Cube:

    def __init__(self,rows,cols,layers,value=None) -> None:
        self.cube = Array(layers)

        for layer in range(layers):
            self.cube[layer] = Grid(rows,cols,value)

    def __setitems__(self,i,j,k,value):
        self.cube[i][j][k] = value

    def __getlayers__(self,i):
        return self.cube[i]
    
    def __getitem__(self,i):
        return self.__getlayers__(i)

    def layers(self):
        return len(self.cube)

    def rows(self):
        return self.cube[0].rows()
    
    def columns(self):
        return self.cube[0].columns()

    def __str__(self):
        cube = ""
        for count,layer in enumerate(self.cube):
            for row in layer:
                cube = cube + str(row) + "\n" 
            if count < self.layers()-1: 
                cube = cube + " -"*3  + "\n" 
        return cube
    

if __name__ == "__main__":

    matrix3d = Cube(3,3,2,1)

    # probando metodos
    matrix3d[0][1][1] = 12                              # setitems
    matrix3d[1][1][1] = 12                              # setitems
    print("matrix3d[0][1][1] = ",matrix3d[0][1][1])     # getistems
    print("layers = ",matrix3d.layers())                # layers number => profundidad
    print("rows = ",matrix3d.rows())                    # rows number => filas 
    print("columms = ",matrix3d.columns())              # columns number => filas
    print("matrix3d =\n",matrix3d)                      # __str__ 

Aporte

class Cube():

    def __init__(self, rows, columns, length) :
        self.data = Grid(rows,columns)
        for row in range(rows):
            for col in range(columns):
                self.data[row][col] = Array(length)

    def get_rows(self):
        return self.data.get_height()

    def get_column(self):
        return self.data.get_width()

    def get_depth(self):
        return len(self.data[0][0])
    
    def __str__(self):
        result = " "
    
        for row in range(self.get_rows()):
            for column in range(self.get_column()):
                for prof in range(self.get_depth()):
                    result += str(self.data[row][column][prof]) + " "
                result += "\n"
        return str(result)

    def randomsplot(self, min, max):
        for i in range(self.get_rows()):
            for j in range(self.get_column()):
                for k in range(self.get_depth()):
                    self.data[i][j][k] = random.randint(min,max)

Mi aporte de la clase Grid, tambi茅n he decidido agregar una funci贸n para poblar el arreglo bidimensional:

from arrays import Array
import random


class Grid(object):
    
    def __init__(self, rows, columns, default_value=None):
        self.data = Array(rows)
        for row in range(rows):
            self.data[row] = Array(columns, default_value)

    def get_height(self):
        return len(self.data)

    def get_width(self):
        return len(self.data[0])
    
    def __getitem__(self, index):
        return self.data[index]

    def __str__(self):
        result = ""
        for row in range(self.get_height()):
            for col in range(self.get_width()):
                result += str(self.data[row][col]) + " "
            
            result += "\n"
        
        return str(result)

    def __populate__(self):
        for row in range(self.get_height()):
            for column in range(self.get_width()):
                self.data[row][column] = random.randint(0, (len(self.data) * len(self.data[0])))


if __name__ == '__main__':
    matrix = Grid(3,4)
    matrix.__populate__()
    print(matrix.__str__()) 

crear array en 3D

import random
from crear_array import array

class array_3D():


    def __init__(self,rows,columns,depths, fill_value =None)-> None:
        self.data = array(rows) 
        for row in range(rows):
            self.data[row] = array(columns)
            for column in range(columns):
                self.data[row][column] = array(depths,fill_value)


    def __get_height__(self):
        return len(self.data)
    

    def __get_width__(self):
        return len(self.data[0])

    def __get_depth__(self):
        return len(self.data[0][0])

    def __str__(self) -> str:
        result = ""
        for row in range(self.__get_height__()):
            for col in range(self.__get_width__()):
                for depth in range(self.__get_depth__()):
                    result += str(self.data[row][col][depth]) + " "
                result += "\n"
        return str(result)

    
    def __random_numbers__(self):
        for row in range(self.__get_height__()):
            for col in range(self.__get_width__()):
                for depth in range(self.__get_depth__()):
                    self.data[row][col][depth] = random.randint(10,20)

    
if __name__ == '__main__':
    matrix = array_3D(5,5,5)
    print(matrix.__get_height__())
    print(matrix.__get_width__())
    matrix.__random_numbers__()
    print(matrix.__str__())
    print(matrix.__getitem__(0)[2])
from array1 import Array1
from grid import Grid

import random

class Cube():
	def __init__(self, rows, columns, depth, fill_value=None):
		self.data = Grid(rows, columns)

		for row in range(self.data.get_height()):
			for column in range(self.data.get_width()):
				self.data[row][column] = Array1(depth, fill_value)


	def get_height(self):
		return self.data.get_height()

	def get_width(self):
		return len(self.data[0])

	def get_depth(self):
		return len(self.data[0][0])

	def __getitem__(self, index):
		return self.data[index]

	def __fill__(self):
		for row in range(self.get_height()):
			for col in range(self.get_width()):
				for dep in range(self.get_depth()):
					self.data[row][col][dep] = random.randint(0,int(self.get_width() * self.get_height() * self.get_depth()))

	def __str__(self):
		result = ""

		for row in range(self.get_height()):
			for col in range(self.get_width()):
				for dep in range(self.get_depth()):
					result += str(self.data[row][col][dep]) + " "
				result += "\n"
			result += "\n"

		return str(result )

Yo agregue un metodo de suma al array de dos dimensiones ya que llegue tarde para crear los metodos de rellenar.

from random import randint

class Grid():
    def __init__(self, rows, columns, fill_value=None):
        self.data = Array(rows)
        for row in range(rows):
            self.data[row] = Array(columns) # aqui se habia pasado fill_value, pero no es necesario
        
    def get_height(self):
        return len(self.data)
    
    def get_width(self):
        return len(self.data[0])
    
    def __getitem__(self, index):
        return self.data[index]
    
    def __str__(self):
        result = ''
        for row in range(self.get_height()):
            for col in range(self.get_width()):
                result += str(self.data[row][col]) + ' '
            result += '\n'
        return str(result)
    
    def random_fill(self, min, max):
        for i in range(self.get_height()):
            for j in range(self.get_width()):
                self[i][j] = randint(min, max)
        # return [randint(min, max) for j in range(self.get_width()) for i in range(self.get_height())]  
            
    def __sum__(self):
        """Return the sum of the elements inside the array"""
        return reduce(lambda a, b: a + b, list(map(int, matrix.__str__().rstrip().split())))
    
    
if __name__ == '__main__':
    matrix = Grid(3,3)
    print(matrix)

    for row in range(matrix.get_height()):
        for column in range(matrix.get_width()):
            matrix[row][column] = row * column
            
    print(f'la matrix:\n{matrix}')

    print(f'La matriz es {matrix.get_height()}x{matrix.get_width()}')
    print(matrix.__str__())
    print(matrix.__getitem__(1)[1])
    print(f'La suma de nuestra matriz es: {matrix.__sum__()}')
    
    matrix.random_fill(1,100)
    print(matrix)
    print(f'La suma de nuestra matriz es: {matrix.__sum__()}')

CUBO

from c_array import Array

class Cubo():
def init(self, x, y, z, fill_value=None):
self.x = x
self.y = y
self.z = z
self.cubo = Array(x, fill_value)
for i in range(x):
self.cubo[i] = Array(y, fill_value)
for i in range(x):
for j in range(y):
self.cubo[i][j] = Array(z, fill_value)

def get_height(self):
    return self.x

def get_width(self):
    return self.y

def get_long(self):
    return self.z

def __getitem__(self, row, col, lar):
    return self.cubo[row] [col] [lar]

def __str__(self):
    resultx = ""
    for i in range(self.get_height()):
        resulty = ""
        for j in range(self.get_width()):
            resultj = ""
            for k in range(self.get_long()):
                resultj += str(self.cubo[i] [j] [k]) + " "
            resulty += resultj + "| "
        resultx += resulty + "\n"
    return str(resultx)

def carga_cubo(self):
    for i in range(self.x):
        for j in range(self.y):
            for k in range(self.z):
                self.cubo[i] [j] [k] =  i * j * k

primero la clase Array:

from my_array import Array

class Grid():

    def __init__(self, rows, columns, value = None):
        self.rows = rows
        self.columns = columns
        self.items = [Array(self.rows) for i in range (self.columns)]



    def get_rows(self):
        return self.rows


    def get_columns(self):
        return self.columns

    def __get_item__(self, row, column):
        line_array = self.items[column]
        return line_array.__getitem__(row)

    def __str__(self):
        result = ''
        for column in range(self.columns):
            line_array=self.items[column]
            result+=line_array.__str__() + '\n'
        return result
    
def main():
    a = Grid(2,3)
    print(a)

if __name__ == '__main__':
    main()

Ahora la clase Cube:

from grid import Grid

class Cube():

    def __init__(self, rows, columns, depths):
        
        self.rows = rows
        self.columns = columns
        self.depths = depths
        self.items = [Grid(self.rows, self.columns) for i in range(self.depths)]

    
    def get_rows(self):
        return self.rows


    def get_columns(self):
        return self.columns

    def __get_item__(self, row, column, depth):
        matrix = self.items[depth]
        valor = matrix.__get_item__(row,column)
        return valor

    def __str__(self):
        result = ''
        for depth in range(self.depths):
            matrix=self.items[depth]
            result+=matrix.__str__() + '\n'
        return result
    
def main():
    a = Cube(3,4,5)
    print(a.__get_item__(1,1,1))
    print(a)

if __name__ == '__main__':
    main()

Mi soluci贸n:

from class_array import Array
from class_grid import Grid
from random import randint

class Cube():
    def __init__(self, rows, columns, depth, fill_value = None) -> None:
        self.data = Grid(rows, columns)
        for i in range(rows):
            for j in range(columns):
                self.data[i][j] = Array(depth, fill_value)
    
    def get_heigth(self):
        return Grid.get_heigth(self.data)

    def get_witdh(self):
        return len(self.data[0])

    def get_depth(self):
        return len(self.data[0][0])

    def __getitem__(self, index):
        return self.data[index]
    
    def __str__(self):
        result = ''
        for row in range(self.get_heigth()):
            for column in range(self.get_witdh()):
                for col in range(self.get_depth()):
                    result += str(self.data[row][column]) + ' '
            result += '\n'
        return str(result)
    
    def fill_cube(self, low=1, hig=99):
        for row in range(self.get_heigth()):
            for column in range (self.get_witdh()):
                for col in range (self.get_depth()):
                    self.data[row][column][col] = randint(low, hig)

if __name__ == '__main__':

    test = Cube(3,3,3)
    print(test)
    print(test.get_heigth())
    print(test.get_witdh())
    print(test.get_depth())
    test.fill_cube()
    print(test)

Me cost贸 pero lo logr茅 Platzi! 馃挭


class Cube:
    '''
    Crea un array3d de tama帽o x*y*z de valor: fill_value. Considere
    el 铆ndice del primer elemento como [1,1,1].
    '''
    def __init__(self, x,y,z,fill_value=None):
        self.numrows = x
        self.numcols = y
        self.nummatrix = z
        self.items = [[[fill_value for i in range(y)] for i in range(x)] for i in range(z)]

    def numcols(self):
        return self.numcols
        
    def numrows(self):
        return self.numrows

    def depth(self):
        return self.nummatrix

    def __setitem__(self,x,y,z,value):
        matrix = self.items[z-1]
        row = matrix[x-1]
        row[y-1] = value

    def __getitem__(self,x,y,z):
        matrix = self.items[z-1]
        row = matrix[x-1]
        element = row[y-1]
        return element

    def __str__(self):
        return str(self.items)

Soluci贸n al problema 鈥淥BJECT DOES NOT SUPPORT ITEM ASSIGNAMENT鈥

隆Hola!
Tuve el mismo error y aqu铆 les dejo la respuesta:

  1. En corto, chequen que sus m茅todos __getitem __ y setitem est茅n escritos exactamente as铆
  2. Igual, en corto鈥 ch茅quen que __getitem __ tenga un return (para retornar el valor) y setitem no (porque este coloca un valor, no lo regresa)
  3. Cuando nos menciona 鈥淢yArray鈥 object does not support item assignament est谩 indic谩ndonos que el objeto que no soporta esta operaci贸n es MyArray, no Grid, por lo tanto el error estar谩 en el c贸digo de la clase pasada en donde definimos el objeto MyArray .

El tema no est谩 de lo mejor explicado, pero aqu铆 dejo un resumen:

  • El tema se llama 鈥dunder methods鈥 o 鈥渕agic methods鈥
  • Los 鈥渄under methods鈥 sobreescriben m茅todos ya preconstruidos en python (built-in methods) o sea鈥 no podemos crear nombres a lo wey, estos nombres dependen de los m茅todos predefinidos en python.
  • Finalmente estamos sobreescribiendo un m茅todo, por lo que debemos aclarar si regresa alg煤n valor o no.

utilizar las list comprehentions se hace el codigo mas corto y legible.

no recuerdo si el termino tensor se aplica a partir de la tercera dimensi贸n o si tiene otro nombre, entonces le puse igualmente tensor al nombre de la variable.
aqu铆 les dejo el c贸digo

from r_grid import Grid
from r_array import Array
from random import randint as rd

class Cube():
    def __init__(self, depth, rows,columns, fill_value=None):
        #self.tensor = Array(depth, fill_value=None)
       # for matrix in range(depth):
        #    self.tensor[matrix] = Grid(rows, columns, fill_value=None)

        self.tensor = [Grid(rows, columns) for i in range(depth)]

    def get_depth(self):
        return len(self.tensor)

    def get_height(self):
        return self.tensor[0].get_height()
    
    def get_width(self):
        return self.tensor[0].get_width()

    def __getitem__(self, index):
        return self.tensor[index]

    def set_random(self, lower, upper):
        for matrix in range(self.get_depth()):
            self.tensor[matrix].set_random(lower, upper)

    def set_lin_sec(self, first):
        x = first
        for matrix in range(self.get_depth()):
            self.tensor[matrix].set_lin_sec(x)
            x = self.tensor[matrix][-1][-1] + 1

    def __str__(self):

        result = ""
        for matrix in range(self.get_depth()):
            result += str(self.tensor[matrix]) + "\n"
        return str(result)
    print(matrix[1])
    print(matrix.__getitem__(1))
    print(matrix.__getitem__(1)[1])
    print(matrix.__str__())

RPTA:

[0, 1, 2]
[0, 1, 2]
1
0 0 0 
0 1 2 
0 2 4 

El mismo codigo con resultados algo distintos

Mi Solucion al reto 3

from array_ import Array
from grid import Grid
import random


class Cube(object):

    def __init__(self, rows, columns, cells, fill_value=None):
        self.rows = rows
        self.columns = columns
        self.cells = cells
        self.data = Grid(rows, columns, fill_value)
        for row in range(rows):
            for col in range(columns):
                for cell in range(cells):
                    self.data[row][col] = Array(cells, fill_value)

    def get_height(self):
        return len(self.data)

    def get_width(self):
        return len(self.data[0])

    def get_deep(self):
        return len(self.data[0][0])

    def __getitem__(self, row, col, cell):
        return self.data[row][col][cell]

    def __fillRandom__(self, min=0, max=10):
        for row in range(self.rows):
            for col in range(self.columns):
                for cell in range(self.cells):
                    self.data[row][col][cell] = random.randint(min, max)

    def __str__(self):
        result = ""

        for row in range(self.get_height()):
            for col in range(self.get_width()):
                result += "["
                for cell in range(self.get_deep()):
                    result += str(self.data[row][col][cell])+" "
                result += "]\n"
            result += "\n"
        return str(result)

El codigo para probar la estructura de datos:

from cube import Cube

def run():
    cube = Cube(3,3,3, 1)
    print(cube.get_height())
    print(cube.get_width())
    print(cube.get_deep())
    print(cube)
    
    print(cube.__getitem__(0,0,0))
    cube.__fillRandom__()
    print(cube.__getitem__(2,2,2))

    print(cube)

if __name__ == "__main__":
        run()

Y este fue el resultado:

3
3
3
[1 1 1 ]
[1 1 1 ]
[1 1 1 ]

[1 1 1 ]
[1 1 1 ]
[1 1 1 ]

[1 1 1 ]
[1 1 1 ]
[1 1 1 ]


1
4
[6 5 1 ]
[0 1 9 ]
[10 4 6 ]

[5 5 3 ]
[0 1 2 ]
[5 7 6 ]

[5 5 5 ]
[9 9 8 ]
[3 9 4 ]
  1. Soluci贸n al reto de una clase Grid, incorporando un m茅todo para poblar sus slots
from array import Array
import random


class Grid():
    
    def __init__(self, rows, columns, fill_value = None):
        self.data = Array(rows) 
        
        for row in range(rows):
            self.data[row] = Array(columns, fill_value)

    
    def get_height(self):
        return len(self.data)


    def get_width(self):
        return len(self.data[0])


    def __getitem__(self, index):
        return self.data[index]


    def __str__(self):
        result = ""

        for row in range(self.get_height()):
            for col in range(self.get_width()):
                result += str(self.data[row][col]) + " "

            result += "\n"

        return str(result)


    def random_fill(self, min, max):
        for row in range(self.get_height()):
            for column in range(self.get_width()):
                self.data[row][column] = random.randint(min, max)
  1. Soluci贸n al reto de crear una clase Cube (array de 3 dimensiones)
from array import Array
from grid_reto import Grid
import random


class Cube():
    # metodo constructor
    def __init__(self, rows, columns, depth, fill_value = None):
        self.data = Grid(rows, columns) 
        
        for row in range(rows):
            for column in range(columns):
                self.data[row][column] = Array(depth, fill_value)
        
    
    def get_rows(self):
        return self.data.get_height()


    def get_columns(self):
        return self.data.get_width()


    def get_depth(self):
        return len(self.data[0][0])


    def __getitem__(self, index):
        return self.data[index]


    def __str__(self):
        result = ""

        for row in range(self.get_rows()):
            for col in range(self.get_columns()):
                for depth in range(self.get_depth()):
                    result += str(self.data[row][col][0]) + " "

            result += "\n"

        return str(result)

    
    def random_fill(self, min, max):
        for row in range(self.get_rows()):
            for column in range(self.get_columns()):
                for depth in range(self.get_depth()):
                    self.data[row][column][depth] = random.randint(min, max)

Challenge one:

Return:

Two:

Return:

Qu茅 ch茅vere, me divert铆 mucho haciendo ambos ejercicios. Comparto mi soluci贸n para el array-3D y un screenshot de la impresi贸n formateada. 馃構

Mi soluci贸n:

from arrays import Array

class Cube():

    def __init__(self, rows, columns, depth, fill_value = None):
        """
        Create tri-dimensional Arrays
        Giving numbers of rows, columns, and depth to get an Array
        """
        self.cube = [Array(columns, Array(depth)) for i in range(rows)]

    def get_height(self):
        return len(self.cube)

    def get_width(self):
        return len(self.cube[0])

    def get_depth(self):
        return len(self.cube[0][0])

    def __getitem__(self, index):
        return self.cube[index]

    def __str__(self):
        """
        Return string values from a tri-dimensional array
        """
        result = ""

        for row in range(self.get_height()):
            for column in range(self.get_width()):
                for depth in range(self.get_depth()):
                    result += str(self.cube[row][column][depth]) + " "
            
            result += "\n"
        
        return str(result)

Primer Reto: a帽ade algo que pueble los espacios de los arrays, sean random o secuenciales.

def __setitem__(self, row, column, value):
        self.data[row][column] = value

    def __setRandints__(self):
        for i in range(self.get_height()):
            self.data[i] = [randint(0, self.get_width()) for i in range(self.get_width())] 

Hice una peque帽a funci贸n setitem para que se pueda agregar manualmente.

Array 2D

class Grid():
    
    def __init__(self, rows, columns, fill_value=None):
        
        # Defines the rows of the array
        self.data = Array(rows)
        
        # Defines the columns of the array and set their default values
        for row in range(rows):
            self.data[row] = Array(columns, fill_value=fill_value)

    def get_height(self):
        return len(self.data)

    def get_width(self):
        return len(self.data[0])

    def __getitem__(self, row, column):
        return self.data[row][column]

    def __str__(self):
        string = ""

        for row in range(self.get_height()):
            for col in range(self.get_width()):
                string += str(self.data[row][col]) + " "

            string += "\n"

        return str(string)

    def __populate__(self, min_value, max_value):
        for row in range(self.get_height()):
            for column in range(self.get_width()):
                self.data[row][column] = random.randint(min_value, max_value)
                
        print(self)
from grid import Grid

class Cube:
    def __init__(self, rows, columns, depth, fill_values=None):
        self.data = []

        for cell in range(depth):
            self.data.append(Grid(rows, columns))
        
        print(self.data[0])
    

    def get_depth(self):
        return len(self.data)
    
    def get_height(self):
        return self.data[0].get_height()
    
    def get_width(self):
        return self.data[0].get_width()

    def __str__(self):
        result = ''

        for depth in range(self.get_depth()):
            result += '['
            for row in range(self.get_height()):
                result += '['
                for column in range(self.get_width()):
                    result +=  str(self.data[depth][row][column]) + ','
                result += '],\n'

            
            result += ']'

        return result
    

Mi soluci贸n al reto del cubo:

from array import Array
from random import randint

class Cube():
    def __init__(self, rows, columns, deeps, fill_value=None):
        self.data = Array(rows)
        for row in range (rows):
            self.data[row] = Array(columns)
            for col in range(columns):
                self.data[row][col] = Array(deeps, fill_value)
            
    def get_height(self):
        return len(self.data)
    
    def get_width(self):
        return len(self.data[0])
    
    def get_depth(self):
        return len(self.data[0][0])
    
    def __getitem__(self, index):
        return self.data[index]
    
    def __str__(self):
        result = "\n"*2
        for row in range(self.get_height()):
            result += "{ "
            for col in range(self.get_width()):
                for deep in range(self.get_depth()):
                    result += "[" + str(self.data[row][col][deep]) + "],"
                result = result[:-1] + " ; "
            result = result[:-3] + " }" + "\n"*2
        return str(result)
    
    def fill_cube_rand(self):
        for i in range(self.get_height()):
            for j in range(self.get_width()):
                for k in range(self.get_depth()):
                    self[i][j][k] =  randint(10, 100)
    
    def fill_cube_xyz(self):
        for i in range(self.get_height()):
            for j in range(self.get_width()):
                for k in range(self.get_depth()):
                    self[i][j][k]= f'{i},{j},{k}'
    


if __name__ == '__main__':
    hexaedro = Cube(7, 5, 2)
                
    print(f'\n  Height= {hexaedro.get_height()}, Width= {hexaedro.get_width()}, Depth= {hexaedro.get_depth()} \n')
    
    hexaedro_xyz = hexaedro
    hexaedro_xyz.fill_cube_xyz()
    print(hexaedro_xyz.__str__())     

    hexaedro.fill_cube_rand()
    print(hexaedro.__str__())     

Salida en Consola:

![](

Agregue la sumatoria de filas y columnas como totales

#sumando filas y columnas
    def __sumRow__(self):
        suma = 0
        for row  in range(self.get_height()):
            for column in range(self.get_width()):
                n = self[row][column]
                suma += n
            print('Fila ',row, 'Suma ', suma)

    def __sumCol__(self):
        suma = 0
        for column in range(self.get_width()):
            for row  in range(self.get_height()):
                n = self[row][column]
                suma += n
            print('Columna ',column, 'Suma ', suma)

y en el cube le agregue un random

def __randReplace__(self, min, max):
        for row  in range(self.get_height()):
            for column in range(self.get_width()):
                for depth in range(self.get_depth()):
                    self[row][column][depth] = random.randint(min, max)

oyeeee, no mames, eso esta genial profe

Mi reto qued贸 as铆:

from array import Array
from grid import Grid
import logging


logging.basicConfig(filename="platzi.log")
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class Cube:

    def __init__(self, rows, columns, slots, fill_value=None):
        log.debug("Cube constructor")
        self.data = Grid(rows, columns)
        for row in range(rows):
            for column in range(columns):
                self.data[row][column] = Array(slots, fill_value)

    def get_height(self):
        log.debug("get_height method")
        return self.data.get_height()

    def get_width(self):
        log.debug("get_width method")
        return self.data.get_width()

    def get_depth(self):
        log.debug("get_depth method")
        return len(self.data[0][0])

    def __getitem__(self, index):
        log.debug("__getitem__ method")
        return self.data[index]

    def __str__(self):
        log.debug("__str__ method")
        result = ""
        for slot in range(self.get_depth()):
            for row in range(self.get_height()):
                for col in range(self.get_width()):
                    result += str(self.data[row][col][slot]) + " "
                result += "\n"
            result += "\n"
        return str(result)

Reto 1:
Archivo MiArray:

import random
from functools import reduce

class Array:

    def __init__(self, capacity, value=None):
        self.items = list()
        self.__capacity = capacity
        for i in range(capacity):
            self.items.append(value)

    def __len__(self):
        return len(self.items)

    def __str__(self):
        return str(self.items)

    def __iter__(self):
        return iter(self.items)

    def __getwidth__(self):
        return len(self.items)

    def __getitem__(self, index):
        return self.items[index]
    
    def __setitem__(self, index, value):
        self.items[index] = value

    def __populate__(self, random_ini, random_end):
        #Realizando pruebas verifico que este puede tirar n煤mero duplicados
        #self.items = random.choices(range(random_ini, random_end), k=self.__capacity)
        
        #No duplicamos los n煤meros
        self.items = random.sample(range(random_ini, random_end), self.__capacity)

    def __sum__(self):
        #Solo sirve para sumas
        #sum(self.items)
        return reduce(lambda a, b: a+b, self.items)

Archivo MiGrid

import functools
from MiArray import Array
import random
from functools import reduce

class Grid():

    def __init__(self, rows, cols, value=None):

        self.__cols__ = cols
        self.__rows__ = rows

        self.grid = Array(rows, value)
        for row in range(rows):
            self.grid.__setitem__(row, Array(cols, value))

    def __getrow__(self, row):
        return self.grid.__getitem__(row)

    def __setitem__(self, row, col, value):
        self.grid.__getitem__(row).__setitem__(col, value)

    def __getvalue__(self, row, col):
        get_row = self.__getrow__(row)
        return get_row.__getitem__(col)

    def __getheight__(self):
        return len(self.grid)

    def __str__(self):
        result = ''
        for row in range(self.__rows__):
            result += self.grid.__getitem__(row).__str__()
        return result

    def __getwidth__(self):
        return self.__getrow__(0).__getwidth__()

    def __populate__(self, random_number_end):
        for row in range(self.__rows__):
            self.grid.__getitem__(row).__populate__(0, random_number_end)
        return self.grid

    def __sum__(self):
        sum = 0
        for row in range(self.__rows__):
            sum += self.grid[row].__sum__()
        return sum

Me tom贸 cerca de 24 hs descubrir que debia usar los m茅todos creados en los otros m贸dulos, y c贸mo usarlos. Pero creo que ya comprend铆 como funciona. Solo tengo un par de dudas respecto al doble gui贸n bajo, si lo borro me da error.

from arrays import Array
from grid import Grid
from random import randint
from functools import reduce

class Cubo():
    def __init__(self, y, x, z, fill_value=None):
        self.data = Grid(y, x)
        for i in range(y):
            for j in range(x):
                self.data[i][j] = Array(z,fill_value)

    def get_height(self):
        return self.data.get_height()

    def get_width(self):
        return self.data.get_width()

    def get_deep(self):
        return len(self.data[0][0])

    def __getitem__(self, y, x): #esto creo que devuelve el espacio en memoria
        return self.data[y][x] #y le debo agregar el 铆ndice para pedir el elemento

    def __setitem__(self, y, x, z, new_item):
        self.__getitem__(y,x)[z] = new_item

    def __str__(self):
        result = ""

        for row in range(self.get_height()):
            for col in range(self.get_width()):
                result += "|"
                for deep in range(self.get_deep()):
                    result += str(self.__getitem__(row, col)[deep]) + " "
                result += "|"

            result += "\n"
        return str(result)

    def rand_replace(self, min= 0, max=9):
        for row in range(self.get_height()):
            for col in range(self.get_width()):
                for deep in range(self.get_deep()):
                    self.__setitem__(row,col,deep,randint(min, max))

    def order_replace(self, start=0):
        count= 0
        for row in range(self.get_height()):
            for col in range(self.get_width()):
                for deep in range(self.get_deep()):
                    self.__setitem__(row,col,deep,count)
                    count+=1

    def suma(self):
        sumatoria = 0
        for row in range(self.get_height()):
            for col in range(self.get_width()):
                sumatoria += reduce(lambda a, b: a+b, self.__getitem__(row,col))
        return(sumatoria)

![](

Lo logre, pero me ayude bastante de lo ya comentado

from grid_2 import Grid
from array_1D import Array
from random import randint

class Cube:
    def __init__(self, rows, columns, deep, fill_value = None):
        self.data = Grid(rows, columns)
        for row in range(rows):
            for col in range(columns):
                self.data[row][col] = Array(deep)
                
    def get_height(self):
        return (self.data.get_height())
    
    def get_width(self):
        return (self.data.get_width())
    
    def get_depth(self):
        return (len(self.data[0][0]))
    
    def __getitem__ (self, index):
        return (self.data[index])
    
    def __str__(self):
        result = ""
        for row in range(self.get_height()):
            for col in range(self.get_width()):
                for d in range(self.get_depth()):
                    result += str(self.data[row][col][d]) + " "
                
                result += "\n"
                
        return result
    
    def fill_values(self):
        for row in range(self.get_height()):
            for col in range(self.get_width()):
                for d in range(self.get_depth()):
                    self.data[row][col][d] = randint(1,15)

Mi soluci贸n al array de 3 dimensiones鈥

import random
from customArray import Array
from customGrid import Grid

class Cube:

    def __init__(self, rows: int, columns: int, depth: int, fill_value: int = None):
        self.data = Grid(rows , columns)
        for row in range(rows):
            for column in range(columns):
                self.data[row][column] = Array(depth, fill_value)

    def get_height(self):
        "Returns the height of the cube"
        return self.data.get_height()
    
    def get_width(self):
        "Returns the width of the cube"
        return self.data.get_width()
    
    def get_depth(self):
        "Returns the depth of the cube"
        return len(self.data[0][0])

    def get_item(self, index: int):
        "Returns an item of the cube"
        return self.data[index]
    
    def set_item(self, row, column, depth, new_item):
        "Sets an item in a certain position of the 3 dimensional array"
        self.data[row][column][depth]= new_item

    def __str__(self):
        "String representation of the 3 dimensional array"
        result=""
        print("\n")
        for deep in range(self.get_depth()):
            for row in range(self.get_height()):
                for column in range(self.get_width()):
                    result += str(self.data[row][column][deep]) + " "
                result += "\n"
            result += f"Grid {deep+1}\n\n"
        return result

    def randomitems(self, min:int, max: int):
            "Sets random items to the 3 dimensional array"
        for deep in range(self.get_depth()):
            for row in range(self.get_height()):
                for column in range(self.get_width()):
                    self.data[row][column][deep]= random.randint(min, max)

Debo admitirlo, me ayud贸 Github Copilot. Y es que a m铆 siempre se me ha hecho muy dif铆cil visualizar (soy una persona EXTREMADAMENTE visual) objetos 3D en pantallas (que son 2D).


pues asi hice el reto

class Matrix:
    def __init__(self,tam_x, tam_y, tam_z, valor = None):
        self.lista = []
        self.RE_dimencionar(tam_x, tam_y, tam_z,valor,False)



    def RE_dimencionar(self, tam_x, tam_y, tam_z, valor = None, MANTENER_VALOR = True):
        nueva_lista = []
        val = valor
        for x in range(tam_x):
            lista_temp_x = []
            nueva_lista.append(lista_temp_x)
            for y in range(tam_y):
                lista_temp_y = []
                lista_temp_x.append(lista_temp_y)
                for z in range(tam_z):
                    if MANTENER_VALOR:
                        val = self.dameValor(x,y,z,ADVERTENCIA = False)
                        if valor != None and val == None:
                            val = valor
                    lista_temp_y.append(val)
        self.lista = nueva_lista
    


    def cambiaValor(self, index = 0, sub_index = 0, hiper_sub_index = 0, valor = None):
        if self.dameValor(index,sub_index,hiper_sub_index) == None:
                return
        self.lista[index][sub_index][hiper_sub_index] = valor



    def dameValor(self, i_x = 0, i_y = None, i_z = None, ADVERTENCIA = True):
        if type(i_x) == int and i_y == None and i_z == None:
            try:
                return self.lista[i_x]
            except IndexError:
                pass
        elif  type(i_x) == int and type(i_y) == int and i_z == None:
            try:
                return self.lista[i_x][i_y]
            except IndexError:
                pass
        elif  type(i_x) == int and type(i_y) == int and type(i_z) == int:
            try:
                return self.lista[i_x][i_y][i_z]
            except IndexError:
                pass

        if ADVERTENCIA:
            print("ERROR al pasar el indice")
        return None



    def imprime(self):
        for x in self.lista:
            print("->",end="")
            for y in x:
                print("|" ,end= " ")
                for z in y:
                    print(f"{z}",end=" ")
                print("|",end= "")
            print("<-",)

    def __iter__(self):
        return iter(self.lista)



if __name__ == "__main__":
    print("\n normal\n")
    matris = Matrix(3,2,3,"hi")
    matris.imprime()
    print("\n Redimencionada\n")
    matris.RE_dimencionar(4,3,3,"XD")
    matris.imprime()
from arrayClass import Array
from gridClass import Grid

class Cube:
  def __init__(self, row,col,deep):
    self.data = Array(row)
    for d in range(deep):
      self.data[d] = Grid(col,deep)

  def get_height(self):
    return len(self.data )

  def get_width(self):
    return len(self.data[0])

  def get_deep(self):
    return len(self.data[0][0])

  def __getitem__(self,index):
    return self.data[index]

Hola, teniendo en cuenta el concepto de herencia, quer铆a compartir la forma en que yo crear铆a un array de m煤ltiples dimensiones, empleando la clase Array que se cre贸 en la clase anterior:

<class nD_array(Array):

  def __init__(self, dim, capacity, fill=None):
    super().__init__(dim, fill_value=Array(capacity, fill_value=fill))> 

El 煤nico inconveniente que encontr茅 es que al momento de hacer un print cuando se crea una instancia de nD_array es que no salen los arrays como tal, sino que indica es a que clase pertenece cada item as铆:

<two_dim_array = nD_array(2, 5)

print(twi_dim_array)> 

El output es:

[<main.Array object at 0x7fd9583b4bd0>, <main.Array object at 0x7fd9583b4bd0>]

BTW: lo hice antes de ver la clase, XD jajaj

Mi soluci贸n a los retos:

grid

from .array import Array

class Grid(object):
    """Two dimensional Array """

    def __init__(self, nrows, ncols, value=None) -> None:
        """Initializes the Arrays with nrows, ncols and optional value"""
        self.data = Array(nrows)
        for nrow in range(nrows):
            self.data[nrow] = Array(ncols, value)

    def __getheight__(self) -> int:
        """Returns the Arrays's height"""
        rows = self.data
        res: int = 0
        for i in rows:
            res += 1
        return res

    def __getwidth__(self) -> int:
        """Returns the Arrays's width"""
        cols = self.data[0]
        res: int = 0 #  Probando nuevos features de python 3.9
        for i in cols:
            res += 1
        return res

    def __getrow__(self, index) -> any:
        """Returns the index-th row"""
        try:
            if index == 0:
                raise IndexError('Index out of range')
            return self.data[index - 1]
        except IndexError as e:
            print(e)

    def __getelement__(self, index_x, index_y) -> any:
        """Returns the value of the index (x,y)"""
        try:
            if index_x == 0 or index_y == 0:
                raise IndexError('Index out of range')
            return self.data[index_x][index_y]
        except IndexError as e:
            print(e)

    def __str__(self) -> str:
        """Returns string representation of the grid"""
        rows = self.data
        res = ""
        for nrow in range(self.__getheight__()):
            for ncol in range(self.__getwidth__()):
                res += str(rows[nrow][ncol]) + " "
            res += "\n"
        return res

    def __fillvalues__(self) -> None:
        """Fills the array with random values"""
        for nrow in range(self.__getheight__()):
            for ncol in range(self.__getwidth__()):
                self.data[nrow][ncol] = nrow * ncol

cube


from .array import Array
from .grid import Grid

class Cube(object):
    """three-dimensional array"""

    def __init__(self, nrows, ncols, deep, value=None) -> None:
        """Initializes the Cube with nrows, ncols, deep and optional value"""
        self.data = Array(deep)
        for i in range(deep):
            self.data[i] = Grid(nrows, ncols, value)

    def __getdeep__(self) -> int:
        """Return the whole cube"""
        return len(self.data)

    def __str__(self) -> str:
        """Return the cube as a string"""
        result = ""
        for array in range(self.__getdeep__()):
            result += self.data[array].__str__()
            result += "\n"
        return str(result)


En mi caso utilic茅 las demas clases que creamos para hacer m谩s corto el script:
Clase cube:

from grid import Grid
from arrays import Array

class Cube():

    def __init__(self, rows, columns, arrays, fill_value=None):
        self.data = Array(arrays)
        for i in range(arrays):
            self.data[i] = Grid(rows, columns)
        
    def get_arrays(self):
        return len(self.data)
    
    def get_columns(self):
        return self.data[0].get_columns()

    def get_rows(self):
        return self.data[0].get_rows()

    def __str__(self):
        result = ""
        for array in range(self.get_arrays()):
            result += self.data[array].__str__()
            result += "\n"
        return str(result)

    def fill_random_arrays(self, lower_value, upper_value):
        for i in range(self.get_arrays()):
            self.data[i].fill_random(lower_value, upper_value)

clase grid:

from arrays import Array

class Grid():

    def __init__(self, rows, columns, fill_value=None):
        self.data = Array(rows)
        for row in range(rows):
            self.data[row] = Array(columns)

    def get_rows(self):
        return len(self.data)
    
    def get_columns(self):
        return len(self.data[0])

    def get_element(self, row, column):
        return self.data[row][column]

    def __str__(self):
        result = ""
        for row in range(self.get_rows()):
            result += self.data[row].__str__()
            result += "\n"
        return str(result)

    def fill_random(self, lower_value, upper_value):
        for i in range(self.get_rows()):
            self.data[i].__fill_randomvalues__(lower_value, upper_value)

clase array:

import random 
from functools import reduce

class Array():
    def __init__(self, capacity, fill_value = None):
        self.items = list()
        for i in range(capacity):
            self.items.append(fill_value)

    def __len__(self):
        return len(self.items)

    def __str__(self):
        result = ""
        for i in range(self.__len__()):
            result += str(self.items[i]) + " "
        return result

    def __iter__(self):
        return iter(self.items)

    def __getitem__(self, index):
        return self.items[index]

    def __setitem__(self, index, value):
        self.items[index] = value
    
    def __fill_randomvalues__(self, lower_value, upper_value):
        self.items = [random.randint(lower_value, upper_value) for i in range(self.__len__())]
    
    def __fill_secuencialnumbers__(self, start_number, incrase):
        self.items = [start_number + incrase * i for i in range(self.__len__())]

    def __sumelements__(self):
        return reduce(lambda start, finish: start+finish, self.items)

Reto

Les comparto mi soluci贸n del reto.

Representaci贸n

C贸digo

"""Case 8 - Matrices

Crear representaci贸n de una matriz de 3 dimenciones
"""


class DimensionMixin:
    _size = 0
    _items = None
    
    def __len__(self):
        return self._size

    def __str__(self):
        return str(self._items)
    
    def __iter__(self):
        return iter(self._items)

    def __getitem__(self, index):
        return self._items[index]

    def __setitem__(self, index, value):
        self._items[index] = value

    def __repr__(self):
        return str(self)


class Array(DimensionMixin):
    """Representasi贸n de un array."""
    def __init__(self, size : int, fill=None):
        self._items = list()
        self._size = size

        for i in range(size):
            self._items.append(fill)


class Grid(DimensionMixin):
    """Representaci贸n de una matr铆z de 2 dimensiones"""

    def __init__(self, cols: int, rows: int, fill=None) -> None:
        self._items = Array(rows, fill)
        self._cols = cols
        self._rows = rows
        self._size = rows

        for i in range(rows):
            self._items[i] = Array(cols, fill)

    @property
    def count_colums(self):
        """Matrix width"""
        return self._cols
    
    @property
    def count_rows(self):
        """Matrix height"""
        return self._rows

    def get_item_by_coords(self, row_index: int, col_index: int):
        return self._items[row_index][col_index]

    def __repr__(self):
        output = '';

        for r_idx in range(self._rows):
            output += '\n' + repr(self._items[r_idx])
        return output


class Cube(DimensionMixin):
    """Representaci贸n de matr铆z de 3 dimensiones."""

    def __init__(self, depth: int, rows: int, cols: int, fill=None) -> None:
        self._size = depth
        self._depth = depth
        self._cols = cols
        self._rows = rows

        self._items = Array(depth)

        for z in range(depth):
            self._items[z] = Grid(cols, rows, fill)

   @property
   def depth(self):
        return self._depth
    
    @property
    def cols(self):
        return self._cols
    
    @property
    def rows(self):
        return self._rows

    def get_item_by_coords(self, x: int, y: int, z: int):
        return self._items[z][y][z]

    def __repr__(self):
        output = '';
        for idx in range(self._size):
            output += '\n' + str(self._items[idx])
        return output

import random
from prueba import Array

class Cube:
    def __init__(self, rows, depth, columns, fill_value=None):
        self.data = Array(rows)
        for row in range(rows):
            self.data[row] = Array(columns)
            for col in range(columns):
                self.data[row][col] = Array(depth, fill_value=None)


    def get_height(self):
        return len(self.data)


    def get_width(self):
        return len(self.data[0])
    
    def get_depth(self):
        return len(self.data[0][0])

    def __getitem__(self, index):
        return self.data[index]

    def __rempitem__(self, name_array):
        for row in range(name_array.get_height()):
            for column in range(name_array.get_width()):
                for depth in range(name_array.get_depth()):
                    matrix[row][column][depth] = str(random.randint(0, 9)) + " "

    def __str__(self):
        result = ''

        for row in range(self.get_height()):
            for col in range(self.get_width()):
                result += str(self.data[row][col]) + " "
            
            result += '\n'

        return str(result)

if __name__ == '__main__':
    matrix = Cube(3, 3, 3)
    matrix.__rempitem__(matrix)

    print(matrix)

Aqu铆 mi soluci贸n al Reto 2 utilizando la definici贸n de cubo y reutilizando la clase Grid!

class Cube:

    def __init__(self, edge_length):
        self.data = []
        for _ in range(edge_length):
            self.data.append(Grid(edge_length, edge_length)

    def __getitem__(self, index):
        return self.data[index]

    def __str__(self):
        result = ""
        for grid in self.data:
            result += str(grid) + "\n"
        return result

Aqu铆 mi c贸digo. No es posible imprimir un objeto tridimensional en la terminal (2d), pero si es posible representarlo en manera de grupos, osea, en arrays de arrays (que es como lo interpreta numpy por ejemplo)

Channels es como defin铆 la tercera dimensi贸n, que es com煤n llamarla as铆 cuando se trabaja con im谩genes, que es donde es m谩s com煤n encontrar arrays de mas de dos dimensiones. La manera en la que implemente el el m茅todo __str__ es parecida a la de numpy, para presentar de una manera visible el array de tres dimensiones

from array import Array

class Cubo():

    def __init__(self, channels, rows, columns, fill_value=None):
        self.cubic = Array(channels, fill_value)
        for channel in range(channels):
            self.cubic[channel] = Array(rows, fill_value)
            for row in range(rows):
                self.cubic[channel][row] = Array(columns, fill_value)

    def get_channel(self):
        return len(self.cubic)

    def get_height(self):
        return len(self.cubic[0])

    def get_width(self):
        return len(self.cubic[0][0])

    def __str__(self):

        print("[", end="")
        for channel in range(self.get_channel()):
            print("[", end="")
            for row in range(self.get_height()):
                print("[", end="")
                for column in range(self.get_width()):
                    print(f" {self.cubic[channel][row][column]} ", end="")
                print("] \n  ", end="")
            print("] \n", end="")
        print("]", end="")

        return ""


Soluci贸n reto 2:

class Grid(object):
    def __init__(self, rows, columns, fill_value=None):
        self.data = Array(rows)
        self.rows = rows
        self.columns = columns

        for row in range(rows):
            self.data[row] = Array(columns, fill_value)

    # reto 2
    def __random_fill__(self):

        for row in range(self.rows):
            for column in range(self.columns):
                self.data[row][column] = row * column

para imprimir los valores en consola, basta con usar el metodo str que definimos en clase:

if __name__ == '__main__': 
    matrix = Grid(3, 3)
    print(matrix.__random_fill__())
    print(matrix.__str__())

Reto parte 2:
No se si lo hice bien, porque no se como imprimierlo para que se vean en 3 dimensiones jajaja pero bueno les dejo lo que saque

from array_py import Array
from grid import Grid


class Tensor:
	def __init__(self, rows, columns, deep, fill_value=None):
		self.tensor = Grid(rows, columns, fill_value)

		for i in range(rows):
			for j in range(columns):
				self.tensor[i][j] = Array(deep, fill_value)

	def get_height(self):
		return self.tensor.get_height()

	def get_width(self):
		return self.tensor.get_width()

	def get_deep(self):
		return len(self.tensor[0][0])

	def __getitem__(self, idx):
		return self.tensor[idx]

	def __str__(self):
		result = ""
		for row in range(self.get_height()):
			for col in range(self.get_width()):
				for deep in range(self.get_deep()):
					result += str(self.tensor[row][col][deep]) + " "
				result += '\n'

		return str(result)

	def fill(self):
		for i in range(self.get_height()):
			for j in range(self.get_width()):
				self.tensor[i][j].fill()

Este es el c贸digo del reto2 del Grid:

from custom_array import Array


class Grid:
    def __init__(self, rows, columns, fill_value=None):
        self.data = Array(rows)
        for row in range(rows):
            self.data[row] = Array(columns, fill_value)

    def get_height(self):
        return len(self.data)

    def get_width(self):
        return len(self.data[0])

    def __getitem__(self, index):
        return self.data[index]

    def __str__(self):
        result = ""

        for row in range(self.get_height()):
            for col in range(self.get_width()):
                result += str(self.data[row][col]) + " "

            result += "\n"

        return str(result)

    def __random_fill__(self):
        import random

        for row in range(self.get_height()):
            for col in range(self.get_width()):
                self.data[row][col] = random.randint(1,10)

    if __name__ == '__main__':
        from grid import Grid
        matrix = Grid(4,5)
        matrix.__random_fill__()
        print(matrix.__str__())

Y este otro es el c贸digo del reto 3 del Cube

from grid import Grid
from custom_array import Array


class Cube:
    def __init__(self, axes, rows, columns, fill_value=None):
        self.area = Array(axes)
        for axe in range(axes):
            self.area[axe] = Grid(rows, columns, fill_value)

    def get_depth(self):
        return len(self.area)

    def get_height(self):
        return self.area[0].get_height()

    def get_width(self):
        return self.area[0].get_width()

    def __getitem__(self, index):
        return self.area[index]

    def __str__(self):
        result = ""
        for axe in range(self.get_depth()):
            result += f"Matrix {axe} \n"
            for row in range(self.get_height()):
                for col in range(self.get_width()):
                    result += str(self.area[axe][row][col]) + " "

                result += "\n"
            result += "\n"

        return str(result)

    def __random_fill__(self):
        import random

        for axe in range(self.get_depth()):
            for row in range(self.get_height()):
                for col in range(self.get_width()):
                    self.area[axe][row][col] = random.randint(1,100)

    if __name__ == '__main__':

        from cube import Cube
        cubex = Cube(2, 3, 4)
        print(f"La profundidad es: {cubex.get_depth()} el alto es {cubex.get_height()} y el largo es {cubex.get_width()}")
        cubex.__random_fill__()
        print(cubex.__str__())
        

Nuevos m茅todos para mi grid

from customArray import Array
import random

class Grid:
    def __init__(self, rows: int, columns: int, fill_value: int = None):
        self.data = Array(rows)
        
        for row in range(rows):               
            self.data[row] = Array(columns, fill_value) #Doing so it implements the dunder method __setitem__() of the class Array
    
    def get_height(self):
        return len(self.data) #Doing so it implements the dunder method __len__() of the class Array  
        #self.data.__len__.()            
        
    def get_width(self):
        return len(self.data[0]) #Doing so it implements the dunder method __len__() of the class Array            

    def __getitem__(self, index: int):
        return self.data.__getitem__(index)
        #return self.data[index] #Doing so it implements the dunder method __getitem__() of the class Array
    
    def __str__(self):
        result = ""
        
        for row in range(self.get_height()):
            for column in range(self.get_width()):
                result += str(self.data[row][column]) + " "
            result += "\n"
        return str(result)

    def randomitems(self, min: int , max: int):        
        for row in range(self.get_height()):
            for column in range (self.get_width()):
                self.data[row][column]=random.randint(min, max)
    
    def sumitems(self):
        sum = 0
        for row in range(self.get_height()):
            for column in range(self.get_width()):
                sum += sum + self.data[row][column]
        return sum
    
    def max_item(self):
        max = 0
        for row in range(self.get_height()):
            for column in range(self.get_width()):
                if self.data[row][column]>max:
                    max = self.data[row][column]
        return max
    
    def min_item(self):
        min = 0
        for row in range(self.get_height()):
            for column in range(self.get_width()):
                if self.data[row][column]<min:
                    min = self.data[row][column]
        return min

Reto parte 1 y 2

Clase Grid con poblado de datos

from array_py import Array


class Grid:
	def __init__(self, rows, columns, fill_value=None):
		self.data = Array(rows)

		for i in range(rows):
			self.data[i] = Array(columns, fill_value)

	def get_height(self):
		return len(self.data)

	def get_width(self):
		return len(self.data[0])

	def __getitem__(self, idx):
		return self.data[idx]

	def __str__(self):
		result = ""
		for row in range(self.get_height()):
			for col in range(self.get_width()):
				result += str(self.data[row][col]) + " "
			result += '\n'

		return str(result)

	def fill(self):
		for i in range(self.get_height()):
			self.data[i].fill()

Resultaos: