جواب «Search the Weights» چالش 5 از جلسهی 9
سؤال
کامپیوتر خودش وزنها را پیدا کند. هر w1، w2 و threshold از 0 تا 3 را امتحان کن و اولین ترکیبی را که همهی ۴ سطر AND را درست میدهد چاپ کن: found: w1=... w2=... threshold=... و بعد break از همهی حلقهها (با یک متغیر done).
راهنما
سه حلقهی تودرتو؛ داخلترین: if not done and score(w1, w2, t) == 4: چاپ کن و done = True.
یک جواب درست
def neuron(x1, x2, w1, w2, threshold):
total = x1 * w1 + x2 * w2
if total >= threshold:
return 1
return 0
truth = [(0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 1)]
def score(w1, w2, threshold):
correct = 0
for x1, x2, want in truth:
if neuron(x1, x2, w1, w2, threshold) == want:
correct += 1
return correct
done = False
for w1 in range(0, 4):
for w2 in range(0, 4):
for t in range(0, 4):
if not done and score(w1, w2, t) == 4:
print("found: w1=" + str(w1), "w2=" + str(w2), "threshold=" + str(t))
done = True
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن