How can we riffle shuffle list items in python?

I want to shuffle list items without importing any module. The type of shuffle is a random shuffle. Where you want to split is not. list items into two, and then interleave them.

if there is an odd number. elements, then the second half should contain an additional element

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

then the final list should look like [1,4,2,5,3,6,7]
+4
source share
6 answers
listA = [1,2,3,4,5,6,7,8,9]
listLen = len(listA)/2
listB = listA[:listLen]
listC = listA[listLen:]
listD = []
num = 0
while num < listLen:
    if len(listB) >= num:
        listD.append(listB[num])
        listD.append(listC[num])
    num += 1
if len(listA)%2 != 0:
    listD.append(listC[num])
print listD

By looking at another answer, I also add a recursive version, which is a revised version of another guy's answer, but easier to call, since you only need to call the function with one argument (the list you are trying to shuffle), and it does the rest:

def interleave(lst):
    def interleaveHelper(lst1,lst2):
        if not lst1:
            return lst2
        elif not lst2:
            return lst1
        return lst1[0:1] + interleaveHelper(lst2, lst1[1:])
    return interleaveHelper(lst[:len(lst)/2], lst[len(lst)/2:])

, interleave(list)

+2

, :

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

Python 2.x( Python 3.x // /):

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

, , .

+2

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

, :

def riffle(deck):
    '''
    Shuffle a list like a deck of cards.
    i.e. given a list, split with second set have the extra if len is odd
    and then interleave, second deck first item after first deck first item
    and so on. Thus:
    riffle([1,2,3,4,5,6,7])
    returns [1, 4, 2, 5, 3, 6, 7]
    '''
    cut = len(deck) // 2                        # floor division
    deck, second_deck = deck[:cut], deck[cut:]
    for index, item in enumerate(second_deck):
        insert_index = index*2 + 1
        deck.insert(insert_index, item)
    return deck

...

import unittest
class RiffleTestCase(unittest.TestCase):
    def test_riffle(self):
        self.assertEqual(riffle(['a','b','c','d','e']), ['a','c','b','d','e'])
        self.assertEqual(riffle([1,2,3,4,5,6,7]), [1,4,2,5,3,6,7])

unittest.main()
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
+2

, next Python.

, , .

, , Python iter. , , next(iterable) , .

, , ( next ).

:

elements = [1,2,3,4,5,6,7]

half_point = len(elements)/2

a = iter(elements[0:half_point])
b = iter(elements[half_point: ])

result = []
for i in range(half_point):
    result.append(next(a))
    result.append(next(b))

if len(elements) % 2 != 0:
    result.append(next(b))

print result

>>> [1, 4, 2, 5, 3, 6, 7]

, . , .

, , , zipping , , itertools;)

0

, zip .

n = 9
l = range(1,n+1)
a = l[:n/2]
b = l[n/2:]
c = zip(a,b)
d = list()
for p in c :
    d.extend(list(p))
if n%2==1:
    d.append(b[n/2])
print(d)
0
>>> ll = list(range(1,8))
>>> mid = len(ll)/2   # for Python3, use '//' operator
>>> it1 = iter(ll[:mid])
>>> it2 = iter(ll[mid:])
>>> riff = sum(zip(it1,it2), ()) + tuple(it2)
>>> riff
(1, 4, 2, 5, 3, 6, 7)

If this is homework, be prepared to explain how it works sumand zipwhy the second parameter is needed sum, why it is tuple(it2)added to the end, and how this solution has inherent inefficiency.

0
source

All Articles