質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

753閲覧

python の appendについてです。

bbiiq

総合スコア51

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/07/20 11:42

x.append((fitness(ans),ans))
pythonのappendの引数は一つということですが、上の結果はどういう扱いといいますか、どういうことなのしょうか。
どうしてもappendに引数を二つ渡しているように見えるのですが、エラーはおきません。

全体のコードです。

import random
import copy

パラメータ

gene_length = 10 # 遺伝子長
individual_length = 10 # 個体数
generation = 20 # 世代数
mutate_rate = 0.1 # 突然変異の確率
elite_rate = 0.2 # エリート選択の割合

def get_population():
population = []
for i in range(individual_length):
population.append([random.randint(0,1) for j in range(gene_length)])
return population

def fitness(pop):
return sum(pop)

def evaluate(pop):
pop.sort(reverse=True)
return pop

def two_point_crossover(parent1, parent2):
r1 = random.randint(0, gene_length-1)
r2 = random.randint(r1, gene_length-1)
child = copy.deepcopy(parent1)
child[r1:r2] = parent2[r1:r2]
return child

def mutate(parent):
r = random.randint(0, gene_length-1)
child = copy.deepcopy(parent)
child[r] = 1 if child[r]==0 else 0
return child

def main():
# 初期個体生成
pop = evaluate([(fitness(p), p) for p in get_population()])
print('Generation: 0')
print('Min : {}'.format(pop[-1][0]))
print('Max : {}'.format(pop[0][0]))
print('--------------------------')

for g in range(generation): print('Generation: ' + str(g+1)) # エリートを選択 eva = evaluate(pop) elites = eva[:int(len(pop)*elite_rate)] # 突然変異、交叉 pop = elites while len(pop) < individual_length: if random.random() < mutate_rate: m = random.randint(0, len(elites)-1) child = mutate(elites[m][1]) else: m1 = random.randint(0, len(elites)-1) m2 = random.randint(0, len(elites)-1) child = two_point_crossover(elites[m1][1], elites[m2][1]) pop.append((fitness(child), child)) # 評価 eva = evaluate(pop) pop = eva print('Min : {}'.format(pop[-1][0])) print('Max : {}'.format(pop[0][0])) print('--------------------------') print('Result : {}'.format(pop[0]))

if name == 'main':
main()

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

()が1つ入っているので、1つの「2要素タプル」を追加しています。

python

1pop.append((fitness(child), child))

投稿2021/07/20 11:47

TakaiY

総合スコア12745

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問