亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 列表和字典被覆蓋或損壞?

Python 列表和字典被覆蓋或損壞?

PHP
慕斯王 2023-11-09 10:39:06
我正在嘗試暴力解決 N 皇后國際象棋問題https://en.wikipedia.org/wiki/Eight_queens_puzzle我的代碼正在工作,但是當我嘗試返回解決方案數據結構時,會出現異常行為。包含解決方案的列表在某些時候被覆蓋或損壞。我嘗試過使用多種不同的數據結構列表、字典、集合,并且都具有相同的結果。輸出應該是[[1, 3, 0, 2], [1, 3, 0, 2], [1, 3, 0, 2], [1, 3, 0, 2], [1, 3, 0, 2], [1, 3, 0, 2], [1, 3, 0, 2], [1, 3, 0, 2]]但目前正在返回[[3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3]]import numpy as np# Validation Functionsdef checkRows(state):    """    Check only 1 queen per row    """         for row in state:                if sum(row) > 1:            return False    return Truedef checkCols(state):    """    Check only 1 queen exists in a column    """    for i in range(0,len(state)):        count = 0        for j in range(0,len(state)):                        #print(state[j][i])            count = count + state[j][i]        if count > 1: return False    return True       def checkDiag(state):    """    Checks only 1 queen exists per diagonal    https://stackoverflow.com/questions/6313308/get-all-the-diagonals-in-a-matrix-list-of-lists-in-python    """    # Alter dimensions as needed    n = len(state)    x,y = n,n    # incoming state list        a = np.array(state)    diags = [a[::-1,:].diagonal(i) for i in range(-a.shape[0]+1,a.shape[1])]        diags.extend(a.diagonal(i) for i in range(a.shape[1]-1,-a.shape[0],-1))    for n in diags:        if sum(n) > 1: #if any of the diagonals sums to more than 1 there must be more than 1 queen in that diagonal            return False    return True        def checkState(state):    """    Returns false on one or more failures    """    return checkRows(state) and checkCols(state) and checkDiag(state)
查看完整描述

1 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊


mylist.append(this_permutation.copy())


查看完整回答
反對 回復 2023-11-09
  • 1 回答
  • 0 關注
  • 156 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號