TheAlgorithms/Python · error · Exception

Unable to find the secret passcode

Error message

Unable to find the secret passcode

What it means

Raised by the internal passcode search in project_euler/problem_079/sol1.py when no permutation of the digits satisfies every login attempt's ordering constraints. It is a bare Exception (not ValueError), signaling the exhausted search space of itertools.permutations. In practice it is nearly unreachable: the supplied keylog data has a valid answer (73162890 ordering), so hitting it usually means the input file was modified or the login-parsing pipeline changed.

Source

Thrown at project_euler/problem_079/sol1.py:53

    split_logins = [tuple(login) for login in logins]

    unique_chars = {char for login in split_logins for char in login}

    for permutation in itertools.permutations(unique_chars):
        satisfied = True
        for login in logins:
            if not (
                permutation.index(login[0])
                < permutation.index(login[1])
                < permutation.index(login[2])
            ):
                satisfied = False
                break

        if satisfied:
            return int("".join(permutation))

    raise Exception("Unable to find the secret passcode")


def solution(input_file: str = "keylog.txt") -> int:
    """
    Returns the shortest possible secret passcode of unknown length
    for successful login attempts given by `input_file` text file.

    >>> solution("keylog_test.txt")
    6312980
    """
    logins = Path(__file__).parent.joinpath(input_file).read_text().splitlines()

    return find_secret_passcode(logins)


if __name__ == "__main__":
    print(f"{solution() = }")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Restore the original keylog file (git checkout -- project_euler/problem_079/keylog.txt) and retest.
  2. If testing custom inputs, first verify the constraints are acyclic (topological sort of the digit graph must succeed).
  3. Catch Exception narrowly around this call if you accept untrusted keylogs, since it is a bare Exception.
  4. Re-run the doctest: python -m doctest project_euler/problem_079/sol1.py -v.

Example fix

# before
passcode = find_passcode(contradictory_logins)  # may raise bare Exception

# after
try:
    passcode = find_passcode(logins)
except Exception as exc:
    raise ValueError("keylog constraints are unsatisfiable") from exc
Defensive patterns

Strategy: try-catch

Validate before calling

from collections import defaultdict

def constraints_are_acyclic(logins: list[str]) -> bool:
    graph = defaultdict(set)
    digits = set()
    for login in logins:
        digits.update(login)
        for a, b in zip(login, login[1:]):
            graph[a].add(b)
    # Kahn's algorithm
    indeg = {d: 0 for d in digits}
    for outs in graph.values():
        for b in outs:
            indeg[b] += 1
    queue = [d for d, k in indeg.items() if k == 0]
    seen = 0
    while queue:
        d = queue.pop()
        seen += 1
        for b in graph[d]:
            indeg[b] -= 1
            if indeg[b] == 0:
                queue.append(b)
    return seen == len(digits)

Try / catch

try:
    passcode = find_passcode(logins)
except Exception as exc:  # bare Exception in the library
    raise ValueError("keylog constraints are unsatisfiable") from exc

Prevention

When it happens

Trigger: Calling the search helper (e.g. find_passcode) with a fabricated login list whose constraints are contradictory, such as ['12', '21'] style cycles in 3-char form like ['123', '321']. Modifying keylog.txt to include cyclic constraints. Feeding a truncated/garbled file so constraints become inconsistent.

Common situations: Custom keylog experiments with hand-written attempts; unit tests probing unsatisfiable inputs; edits to the constraint check or permutation space that drop the real solution.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/60ee6c8cacacda28. Report an issue: GitHub.