Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random list only with -1 and 1

I need to create random list which consists only of -1 and 1 like -1,1,1,-1,-1 (without zeros). My current coding adds 0 that doesn't suite me.

import random
for x in range(10):
    print (random.randint(-1,1))
like image 753
leonardik Avatar asked Jul 23 '19 08:07

leonardik


2 Answers

You can use random.choices, which randomly selects k elements from a given sequence, avoiding this way the need for any looping:

random.choices([-1,1], k=10)
#[-1, -1, 1, 1, 1, -1, -1, 1, -1, -1]
like image 184
yatu Avatar answered Nov 17 '22 00:11

yatu


You could use random.choice():

>>> [random.choice([-1, 1]) for _ in range(10)]
[1, -1, 1, 1, -1, 1, -1, -1, -1, -1]
like image 26
NPE Avatar answered Nov 17 '22 01:11

NPE