-3

In Python how can I choose two or more random numbers from a given list,such that the numbers are chosen in the same sequence they are arranged in the list they are chosen from?It seems random.choice selects only one number from the list per iteration and as stated earlier random.sample does not give satisfactory answers.for example:

import random
a=['1','2','3','4','5','6','7','8']
b=['4','3','9','2','7','1','6','5']
c=random.sample(a,4)
d=random.sample(b,4)
print "c=",c
print "d=",d

The code gives me the following result:

c=['4','2','3','8']
d=['1','9','5','4']

But I want the answer as:

c=['4','5','6','7']
d=['9','2','7','1']

or

c=['5','6','7','8']
d=['7','1','6','5']
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • 4
    Possible duplicate of [How do I pick 2 random items from a Python set?](http://stackoverflow.com/questions/1262955/how-do-i-pick-2-random-items-from-a-python-set) – DaveBensonPhillips Sep 18 '16 at 06:49
  • Am I correct that you're looking for four consecutive values from the input `list`s? So for your example `list` `a`, wanting four values, there are only five possible outputs (1-4, 2-5, 3-6, 4-7 and 5-8)? – ShadowRanger Oct 13 '16 at 18:55

2 Answers2

2

Looks like you want four consecutive values starting at a random offset, not four values from anywhere in the sequence. So don't use sample, just select a random start point (early enough to ensure the slice doesn't run off the end of the list and end up shorter than desired), then slice four elements off starting there:

import random

...

selectcnt = 4
cstart = random.randint(0, len(a) - selectcnt)
c = a[cstart:cstart + selectcnt]
dstart = random.randint(0, len(b) - selectcnt)
d = b[dstart:dstart + selectcnt]

You could factor it out to make it a little nicer (allowing you to one-line individual selections):

import random

def get_random_slice(seq, slicelen):
    '''Get slicelen items from seq beginning at a random offset'''
    start = random.randint(0, len(seq) - slicelen)
    return seq[start:start + slicelen]

c = get_random_slice(a, 4)
d = get_random_slice(b, 4)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

Answer for original version of question:

To get two samples randomly, use random.sample. First, lets define a list:

>>> lst = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Now, lets get two samples randomly:

>>> random.sample(lst, 2)
[13, 16]
>>> random.sample(lst, 2)
[10, 12]

Sampling is done without replacement.

John1024
  • 109,961
  • 14
  • 137
  • 171