Declaring multi-dimensional array using CFG

I am still juveline to compilers and formal languages. I’ve tried to write context-free grammar (CFG) for a multi-dimensional array, but I am not sure of my solution, so could you suggest your CFG for multi-dimensional array?

<type>:: = int | float | string <array>:: = <type> [<identifier>] | <array> | [<identifier>]  <identifier>::= <letter> | <identifier><letter>|<identifier><digit> <letter>::= a|...|z <digit>::= 0|...|9 

Is this implementation is a true one for multi-dimensional array?

My second question is regarding function invocation as well? I have written the following declaration for function:

<funDeclaration>::= <type> <identifier>(<params>) <statement> | <identifier> (<params> )<statement> 

Without demonstrating , just for clarity and to keep the question short, how to write function invocation?

Convertir json en json multidimensional

Tengo un JSON con la siguiente estructura:

[     {"Model":"6"},     {"Title":"tituloM6","Value":"saddsaf"},     {"Title":"msgOperadorM6","Value":"sdafdsfa"},     {"Title":"msgErrorM6","Value":"sadsdafdf"},     {"Title":"ok","Value":""},     {"Title":"imgM6","Value":""},     {"Model":"6"},     {"Title":"tituloM6","Value":"asdsf"},     {"Title":"msgOperadorM6","Value":"asdsddf"},     {"Title":"msgErrorM6","Value":"dsafsfdsfda"},     {"Title":"ok","Value":""},     {"Title":"imgM6","Value":""} ] 

Pero no logro transformarlo en uno multidimensional con la siguiente estructura:

[     {"Model":"6"},     {"datos":          [             {"Title":"tituloM6","Value":"saddsaf"},             {"Title":"msgOperadorM6","Value":"sdafdsfa"},             {"Title":"msgErrorM6","Value":"sadsdafdf"},             {"Title":"ok","Value":""},             {"Title":"imgM6","Value":""}         ]            }      {"Model":"6"},     {"datos":          [             {"Title":"tituloM6","Value":"asdsf"},             {"Title":"msgOperadorM6","Value":"asdsddf"},             {"Title":"msgErrorM6","Value":"dsafsfdsfda"},             {"Title":"ok","Value":""},             {"Title":"imgM6","Value":""}         ]     }    ] 

El json lo obtengo de un List<string> y lo convierto con:

var json = JsonConvert.SerializeObject(lista); 

He tratado de realizarlo con un foreach que recorriese los elementos de la lista y con dos List<>, una para Model y otra para los otros campos y despues unirlas de la siguiente manera:

List<string> modelos = new List<string>(); List<string> valores = new List<string>(); bool primero = false;      foreach (var resultado in result) {     if (resultado.Model != null)     {         modelos.Add("Modelo");         modelos.Add(resultado.Model);         if (primero != false)         {             modelos.AddRange(valores);             valores = new List<string>();         }                }     else     {         valores.Add(resultado.Title);         valores.Add(resultado.Value);     }     primero = true; } 

¿Cómo puedo generarlo?

Does the order of multidimensional array’s length affect the time complexity of accessing elements?

I was using a 3d array in java of lengths 3001,3001,4 in a dp problem but I couldn’t get my submission accepted as i kept on exceeding the time limit(1 second), i checked the code of a friend and found out that the only difference was that the order of the lengths of the memo was 4,3001,3001 as soon as i changed my memo order to the previous order my code ran in 400ms so i would like to know what is the difference between both cases

Padding multi-dimensional array to its max shape

For some machine learning purpose, I need to work with sequences with different lengths. To be able to process efficiently those sequences, I need to process them in batches of size size_batch. A batch typically has 4 dimensions and I want to convert it to a numpy’s ndarray with 4 dimensions. For each sequence, I need to pad with some defined pad_value such that each element has the same size: the maximal size.

For example with 3 dimensional input:

[[[0, 1, 2],   [3],   [4, 5]],  [[6]],  [[7, 8],   [9]]] 

desired output for pad_value -1 is:

[[[0, 1, 2],   [3, -1, -1],   [4, 5, -1]],  [[6, -1, -1],   [-1, -1, -1],   [-1, -1, -1]]  [[7, 8, -1],   [9, -1, -1],   [-1, -1, -1]]] 

which has shape (3, 3, 3). For this problem, one can suppose there are no empty list in the input. Here is the solution I came up with:

