python - Mengapa hasilnya menjadi seperti itu dalam fungsi main()?
滿天的星座
滿天的星座 2017-05-18 11:00:11
0
1
645
#Any Queens puzzle
def share_diagonal(x0, y0, x1, y1):
    """ Is (x0, y0) on a shared diagonal with (x1, y1)? """
    dy = abs(y1 - y0)
    dx = abs(x1 - x0)
    return dx == dy


def col_clashes(bs, c):
    """
        Return True if the queen at column c clashes
        with any queen to its left.
    """
    for i in range(c):
        if share_diagonal(i, bs[i], c, bs[c]):
            return True
    return False


def has_clashes(the_board):
    """
        Determine whether we have any queens clashing on the diagonals.
        We're assuming here that the_board is a permutation of column
        numbers, so we're not explicitly checking row or column clashes.
        If it has clashes, return True.
    """
    for col in range(1, len(the_board)):
        if col_clashes(the_board, col):
            return True
    return False


def interchange_list(j, k, list):
    temp = list[j]
    list[j] = list[k]
    list[k] = temp



def generating_next_permutation_in_lexicographic_order(per_list):
    n = len(per_list) - 1
    j = n - 1
    while per_list[j] > per_list[j + 1]:
        j = j - 1
        if j < 0:
            return 0
    k = n
    while per_list[j] > per_list[k]:
        k = k - 1
    interchange_list(j, k, per_list)
    r = n
    s = j + 1
    while r > s:
        interchange_list(r, s, per_list)
        r = r - 1
        s = s + 1
    return per_list


def main(num):
    per_list = list(range(0, num))
    tries = 0
    num_found = 0
    result = []
    while per_list != 0:
        tries += 1
        if not has_clashes(per_list):
            #print("Found solution {0} in {1} tries.".format(per_list, tries))
            list1 = per_list
            result.append(list1)
            #print(result)
            num_found += 1
        per_list = generating_next_permutation_in_lexicographic_order(per_list)
    print(num_found)
    print(result)
    

main(8)

Hasil cetakan ialah
92
[[7, 6, 5, 4, 3, 2, 1, 0], [7, 6, 5, 4, 3, 2, 1, 0], [7, 6, 5 , 4, 3, 2, 1, 0], [7, 6, 5, 4, 3, 2, 1, 0], [7, 6, 5, 4, 3, 2, 1, 0], [ 7 , 6, 5, 4, 3, 2, 1, 0], [7, 6, 5, 4, 3, 2, 1, 0], [7, 6, 5, 4, 3, 2, 1, 0 ], [7, 6, 5,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[Tamat dalam 0.2s]
Mengapa keputusan menjadi sama?

滿天的星座
滿天的星座

membalas semua(1)
滿天的星座

Masalahnya terletak pada fungsi generating_next_permutation_in_lexicographic_order.
Senarai dalam Python ialah jenis pembolehubah, jadi anda sebenarnya hanya mengendalikan satu Senarai secara global, dan kemudian terus meletakkan rujukan kepada Senarai yang sama ke dalam hasilnya, sudah tentu ia akan menjadi seperti ini.
Pengubahsuaian mudah:

generating_next_permutation_in_lexicographic_order(per_list):
    import copy
    per_list = copy.deepcopy(per_list)
    #剩下是你原来的代码
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan