Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly move a certain number of items in a Python list

So I've been doing some sorting algorithms and I want to run a test function that generates lists of different varieties to run my sorting algorithms on.

One such list would be an already sorted list, where n number of the items in the list have been shuffled around randomly (but not all of them, the list should still be sorted other than the n items)

testlist = random.sample(range(0,10),10)
testlist.sort()

This gives me a sorted list of unique items of size 10, but then I'm unsure how to go about moving n of these 10 items around the list to a random location, just to mix the sorting up

like image 786
Woooooooooooooow Avatar asked Feb 10 '16 01:02

Woooooooooooooow


People also ask

How do I randomly select multiple items from a list in Python?

Use the random. sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.

How do you randomly pick a number from a list in Python?

Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.

How do you move a list element in Python?

Method : Using pop() + insert() + index() In this we just use the property of pop function to return and remove element and insert it to the specific position of other list using index function.

How do you randomly choose from a list in Python without repeating?

In simple terms, for example, you have a list of 100 names, and you want to choose ten names randomly from it without repeating names, then you must use random. sample() .


1 Answers

Here's one way to shuffle some items in the list:

import random
import numpy as np

# Make a sorted list of integers.
x = np.array(range(100))

# Choose 10 indices at random.
r = random.sample(range(len(x)), 10)

# Copy this list and shuffle.
s = r.copy()
random.shuffle(s)

# Replace the indices with the shuffled ones.
x[r] = x[s]

Note this might leave some indices unchanged.

like image 68
kwinkunks Avatar answered Nov 08 '22 23:11

kwinkunks