import numpy as np import itertools as it from typing import List  def pad(array: List, pad_value: np.int32, dtype: type = np.int32) -> np.ndarray:     """ Pads a nested list to the max shape and fill empty values with pad_value      :param array: high dimensional list to be padded     :param pad_value: value appended to     :param dtype: type of the output     :return: padded copy of param array     """     # Get max shape     def get_max_shape(arr, ax=0, dims=[]):         try:             if ax >= len(dims):                 dims.append(len(arr))             else:                 dims[ax] = max(dims[ax], len(arr))              for i in arr:                 get_max_shape(i, ax+1, dims)         except TypeError:  # On non iterable / lengthless objects (leaves)             pass          return dims      dims = get_max_shape(array)      # Pad values     def get_item(arr, idx):         while True:             i, *idx = idx             arr = arr[i]             if not idx:                 break         return arr      r = np.zeros(dims, dtype=dtype) + pad_value     for idx in it.product(*map(range, dims)):         # idx run though all possible tuple of indices that might          # contain a value in array         try:             r[idx] = get_item(array, idx)         except IndexError:             continue      return r 

It does not feel really pythonic but does the job. Is there any better way to do it I should know ? I think I might be able to improve its speed by doing smart breaks in the last loop but I haven’t dug much yet.

Thanks !

Array multidimensional como retirar um carácter de um determinado index?

O código abaixo é resultado da leitura de um arquivo CSV, que o transformo em Array para trata-lo para criar um novo CSV pra poder ser importado com um novo formato. Quero retirar os – que estão nos números de telefone / celular.

Sabemos que nos telefones / celulares existem sempre 4 dígitos antes do -, mas não sei como faze-lo para retirar.

Exemplo:

array   0 =>      array (size=4)       0 => string 'Nome/Razão Social'       1 => string 'Nome Fantasia'       2 => string 'Tel.'       3 => string 'Cel.'   1 =>      array (size=4)       0 => string 'XXX XXXXX XXXXXXXX'       1 => string ''       2 => string '9123-4321'       3 => string '7123-4312' 

Obrigado desde já pela ajuda.

Como cambiar el valor de un elemento dentro de un arreglo multidimensional en javascript

Buen día

Me surgió algo extraño trabajando con arreglos en javascript, probablemente este omitiendo algo investigue al respecto pero no encontré algo que me ayudara

var arreglo = [['0'],['1'],['2'],['3']]; 

Luego por realizo un push para copiar el ultimo elemento en cuestion

arreglo.push(arreglo[arreglo.length -1]); 

y la estructura del arreglo quedaria de la siguiente forma

arreglo = [['0'],['1'],['2'],['3'],['3']]; 

al querer cambiar el ultimo elemento del arreglo despues del push

arreglo[arreglo.length -1][0] = 'finDeArray'; 

no se por que cambia tambien el elemento del indice [3][0] y termina asi

arreglo = [['0'],['1'],['2'],['finDeArray'],['finDeArray']]; 

cuando busco que termine asi

arreglo = [['0'],['1'],['2'],['3'],['finDeArray']]; 

cualquier tipo de ayuda es agradecida

Saludos

multidimensional change of variables

If $ \mathbf{X}=(X_1,…,X_n)$ s.t $ X_i$ ‘s are iid r.vs with $ X_i\sim Ga(\alpha_i,\beta_i)$ . Let $ S=\sum_{j=1}^\infty X_j$ and $ R_i={X_i\over S}$ s.t $ \mathbf{R}=(R_1,…,R_n)$ . I have read that the density of $ f_{\mathbf{R},S}(r_1,…,r_n,s)$ is $ $ f_{\mathbf{R},S}(r_1,…,r_n,s)=f_{\mathbf{X}}(r_1s,…,r_ns)s^{n-1}.$ $ How did we make the variable change from $ n$ to $ n+1$ variables and should $ |J|=s^{n}$ ?

I want to build multidimensional array at Twig

I want to build multidimensional array at Twig.

In php

 $  attributes['attributes']['class'] = array();  $  attributes['attributes']['class'][] = 'innerTab';  $  attributes['html'] = TRUE;

Same thing I want to build in Twig. I tried but not getting proper one . Please check my code below

 {% set ctn = 0 %}          {% for key, value in menu.menu %} {% set attributes = {'attributes':'class'} %} {% set attributes = attributes|merge( [ { (ctn) :'innerTab'} ,  {'html' : true} ]  ) %}  {% set ctn = ctn+1  %}  {% endfor %}

As a result I get :

array(3) { [“attributes”]=> string(5) “class” [0]=> array(1) { [0]=> string(8) “innerTab” } [1]=> array(1) { [“html”]=> bool(true) } } array(3) { [“attributes”]=> string(5) “class” [0]=> array(1) { [1]=> string(8) “innerTab” } [1]=> array(1) { [“html”]=> bool(true) } } array(3) { [“attributes”]=> string(5) “class” [0]=> array(1) { [2]=> string(8) “innerTab” } [1]=> array(1) { [“html”]=> bool(true) } }