villares / material-aulas

Material para ensino introdutório de programação com Python em um contexto visual
https://abav.lugaralgum.com/material-aulas/
97 stars 70 forks source link

Conversão de Arrays em Java para listas em Python #82

Closed ggiavoni closed 3 years ago

ggiavoni commented 3 years ago

_Python

_board = [[0] * gridw for in range(gridh)] Em vez do 0 você pode usar outro valor calculado ou None como 'segurador de lugar' (placeholder) caso a estrutura vá servir para outros tipos de dados.)_

Professor, seria interessante expandir essa seção, pois em Java a questão do Array é muito utilizada nos livros bibliográficos. No momento de converter com seu guia, eu senti falta de mais exemplos sobre a substituição do Array em Java para Lista em Lista no Python. Porque não podemos usar o Array do Python, como nesse exemplo aqui: https://www.geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way/

Obrigado

villares commented 3 years ago

Salve @ggiavoni essa é uma ótima questão!

Note que o exemplo que você mandou do geesksforgeeks.org, apesar dele usar a palavra array e variáveis de nome arr, o artigo só está usando listas no Python!. No fundo estão usando o termo list/array como uma forma intercambiável, e isso é uma prova de que as listas resolvem para nós na maior parte dos casos em que se usaria um Array, em Java, por exemplo.

É possível usar Arrays "de verdade" mas não é muito prático para nós. Muitas pessoas usando Python moderno (Python 3) usam uma biblioteca maravilhosa chamada numpy que tem arrays multidimensionais de alta performance, que não podemos usar (mas em geral também não são necessários nos nossos casos mais comuns).

De qualquer forma, acho muito bom melhorarmos a documentação de como traduzir coisas feitas com Array no Processing Java. Você tem mais alguns casos-exemplo pra me ajudar a expandir essa sessão?

Estruturas de dados

Arrays como int[], float[] ou PVector[] podem virar listas em Python (ou quem sabe tuplas, se forem criadas e deixadas quietas). Um ArrayList é muito parecido com uma lista:

Java

ArrayList<Bandeirinha> Bandeirinhas; // uma lista de objetos da classe Bandeirinha

void setup() {
  size(400, 400); 
  Bandeirinhas = new ArrayList<Bandeirinha>();
  for (int i=0; i <50; i++) {
    Bandeirinhas.add(new Bandeirinha(100, 100, 12));
  }
}

Python

Bandeirinhas = []  # uma lista de objetos Bandeirinha

def setup():
    size(400, 400); 
    for i in range(50):
        Bandeirinhas.append(Bandeirinha(100, 100, 12))

Arrays 2D

Parar traduzir, arrays de duas dimensões em Java, faça uma lista de listas (não, você não pode usar numpy).

Java

int[][] board;
board = new int[grid_w][grid_h]

Python

board = [[0] * grid_w for _ in range(grid_h)]

Em vez do 0 você pode usar outro valor calculado ou None como 'segurador de lugar' (placeholder) caso a estrutura vá servir para outros tipos de dados.

ggiavoni commented 3 years ago

Obrigado! É verdade, utilizam listas! Não me atentei, segue um exemplo do uso do Array em Java :

// Painel para Apresentação em Java. 
int tileSize = 50; // tamanho_grid = 50
int rows = 50; // n_linhas = 50
int cols = 50; // n_colunas = 50

Tile[][] tiles = new Tile[rows][cols]; // grid = [[0] * n_linhas for in _ range(n_colunas)]
color ic = color(100, 125, 0);    // orange // ic = color(100, 125, 0)
color oc = color(20, 150, 255);  // blue // oc = color(20, 150, 255)

void setup() { 
  size(1000, 1000);
  smooth();

  for (int i=0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      tiles[i][j] = new Tile(j*tileSize, i*tileSize, tileSize, ic, oc);
      colorSwap(i, j);
      tiles[i][j].display();
    }
  }
} // end setup()

class Tile {
  int sz;         // size of tile
  int x, y;       // x, y coords of top left corner of tile
  float orient;     // orientation of tile
  int intorient;
  boolean swapColors;  // whether we should swap inside and outside colors
  color ic;            // inside color – fill color of arc if swapColor is false
  color oc;            // outside color – fill color of background square if swapColor is false

  Tile(int x, int y, int w, color ic, color oc) {
    this.x = x;
    this.y = y;
    sz = w;
    this.ic = ic;
    this.oc = oc;
    orient = random(1, 3); 
    intorient = (int) orient;
  } // end Tile()

