回溯python_用Python回溯算法
我試圖實(shí)現(xiàn)一個(gè)算法,該算法需要兩個(gè)in和n和k,其中n是連續(xù)的座位數(shù),k是試圖坐在那一行的學(xué)生人數(shù)。問題在于每個(gè)學(xué)生在兩邊都必須至少有兩個(gè)座位。我有一個(gè)函數(shù)可以生成所有的子集(一個(gè)0或1的數(shù)組,1表示某人坐在那里),然后我將它發(fā)送給一個(gè)函數(shù)來檢查它是否是一個(gè)有效的子集。這是我對該功能的代碼
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的小輸入,但如果我得到更高的值,出于某種原因我得不到列表錯(cuò)誤的索引。
任何幫助,非常感謝。
O輸入是一個(gè)看起來像這樣的列表
['1','0','0','1','0'] # a valid subset for n=5 and k=2
['0','0','0','1','1'] # an invalid subset編輯:
調(diào)用進(jìn)程的代碼:
'''
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()如果我使用這些數(shù)字,我得到的錯(cuò)誤是
if( (a[i-2] == '0') and (a[i-1] == '0') and (a[i+1] == '0') ):
IndexError: list index out of range
與50位技術(shù)專家面對面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的回溯python_用Python回溯算法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python建立虚拟环境不成功_virt
- 下一篇: websocket python爬虫_p