[英]Interleave shuffle a list until it returns to original order in Python
I am trying to interleave shuffle a deck of cards. 我正在尝试交错播放一副纸牌。 For example [1,2,3,4,5,6] gets cut in half into [1,2,3] and [4,5,6] and then shuffled to become [1,4,2,5,3,6]. 例如,[1,2,3,4,5,6]被切成两半,分为[1,2,3]和[4,5,6],然后改组为[1,4,2,5,3 ,6]。 To accomplish this I have: 为此,我有:
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
Now my question is, how can I take listD (the shuffled cards) and repeat this process until I get back to the original order (1,2,3,4...)? 现在我的问题是,我该如何获取listD(混洗后的卡片)并重复此过程,直到回到原始顺序(1、2、3、4 ...)? And print out the amount of shuffles that occurred. 并打印出发生的洗牌数量。
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
Just throw all of the code into a while loop that checks when ListD equals ListA. 只需将所有代码放入while循环中,即可检查ListD何时等于ListA。 (when it stops they will be the same) (停止时它们将是相同的)
How about using a list slice assignment ? 如何使用列表切片分配 ?
def shuf(cards):
half = len(cards) // 2
res = cards[:]
res[::2] = cards[:half]
res[1::2] = cards[half:]
return res
First we create a shallow copy (with cards[:]
) of the original list (just to get a "writable" list of the same size). 首先,我们创建原始列表的浅表副本(使用cards[:]
)(只是为了获得相同大小的“可写”列表)。 Then we assign the lower half of the initial list to even indices of the result list ( res[::2]
), and the upper half to the odd indices ( res[1::2]
). 然后,将初始列表的下半部分分配给结果列表的偶数索引( res[::2]
),并将上半部分分配给奇数索引( res[1::2]
)。
For example: 例如:
>>> 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]
The Complete solution . 完整的解决方案。
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.