Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can we riffle shuffle the elements of a list in python?

Tags:

python

I want to shuffle the elements of a list without importing any module. The type of shuffle is riffle shuffle. Where you want to divide the no. of elements of the list into two and then interleave them.

if there are odd no. of elements then the second half should have contain the extra element

eg: list = [1,2,3,4,5,6,7]

then the final list should look like [1,4,2,5,3,6,7]
like image 346
user2977671 Avatar asked Nov 11 '13 02:11

user2977671


People also ask

How do you shuffle elements in a list in Python?

Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.

How do you randomize the order of items in a list Python?

To use shuffle, import the Python random package by adding the line import random near the top of your program. Then, if you have a list called x, you can call random. shuffle(x) to have the random shuffle function reorder the list in a randomized way. Note that the shuffle function replaces the existing list.

How do you shuffle two lists in Python?

Method : Using zip() + shuffle() + * operator In this method, this task is performed in three steps. Firstly, the lists are zipped together using zip(). Next step is to perform shuffle using inbuilt shuffle() and last step is to unzip the lists to separate lists using * operator.


1 Answers

Just for fun, a recursive solution:

def interleave(lst1, lst2):
    if not lst1:
        return lst2
    elif not lst2:
        return lst1
    return lst1[0:1] + interleave(lst2, lst1[1:])

Use it as follows in Python 2.x (In Python 3.x, use // instead of /):

lst = [1,2,3,4,5,6,7]
interleave(lst[:len(lst)/2], lst[len(lst)/2:])
=> [1, 4, 2, 5, 3, 6, 7]

The above will work fine with lists of any length, it doesn't matter if the length is even or odd.

like image 60
Óscar López Avatar answered Sep 20 '22 03:09

Óscar López