[Python] Cycle changes list that it should not [duplicate]

Discussão em 'Python' iniciado por Stack, Dezembro 1, 2024.

  1. Stack

    Stack Membro Participativo

    I'm writing weights mutator for my neural network. "distribute_genome" function should slightly mutate best genome and return it.

    import random
    best_genome = [[1, 2, 3], [4, 5, 6]]
    def distribute_genome():
    unique_genom = best_genome
    print(best_genome)
    for i in range(len(unique_genom)):
    for j in range(len(unique_genom)):
    unique_genom[j] += random.randint(-2, 2) #mutation
    print(best_genome)
    print("does not work" if unique_genom == best_genome else "ok")
    return unique_genom
    print(distribute_genome())


    But i noticed that best_genome being chanded when fuction runs. Soon i discovered that this loop changes it, if i delete the loop best_genome will stay same.

    for i in range(len(unique_genom)):
    for j in range(len(unique_genom)):
    unique_genom[j] += random.randint(-2, 2) #mutation


    I found out the reason of this error, and a question with the same problem but it still gives the same result, like here:

    import random
    best_genome = [[1, 2, 3], [4, 5, 6]]
    def distribute_genome():
    unique_genom = list(best_genome)
    for i in range(len(unique_genom)):
    for j in range(len(unique_genom)):
    unique_genom[j] += random.randint(-2, 2) #mutation
    return unique_genom

    print("does not work" if distribute_genome() == best_genome else "works")
    >does not work


    How should i fix this?

    Continue reading...

Compartilhe esta Página