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
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.
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.
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.
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() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With