Back to Freecodecamp

Challenge 221: Inverted Matrix

curriculum/challenges/english/blocks/daily-coding-challenges-python/699c8e045ee7cb94ed2322dc.md

latest2.6 KB
Original Source

--description--

Given a matrix (an array of arrays) filled with two distinct values, return a new matrix where all occurrences of one value are swapped with the other.

For example, given:

js
[
  ["a", "b"],
  ["a", "a"]
]

Return:

js
[
  ["b", "a"],
  ["b", "b"]
]

--hints--

invert_matrix([["a", "b"], ["a", "a"]]) should return [["b", "a"], ["b", "b"]].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(invert_matrix([["a", "b"], ["a", "a"]]), [["b", "a"], ["b", "b"]])`)
}})

invert_matrix([[1, 0, 1], [1, 1, 1], [0, 1, 0]]) should return [[0, 1, 0], [0, 0, 0], [1, 0, 1]].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(invert_matrix([[1, 0, 1], [1, 1, 1], [0, 1, 0]]), [[0, 1, 0], [0, 0, 0], [1, 0, 1]])`)
}})

invert_matrix([["apple", "banana", "banana", "apple"], ["banana", "apple", "apple", "banana"], ["banana", "banana", "banana", "apple"]]) should return [["banana", "apple", "apple", "banana"], ["apple", "banana", "banana", "apple"], ["apple", "apple", "apple", "banana"]].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(invert_matrix([["apple", "banana", "banana", "apple"], ["banana", "apple", "apple", "banana"], ["banana", "banana", "banana", "apple"]]), [["banana", "apple", "apple", "banana"], ["apple", "banana", "banana", "apple"], ["apple", "apple", "apple", "banana"]])`)
}})

invert_matrix([[6, 7, 7, 7, 6], [7, 6, 7, 6, 7], [7, 7, 6, 7, 7], [7, 6, 7, 6, 7], [6, 7, 7, 7, 6]]) should return [[7, 6, 6, 6, 7], [6, 7, 6, 7, 6], [6, 6, 7, 6, 6], [6, 7, 6, 7, 6], [7, 6, 6, 6, 7]].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(invert_matrix([[6, 7, 7, 7, 6], [7, 6, 7, 6, 7], [7, 7, 6, 7, 7], [7, 6, 7, 6, 7], [6, 7, 7, 7, 6]]), [[7, 6, 6, 6, 7], [6, 7, 6, 7, 6], [6, 6, 7, 6, 6], [6, 7, 6, 7, 6], [7, 6, 6, 6, 7]])`)
}})

invert_matrix([[1.2, 2.1, 2.1, 2.1], [2.1, 1.2, 2.1, 1.2], [1.2, 1.2, 2.1, 2.1]]) should return [[2.1, 1.2, 1.2, 1.2], [1.2, 2.1, 1.2, 2.1], [2.1, 2.1, 1.2, 1.2]].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(invert_matrix([[1.2, 2.1, 2.1, 2.1], [2.1, 1.2, 2.1, 1.2], [1.2, 1.2, 2.1, 2.1]]), [[2.1, 1.2, 1.2, 1.2], [1.2, 2.1, 1.2, 2.1], [2.1, 2.1, 1.2, 1.2]])`)
}})

--seed--

--seed-contents--

py
def invert_matrix(matrix):

    return matrix

--solutions--

py
def invert_matrix(matrix):
    flat = [cell for row in matrix for cell in row]
    values = list(set(flat))
    val1, val2 = values

    return [[val2 if cell == val1 else val1 for cell in row] for row in matrix]