  void display() {
    pushMatrix();
    translate(x, y);             // move to tile's x-y location (upper left corner)
    noStroke();
    if (swapColors) {
      fill(ic);
    } else {
      fill(oc);
    }
    rect(0, 0, sz, sz);          // draw background square

    translate(sz/2, sz/2);       // move to the center of the tile
    rotate(intorient * PI/2);         // rotate by the appropriate angle
    translate(-sz/2, -sz/2);     // move back to the upper left corner
    stroke(255);
    strokeWeight(3);
    if (swapColors) {
      fill(oc);
    } else {
      fill(ic);
    }
    arc(0, 0, sz, sz, 0, PI/2);
    arc(sz, sz, sz, sz, PI, 3*PI/2);
    popMatrix();
  } // end display()
} // end class Tile

// takes the row and column indices of the current tile and 
// decides how to set its swapColor boolean variable
void colorSwap(int i, int j) {
  if (i > 0 && j == 0) {                        // first tile of a row, starting from the 2nd row
    // same orientation as tile directly above
    if (tiles[i-1][0].intorient == tiles[i][0].intorient) {          
      // set to opposite coloring of my neighbor above
      tiles[i][0].swapColors = !tiles[i-1][0].swapColors;
    } else {
      // set to same coloring of my neighbor above
      tiles[i][0].swapColors = tiles[i-1][0].swapColors;
    }
  }
  if (j > 0) {                           // subsequent tiles in a row, including the first
    // same orientation as tile to the left
    if (tiles[i][j-1].intorient == tiles[i][j].intorient) {
      // set to opposite coloring of my neighbor to the left
      tiles[i][j].swapColors = !tiles[i][j-1].swapColors;
    } else {
      // set to same coloring of my neighbor to the left 
      tiles[i][j].swapColors = tiles[i][j-1].swapColors;
    }
  }
} // end colorSwap()

detalhe do resultado:

image

villares commented 3 years ago

Opa @ggiavoni ! Não vamos fechar essa issue por enquanto não! Vai dar uma ótima contribuição.

Faz o seguinte, tenta um pouco traduzir esse exemplo que você mandou que eu te ajudo :)

ggiavoni commented 3 years ago

Desculpe! hahaha sou novo no GitHub! Ok! Vou tentar traduzir e coloco aqui, esse foi o primeiro painel que desejei fazer para a aula e travei bastante.

villares commented 3 years ago

Massa! Vou traduzir a classe para você poder se concentrar na questão dos arrays :)

image

class Tile:

    def __init__(self, x, y, w, ic, oc):
        self.x, self.y = x, y  # x, y coords of top left corner of tile
        self.sz = w  # size of tile
        self.ic = ic  # inside – fill of arc if swapColor is False
        # outside – fill of background square if swapColor is False
        self.oc = oc
        self.orient = random(1, 3)  # orientation of tile
        self.intorient = int(self.orient)  # orientation of tile
        # whether we should swap inside and outside colors
        self.swapColors = False

    def display(self):
        pushMatrix()
        # move to tile's x-y location (upper left corner)
        translate(self.x, self.y)
        noStroke()
        if (self.swapColors):
            fill(self.ic)
        else:
            fill(self.oc)

        rect(0, 0, self.sz, self.sz)  # draw background square

        translate(self.sz / 2, self.sz / 2)  # move to the center of the tile
        rotate(self.intorient * PI / 2)  # rotate by the appropriate angle
        # move back to the upper left corner
        translate(-self.sz / 2, -self.sz / 2)
        stroke(255)
        strokeWeight(3)
        if self.swapColors:
            fill(self.oc)
        else:
            fill(self.ic)

        arc(0, 0, self.sz, self.sz, 0, PI / 2)
        arc(self.sz, self.sz, self.sz, self.sz, PI, 3 * PI / 2)
        popMatrix()
villares commented 3 years ago

Opa, fiz aqui a outra função também. Mas não tenho como testar ainda :) precisa terminar a parte principal da grade com a lista de listas dos Tiles.

tileSize = 50  # tamanho_tile = 50
rows = 50  # n_linhas = 50
cols = 50  # n_colunas = 50

# Tile[][] tiles = new Tile[rows][cols];
# grid = [[0] * n_linhas for in _ range(n_colunas)]
# tiles = ... 

ic = color(100, 125, 0)  # orange
oc = color(20, 150, 255)  # blue

def setup():
    size(500, 500)
    smooth()

    # for (int i=0; i < rows; i++) {
    #     for (int j = 0; j < cols; j++) {
    #     tiles[i][j] = new Tile(j*tileSize, i*tileSize, tileSize, ic, oc);
    #     colorSwap(i, j);
    #     tiles[i][j].display();
    #     }
    # }

    # código só para testar a classe
    # new Tile() em Python é só Tile()
    i, j = 1, 1
    tile = Tile(j * tileSize, i * tileSize, tileSize, ic, oc)
    tile.display()

