日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python的回溯信息_基于Python的回溯算法

發布時間:2025/3/19 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python的回溯信息_基于Python的回溯算法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我試圖實現一個算法,它包含兩個整數n和k,其中n是一排的座位數,k是試圖坐在那一排的學生數。問題是每一個學生必須在兩邊至少有兩個座位。我所擁有的是一個生成所有子集的函數(一個0或1s的數組,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

總結

以上是生活随笔為你收集整理的python的回溯信息_基于Python的回溯算法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。