#coding: utf-8"""http://www.zhihu.com/question/21503093a set of cards including 52 cards tagged from 1 to 52, no joker cards"""importcopydefperfect_shuffle(cards):size=len(cards)left,right=cards[0:size/2],cards[size/2:]new_cards=[]foriinrange(size/2):new_cards.append(left[i])new_cards.append(right[i])returnnew_cardsdefmain():cards=range(1,53)shuffle_times=0old_cards=copy.deepcopy(cards)new_cards=[]whileTrue:new_cards=perfect_shuffle(old_cards)shuffle_times+=1ifnew_cards==cards:breakold_cards=copy.deepcopy(new_cards)printshuffle_timesif__name__=='__main__':main()
最终确定是8次。
但是我这个完美洗牌算法不是最优解。正确的完美洗牌要求是:
输入a1, a2, …, an, b1, b2, …, bn,这是一个2n大小的数组。要求用O(n)的时间,用O(1)的空间,将这个序列顺序改为a1, b1, …, an, bn。