mercredi 25 mars 2015

Random contiguous slice of list in Python based on a single random integer

Using a single random number and a list, how would you return a random slice of that list?


For example, given the list [0,1,2] there are seven possibilities of random contiguous slices:



  1. [ ]

  2. [ 0 ]

  3. [ 0, 1 ]

  4. [ 0, 1, 2 ]

  5. [ 1 ]

  6. [ 1, 2]

  7. [ 2 ]


Rather than getting a random starting index and a random end index, there must be a way to generate a single random number and use that one value to figure out both starting index and end/length.





Aucun commentaire:

Enregistrer un commentaire