List of lists of random numbers python

1

I want to know how to implement the matrizAleatoria(a) function, which completes the list of a lists with random numbers using random.random() (the function does not return anything, you only have to modify a)

I wrote the following code:

def matrizAleatoria(a):
    A = []
    for i in range(len(A)):
        for j in range(1,len(A)):
            elemento_aleatorio = random.random()
            A.append(elemento_aleatorio)
    return A       # Acá retorno A a modo de verificación

print("MatrizAleatoria:",matrizAleatoria([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]))

Generate in response:

MatrizAleatoria: []

I'm not sure if line A.append(elemento_aleatorio) is adding each random value.

    
asked by jsuarezbaron 23.10.2018 в 22:01
source

1 answer

1

First of all, if your idea is to pass an existing matrix and fill it with values at random, it does not make any sense to use append() , it would have it eventually if you are creating a new matrix. Then you initialize a blank list A = [] that obviously has no dimension so the len(A) will always be 0, that is, we will never enter the cycles.

I suggest something like this:

import random

def matrizAleatoria(A):
    for i in range(len(A)):
        for j in range(len(A[0])):
            A[i][j] = random.uniform(0, 1)
    return A

What we do is to receive a matrix and go through two cycles the (range(len(A)) and columns range(len(A[0])) , by index A[i][j] to each "cell" we give a random value float between 0 and 1 with random.uniform(0, 1)

Demonstration:

import pprint
m = [
      [0.0, 0.0, 0.0], 
      [0.0, 0.0, 0.0], 
      [0.0, 0.0, 0.0]
    ]

pprint.pprint(matrizAleatoria(m))

[[0.16709861608817678, 0.8347266417016206, 0.13958854790714093],
 [0.8034171062425288, 0.41111929257971636, 0.5428587290518186],
 [0.2207627499411946, 0.33454580726581595, 0.8248387671432847]]
    
answered by 23.10.2018 / 22:50
source