Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Randomly Crop a Given Input Sequence in Python?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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 ?

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading