0

Instead of the typical binary 0 or 1, or two consecutive numbers, I need to create a loop which will generate three random -1s and 1s, 100 times. My code so far looks like:

new = []
i =1 
while i <= 100:
    random = np.random.randint(low=-1, high=1, size=(1,3))
    new.append(random)
    i += 1
print(new.append(random))

Though this just returns None and even if it was working, would return 0s as well which is not wanted.

1
  • Did you try to print(new)? Here you're just printing the function return value of another .append() call, which will be None Commented Oct 14, 2021 at 5:00

1 Answer 1

4

No need to bother importing numpy - it may be easier to just use random.choices() (from the standard library) to generate three random choices from [-1, 1], and do it 100 times.

import random

new = [random.choices([-1, 1], k=3) for _ in range(100)]
# [[1, 1, -1], 
#  [1, 1, 1], 
#  [1, 1, -1], 
#  [-1, -1, -1], 
#  ...
#  [1, -1, 1]]

If you're doing this inside a function, with the intent for that function to produce new for outside use, then don't forget to do return new at the end of the function.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.