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]. 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...)? 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. (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). 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]
).
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.