# takes the row and column indices of the current tile and
# decides how to set its swapColor variable
def colorSwap(i, j):
    if i > 0 and j == 0:  # first tile of a row, starting from the 2nd row
        # same orientation as tile directly above
        if tiles[i - 1][0].intorient == tiles[i][0].intorient:
            # set to opposite coloring of my neighbor above
            tiles[i][0].swapColors = !tiles[i - 1][0].swapColors
        else:
            # set to same coloring of my neighbor above
            tiles[i][0].swapColors = tiles[i - 1][0].swapColors

    if j > 0:  # subsequent tiles in a row, including the first
        # same orientation as tile to the left
        if tiles[i][j - 1].intorient == tiles[i][j].intorient:
            # set to opposite coloring of my neighbor to the left
            tiles[i][j].swapColors = !tiles[i][j - 1].swapColors
        else:
            # set to same coloring of my neighbor to the left
            tiles[i][j].swapColors = tiles[i][j - 1].swapColors
villares commented 3 years ago

Salve Paulo @ggiavoni! Você chegou a terminar este exemplo?

Queria fechar esta issue mas também queria de alguma maneira incorporar este material em uma página, você consegue me ajudar?

villares commented 3 years ago

image

# Translated to Processing Python mode from the Java example at
# "Processing: Creative Coding and Generative Art in Processing 2" by Ira Greenberg, Dianna Xu, Deepak Kumar 

tileSize = 50 # tamanho_grid = 50
rows = 50 # n_linhas = 50
cols = 50 # n_colunas = 50

# grid = [[None] * n_linhas for in _ range(n_colunas)]
tiles = [[None] * rows for _ in range(cols)]
ic = color(100, 125, 0)        # orange # ic = color(100, 125, 0)
oc = color(20, 150, 255)    # blue # oc = color(20, 150, 255)

def setup(): 
    size(1000, 1000)
    smooth()
    for i in range(rows):
        for j in range(cols):
            tiles[i][j] = Tile(j*tileSize, i*tileSize, tileSize, ic, oc)
            colorSwap(i, j)
            tiles[i][j].display()

def colorSwap(i,j):
    if i > 0 and j == 0:   # first tile of a row, starting from the 2nd row
        # same orientation as tile directly above
        if (tiles[i-1][0].intorient == tiles[i][0].intorient):                    
            # set to opposite coloring of my neighbor above
            tiles[i][0].swapColors = not tiles[i-1][0].swapColors
        else:
            # set to same coloring of my neighbor above
            tiles[i][0].swapColors = tiles[i-1][0].swapColors

    if j > 0:  # subsequent tiles in a row, including the first
        # same orientation as tile to the left
        if (tiles[i][j-1].intorient == tiles[i][j].intorient):
            # set to opposite coloring of my neighbor to the left

            tiles[i][j].swapColors = not tiles[i][j-1].swapColors
        else:
            # set to same coloring of my neighbor to the left 
            tiles[i][j].swapColors = tiles[i][j-1].swapColors

class Tile:

    def __init__(self, x, y, w, ic, oc):
        self.x, self.y = x, y  # x, y coords of top left corner of tile
        self.sz = w  # size of tile
        self.ic = ic  # inside – fill of arc if swapColor is False
        # outside – fill of background square if swapColor is False
        self.oc = oc
        self.orient = random(1, 3)  # orientation of tile
        self.intorient = int(self.orient)  # orientation of tile
        # whether we should swap inside and outside colors
        self.swapColors = False

    def display(self):
        pushMatrix()
        # move to tile's x-y location (upper left corner)
        translate(self.x, self.y)
        noStroke()
        if (self.swapColors):
            fill(self.ic)
        else:
            fill(self.oc)

        rect(0, 0, self.sz, self.sz)  # draw background square

        translate(self.sz / 2, self.sz / 2)  # move to the center of the tile
        rotate(self.intorient * PI / 2)  # rotate by the appropriate angle
        # move back to the upper left corner
        translate(-self.sz / 2, -self.sz / 2)
        stroke(255)
        strokeWeight(3)
        if self.swapColors:
            fill(self.oc)
        else:
            fill(self.ic)

        arc(0, 0, self.sz, self.sz, 0, PI / 2)
        arc(self.sz, self.sz, self.sz, self.sz, PI, 3 * PI / 2)
        popMatrix()
villares commented 3 years ago

https://github.com/villares/material-aulas/blob/main/Processing-Python/truchet.md