Home > Blockchain >  Randomly Crop a Given Input Sequence in Python?
Randomly Crop a Given Input Sequence in Python?

Time:01-16

I want to create a function that takes in a input sequence/list of given length

(ex: [48083, 50118, 50118, 39631, 5868, 452, 32, 460, 15, 49, 1028, 4, 252, 32, 460, 15, 49, 1028, 55, 87, 195, 722, 10, 183, 117, 912, 479, 3684, 51, 109, 16, 2788, 124, 8, 556, 8, 95, 33, 333, 732, 2923, 15, 592, 433, 4.])

and the function will output a random seqeunce of given length say 5 from the input

(ex: [48083, 50118, 50118, 39631, 5868] or [479, 3684, 51, 109, 16])

It would basically look something like this -

def foo(x, len):
  return ...

x = [48083, 50118, 50118, 39631, 5868, 452, 32, 460, 15, 49]
output_seq = foo(x, 5) # [39631, 5868, 452, 32, 460]
output_seq = foo(x, 5) # [452, 32, 460, 15, 49]
output_seq = foo(x, 5) # [50118, 50118, 39631, 5868, 452]

Can this be done in python3x ? Any help would be appreciated ?

CodePudding user response:

Your question boils down to randomly picking a start index. You need to make sure that index gives enough room at the end to include the length you want, which will be something between 0 and the length of the list minus the size:

import random

l = [48083, 50118, 50118, 39631, 5868, 452, 32, 460, 15, 49, 1028, 4, 252, 32, 460, 15, 49, 1028, 55, 87, 195, 722, 10, 183, 117, 912, 479, 3684, 51, 109, 16, 2788, 124, 8, 556, 8, 95, 33, 333, 732, 2923, 15, 592, 433, 4.]

def foo(x, size):
    start = random.randint(0, len(x) - size)
    return x[start: start size]

foo(l, 5)
# [109, 16, 2788, 124, 8]

foo(l, 5)
# [10, 183, 117, 912, 479]

CodePudding user response:

You can just use random.sample(x, len):

x = [48083, 50118, 50118, 39631, 5868, 452, 32, 460, 15, 49]
print(random.sample(x, 5))
print(random.sample(x, 5))
print(random.sample(x, 5))

Output:

[50118, 39631, 48083, 460, 452]
[452, 50118, 15, 49, 48083]
[15, 452, 48083, 50118, 39631]
  •  Tags:  
  • Related