0

リストを 2 つのリストに分割してから n 回シャッフルする必要があります。n が何であれ、2 つのリストを (n の範囲で) シャッフルする for ループを作成するのに問題があります。1回だけシャッフルします。これは関数の私のコードです:

def shuffle(xs,n=1):
il=list()
if len(xs)%2==0:
    stop=int(len(xs)//2)
    a=xs[:stop]
    b=xs[stop:]
else:
    stop=int(len(xs)//2)
    a=xs[:stop]
    b=xs[stop:]
if n>0:
    for i in range(n):
        shuffle=interleave(a,b)
else:
    return 
return shuffle

私のインターリーブ関数は以前に定義されており、正しく機能しているようです。

4

1 に答える 1

0

リストをインターリーブしたいと仮定すると、単純な再帰関数を記述して n 回実行できます。リストをインターリーブすることの 1 つのことは、最初と最後の文字が常に同じになることだと思います。

def shuffle(lst, num):
    '''
    lst - is a list
    num - is the amount of times to shuffle
    '''
    def interleave(lst1,lst2):
        '''
        lst1 and lst2 - are lists to be interleaved together
        '''
        if not lst1:
            return lst2
        elif not lst2:
            return lst1
        return lst1[0:1] + interleave(lst2, lst1[1:])
    while num > 0:
        lst = interleave(lst[:len(lst)/2], lst[len(lst)/2:])
        print lst
        num -= 1
    return lst
于 2013-11-11T08:35:00.607 に答える