質問

私は2つのints nとkを取得するアルゴリズムを実装しようとしています。ここで、nは連続した座席数であり、Kはその列に座ろうとする生徒の数です。問題は、各生徒が両側で少なくとも2つの席である必要があるということです。私が持っているのは、すべてのサブセットを生成する関数(0または1 sのいずれかの配列、1つの人がそこに座っていることを意味します)であり、これを関数に送信して、それが有効なサブセットであるかどうかを確認します。これは私がその関数に対して持っているコードです

def process(a,num,n):
    c = a.count('1')
    #If the number of students sitting down (1s) is equal to the number k, check the subset
    if(c == num):
        printa = True
        for i in range(0,n):
            if(a[i] == '1'):
                if(i == 0):
                    if( (a[i+1] == '0') and (a[i+2] == '0') ):
                        break
                    else:
                        printa = False
                elif(i == 1):
                    if( (a[i-1] == '0') and (a[i+1] == '0') and (a[i+2] == '0') ):
                        break
                    else:
                        printa = False
                elif(i == (n-1)):
                    if( (a[i-2] == '0') and (a[i-1] == '0') and (a[i+1] == '0') ):
                        break
                    else:
                        printa = False
                elif(i == n):
                    if( (a[i-2] == '0') and (a[i-1] == '0') ):
                        break
                else:
                    printa = False                    
            else:
                if( (a[i-2] == '0') and (a[i-1] == '0') and (a[i+1] == '0') and (a[i+2] == '0') ):
                    break
                else:
                    printa = False
        if(printa):
            print a
    else:
        return

コードはkとnの小さな入力で機能しますが、より高い値を取得すると、何らかの理由でリストからインデックスエラーが表示されます。
どんな助けも感謝します。

o入力aは、このようなものに見えるリストです

['1','0','0','1','0'] # a valid subset for n=5 and k=2
['0','0','0','1','1'] # an invalid subset

編集:

プロセスを呼び出すコード:

'''
This function will recursivly call itself until it gets down to the leaves then sends that
subset to process function.  It appends
either a 0 or 1 then calls itself
'''
def seatrec(arr,i,n,k):
    if(i==n):
        process(arr,k,n)
        return
    else:
        arr.append("0")
        seatrec(arr,i+1,n,k)
        arr.pop()
        arr.append("1")
        seatrec(arr,i+1,n,k)
        arr.pop()
    return
'''
This is the starter function that sets up the recursive calls
'''
def seat(n,k):
    q=[]
    seat(q,0,n,k)

def main():
    n=7
    k=3
    seat(n,k)

if __name__ == "__main__":
    main()

これらの数字を使用した場合に得られるエラー

if( (a[i-2] == '0') and (a[i-1] == '0') and (a[i+1] == '0') ):
IndexError: list index out of range
役に立ちましたか?

解決

無効な座席の手配を除外するだけで十分です。つまり、学生が隣同士に座ったとき ['1', '1'] または、それらの間に座席が1つしかない場合 ['1', '0', '1'] 正しい数の他のすべてのアレンジメント '1', 、 と '0' 有効です、 :

def isvalid(a, n, k):
    if not isinstance(a, basestring):
       a = ''.join(a) # `a` is a list of '1', '0'
    return (len(a) == n and a.count('1') == k and a.count('0') == (n-k) and
            all(p not in a for p in ['11', '101']))

すべてのサブセットをチェックせずに有効なサブセットを生成するためのより効率的なアルゴリズムがあります。

def subsets(n, k):
    assert k >= 0 and n >= 0
    if k == 0: # no students, all seats are empty
        yield '0'*n
    elif k == 1 and (n == 1 or n == 2): # the last student at the end of the row
        yield '1' + '0'*(n-1) # either '1' or '10'
        if n == 2: yield '01'
    elif n > 3*(k-1): # there are enough empty seats left for k students
        for s in subsets(n-3, k-1):
            yield '100' + s # place a student
        for s in subsets(n-1, k):
            yield '0' + s   # add empty seat

n, k = 5, 2
for s in subsets(n, k):
    assert isvalid(s, n, k)
    print(s)

出力

10010
10001
01001

他のヒント

長さの配列のインデックス n から 0n-1. 。したがって、アクセス n リストが外れています。

リストを生成するコードには、これが小さい値でこれに気付いていない場合は、バグが必要です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top