0

I have a numeric vector of length x, all values in the vector are currently 0. I want it to randomly assign y of these values to equal 1, and x-y of these values to equal 0. Any fast way to do this? My best guess right now is to have a RNG assign each value to 0 or 1, sum up the string and, if the sum does not equal y, start all over again.

Can I use random.choice(vector,y) and then assign the elements that were picked to equal 1?

1 Answer 1

2

There's a function called random.sample() which, given a sequence of items, will give you back a certain number of them randomly selected.

import random
for index in random.sample(xrange(len(vector)), y): # len(vector) is "x"
    vector[index] = 1

Another way to do this would be to combine a list of x 0's and y 1's and shuffle it:

import random
vector = [0]*(x-y) + [1]*y  # We can do this because numbers are immutable
vector.shuffle()
Sign up to request clarification or add additional context in comments.

5 Comments

I was just going to post the second answer. Spent some time testing which was faster, and it turns out the shuffle wins by about 30% for vector of len 10 to 1000. Didn't test beyond that.
@sberry It probably depends on the ratio of x to y.
y/x is about 1.2. Thanks!
@Amber: certainly it does. I was using a ratio of 1:1.
@sberry Yeah, for 1:1 shuffle likely wins simply due to not having to create an extra list (for returning from random.sample()) and instead being able to shuffle in-place. For smaller ratios random.sample() might very well win due to not having to shuffle a large base list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.