From a truth table to a sum of minterms

A function of n variables (named A, B, C, … with A as the leftmost bit) is given by its truth table's output column. Print its minterm list and its sum of products.

Input

A line with n (1 ≤ n ≤ 4), then a line with the 2ⁿ output bits for rows 0, 1, 2, … in order, as one string such as 00010111.

Output

Two lines:

  • m( followed by the minterm numbers separated by commas, then ), for example m(3,5,6,7);
  • the sum of products, terms joined by +, with a complemented variable written with ', for example A'BC + AB'C + ABC' + ABC. If the function is never 1, print 0.

Examples

Example 1 · Input
3
00010111
Expected output
m(3,5,6,7)
A'BC + AB'C + ABC' + ABC
Example 2 · Input
2
0110
Expected output
m(1,2)
A'B + AB'

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

The rows with a 1 are the minterms: row r is 1 when the output string has '1' at position r.

Hint 2

For each minterm, write the row number in binary with n digits: a 1 bit means the variable, a 0 bit means the variable with '.

Hint 3

Join the terms with ' + '. With no 1s at all, print m() and 0.

Solution

Show one correct solution (try it yourself first)
n = int(input())
outputs = input().strip()
names = "ABCD"
ones = [r for r in range(2 ** n) if outputs[r] == "1"]
terms = []
for r in ones:
    bits = format(r, "0" + str(n) + "b")
    terms.append("".join(names[i] if bit == "1" else names[i] + "'" for i, bit in enumerate(bits)))
print("m(" + ",".join(map(str, ones)) + ")")
print(" + ".join(terms) if terms else "0")

Lesson: Minterms, maxterms and canonical forms →