بتل کد Battle Codeدارد باز می‌شود…

جواب «Step 4: Accuracy» چالش 4 از جلسه‌ی 12

سؤال

لیست tests عکس‌های تازه با برچسب درست دارد. هر کدام را با recognise تشخیص بده، چاپ کن guess 1 real 1 ok یا ... wrong، و در پایان accuracy: 4 of 4.

راهنما

for picture, real in tests: g = recognise(picture)؛ اگر g == real بود ok و شمارنده، وگرنه wrong.

یک جواب درست

def flatten(picture):
    return [1 if ch == "#" else 0 for row in picture for ch in row]

def distance(a, b):
    return sum(1 for i in range(len(a)) if a[i] != b[i])

training = [
    ([".#####.", "#.....#", "#.....#", "#.....#", "#.....#", "#.....#", ".#####."], 0),
    (["..###..", ".#...#.", "#.....#", "#.....#", "#.....#", ".#...#.", "..###.."], 0),
    ([".####..", "#....#.", "#....#.", "#....#.", "#....#.", "#....#.", ".####.."], 0),
    (["...#...", "..##...", "...#...", "...#...", "...#...", "...#...", ".#####."], 1),
    (["...#...", "...#...", "...#...", "...#...", "...#...", "...#...", "...#..."], 1),
    (["..#....", ".##....", "..#....", "..#....", "..#....", "..#....", ".####.."], 1),
]
tests = [
    (["...#...", "..##...", "...#...", "...#...", "...#...", "...#...", "..###.."], 1),
    ([".#####.", "#.....#", "#.....#", "#..#..#", "#.....#", "#.....#", ".#####."], 0),
    (["....#..", "...##..", "....#..", "....#..", "....#..", "....#..", "..####."], 1),
    (["..####.", ".#....#", ".#....#", ".#....#", ".#....#", ".#....#", "..####."], 0),
]

def recognise(picture):
    pixels = flatten(picture)
    scored = []
    for p, label in training:
        scored.append((distance(pixels, flatten(p)), label))
    scored.sort()
    votes = {}
    for d, label in scored[:3]:
        votes[label] = votes.get(label, 0) + 1
    return max(votes, key=votes.get)

correct = 0
for picture, real in tests:
    g = recognise(picture)
    if g == real:
        print("guess", g, "real", real, "ok")
        correct += 1
    else:
        print("guess", g, "real", real, "wrong")
print("accuracy:", correct, "of", len(tests))

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن