0

パイソン

この 2 つのコードが異なる理由を説明してください。実際に私は、最初の世代で個人がランダムな方向に進むような AI を作ろうとしています。コードをシンプルに保つために、ブレイン自身でランダムな指示をいくつか提供しました。

個人に頭脳を与える個人クラスがあります。また、親とまったく同じ脳 (同じ方向に進むことを意味します) を持つ子供を返す機能もあります。

私は2つのコードを持っています:

最初:親でいくつかの方向が変更されると、同じことが子でも変更されます(または子で変更された場合、親でも変更されます)。

2番目:これは完全に私のものではありません(そのため、なぜ機能するのかよくわかりません)が、正常に機能します。親で変更された一部の方向は、子では変更されず、その逆も同様です。

誰かが違いと、最初のものが機能しなかった理由を説明してください。ご回答いただければ幸いです。


最初の1つ:

class Brain():
    def __init__(self):
        self.directions = [[1, 2], [5, 3], [7, 4], [1, 5]]

class Individual():
    def __init__(self):
        self.brain = Brain()

    def getChild(self):
        child = Individual()
        child.brain = self.brain
        return child

parent = Individual()
child = parent.getChild()

parent.brain.directions[0] = [5, 2]

print(parent.brain.directions)
print(child.brain.directions)

[ [5, 2], [5, 3], [7, 4], [1, 5] ]

[ [5, 2], [5, 3], [7, 4], [1, 5] ]



二つ目:

class Brain():
    def __init__(self):
        self.directions = [[1, 2], [5, 3], [7, 4], [1, 5]]

    def clone(self):
        clone = Brain()
        for i, j in enumerate(self.directions):
            clone.directions[i] = j
        return clone

class Individual():
    def __init__(self):
        self.brain = Brain()

    def getChild(self):
        child = Individual()
        child.brain = self.brain.clone()
        return child

parent = Individual()
child = parent.getChild()

parent.brain.directions[0] = [5, 2]

print(parent.brain.directions)
print(child.brain.directions)

[ [5, 2], [5, 3], [7, 4], [1, 5] ]

[ [1, 2], [5, 3], [7, 4], [1, 5] ]

4

2 に答える 2