![]() This ensures that no duplicate elements are added, since you're just slicing the list, and we've shuffled it so the collections are random. You shuffle() the list and partition it into n parts. If you're looking to create random collections of n elements, with no repetitions, the task is seemingly more complex than the previous tasks, but in practice - it's pretty simple. Now, an even better solution than the last would be to use random.choice() as this is precicely the function designed to solve this problem: This approach is a tiny bit simpler than the last, simply because we don't specify the starting point, which defaults to 0. Running this code multiple times will produce something along the lines of: fĪs random.randrange(len(letters)) returns a randomly generated number in the range 0 to len(letters) - 1, we use it to access an element at random in letters, just like we did in the previous approach. Random_index = random.randrange( len(letters)) Random.randrange(a) is another method which returns a random number n such that 0 <= n < a: import random Running this code multiple times yields us: e Random_index = random.randint( 0, len(letters)- 1) We'll want random index in the range of 0 to len(list)-1, to get a random index of an element in the list: import random ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |