簡體   English   中英

交錯排列列表,直到它恢復為Python的原始順序

[英]Interleave shuffle a list until it returns to original order in Python

我正在嘗試交錯播放一副紙牌。 例如,[1,2,3,4,5,6]被切成兩半,分為[1,2,3]和[4,5,6],然后改組為[1,4,2,5,3 ,6]。 為此,我有:

listA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]
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

現在我的問題是,我該如何獲取listD(混洗后的卡片)並重復此過程,直到回到原始順序(1、2、3、4 ...)? 並打印出發生的洗牌數量。

listA = [1,2,3,4...]

while ListD!=ListA:
    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

只需將所有代碼放入while循環中,即可檢查ListD何時等於ListA。 (停止時它們將是相同的)

如何使用列表切片分配

def shuf(cards):
    half = len(cards) // 2
    res = cards[:]
    res[::2] = cards[:half]
    res[1::2] = cards[half:]
    return res

首先,我們創建原始列表的淺表副本(使用cards[:] )(只是為了獲得相同大小的“可寫”列表)。 然后,將初始列表的下半部分分配給結果列表的偶數索引( res[::2] ),並將上半部分分配給奇數索引( res[1::2] )。

例如:

>>> x = range(1,7); x
[1, 2, 3, 4, 5, 6]
>>> x = shuf(x); x
[1, 4, 2, 5, 3, 6]
>>> x = shuf(x); x
[1, 5, 4, 3, 2, 6]
>>> x = shuf(x); x
[1, 3, 5, 2, 4, 6]
>>> x = shuf(x); x
[1, 2, 3, 4, 5, 6]

完整的解決方案。

listA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]

listE = listA
listD = []
amountOfShuffles = 0
while listE != listD:
    num = 0
    listD = []
    listLen = len(listA)/2
    listB = listA[:listLen]
    listC = listA[listLen:]
    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])
    listA = listD
    amountOfShuffles += 1

print 'No of shuffles :',amountOfShuffles

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM