python - Pourquoi le résultat devient-il comme ça dans la fonction main() ?
滿天的星座
滿天的星座 2017-05-18 11:00:11
0
1
644
#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)

Le résultat imprimé est
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, 4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2 s]
Pourquoi les résultats deviennent-ils les mêmes ?

滿天的星座
滿天的星座

répondre à tous(1)
滿天的星座

Le problème réside dans la fonction generate_next_permutation_in_lexicographic_order.
La liste en Python est un type de variable, donc vous n'exploitez en fait qu'une seule liste globalement, puis vous mettez continuellement des références à la même liste dans le résultat, bien sûr, ce sera comme ça.
Une modification simple :

generating_next_permutation_in_lexicographic_order(per_list):
    import copy
    per_list = copy.deepcopy(per_list)
    #剩下是你原来的代码
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal