Create vector automatically in Python

3

I'm new to Python and need help with the following:

  • I have a variable (x) that gets an integer value.
  • I want this variable to be used to create a vector with 1 row and (x) columns.
  • This vector must have random integer values from 0 to 100.

Example:

For x = 4

My output should be:

  

[50,40,60,70]

    
asked by anonymous 23.04.2017 / 20:34

2 answers

3

You can use random module to generate the random values:

If you do not want repeated values:

import random

x = 5
saida = []
for _ in range(x):
    saida.append(random.choice(range(100)))
print saida # [5, 75, 9, 38, 33]

Or even better:

import random

x = 5
saida = random.sample(range(100),  x)
print(saida) # [69, 47, 43, 64, 16]

If there can be repeated values:

import random

x = 5
saida = []
for _ in range(x):
    saida.append(random.randint(0, 100))
print saida # [74, 12, 15, 32, 74]

Note that you can use a list understanding for any of the above solutions:

import random

x = 5
saida = [random.randint(0, 100) for _ in range(x)]
print saida # [88, 37, 17, 27, 58]

DEMONSTRATION of the three examples above

    
23.04.2017 / 20:51
3

It's simple. It would be nice to take a look at the module random , there are several ways to work with random numbers.

randint returns an integer between the two that were passed by parameter.

from random import randint

x = int(raw_input('entre com o valor desejado: '))
vec = []

for i in range (x):
    vec.append(randint(0, 100))

print(vec)

See working on repl.it.

    
23.04.2017 / 20:48