if-statementboolean-logicboolean-expressionboolean-operationstruthtable

Simplify if-elif-else-if-else conditional structure into a single if-else


This would not be a problem for me if this was a "regular" program, however I am working with program synthesis and I have to have a code as compact as possible.

Consider the pseudocode below:

if A:
    return 'n'
elif B:
    return 'y'
else:
    if C:
        return 'n'
    else:
        return 'y'

A, B and C are boolean conditions (functions that returns a boolean in my real problem - their implementations are not important). I need this whole if-elif-else-if-else structure to be condensed into a single if-else structure.

The closest I got was:

if A or C:
    return 'n'
else:
    return 'y'

However, it fails for a single test case where A = False, B = True, C = True: it returns 'n' instead of 'y'.

The correct truth table is shown below for reference.

|-------|-------|-------|----------|
|   A   |   B   |   C   |  Result  |
|-------|-------|-------|----------|
|   T   |   T   |   T   |    n     |
|-------|-------|-------|----------|
|   T   |   T   |   F   |    n     |
|-------|-------|-------|----------|
|   T   |   F   |   T   |    n     |
|-------|-------|-------|----------|
|   T   |   F   |   F   |    n     |
|-------|-------|-------|----------|
|   F   |   T   |   T   |    y     |
|-------|-------|-------|----------|
|   F   |   T   |   F   |    y     |
|-------|-------|-------|----------|
|   F   |   F   |   T   |    n     |
|-------|-------|-------|----------|
|   F   |   F   |   F   |    y     |
|-------|-------|-------|----------|

Solution

  • if A or ( C and not B): return 'n' else: return 'y'

    Start from the logic table, and use boolean properties