Skip to content

fix: int_to_roman silently returns wrong values for out-of-range input#14635

Open
faizzyhon wants to merge 2 commits intoTheAlgorithms:masterfrom
faizzyhon:fix/int-to-roman-invalid-input-validation
Open

fix: int_to_roman silently returns wrong values for out-of-range input#14635
faizzyhon wants to merge 2 commits intoTheAlgorithms:masterfrom
faizzyhon:fix/int-to-roman-invalid-input-validation

Conversation

@faizzyhon
Copy link
Copy Markdown

Problem

int_to_roman performed no input validation. Python's floor-division semantics silently corrupted results for out-of-range inputs:

# Before this fix:
int_to_roman(0)    # ''          <- silent wrong output
int_to_roman(-1)   # 'CMXCIX'   <- silently returns 999 (WRONG)
int_to_roman(-5)   # 'CMXCV'    <- silently returns 995 (WRONG)
int_to_roman(4000) # 'MMMM'     <- not a valid standard Roman numeral
int_to_roman(True) # 'I'        <- bool silently accepted as 1

Root cause: divmod(-1, 1000) returns (-1, 999) in Python, so 'M' * -1 yields '' and the remainder 999 propagates through the ROMAN lookup table, producing a plausible-looking but completely wrong answer.

Fix

Added early validation guards:

  1. TypeError for non-integer types (including bool, which is a subclass of int)
  2. ValueError for integers outside the valid range [1, 3999]
  3. Added four doctest error cases so the guards are exercised by the doctest runner

Describe your change:

  • Fix a bug or typo in an existing algorithm?

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.

Added input validation for int_to_roman function.
@algorithms-keeper algorithms-keeper Bot added enhancement This PR modified some existing files awaiting reviews This PR is ready to be reviewed tests are failing Do not merge until tests pass labels May 6, 2026
@algorithms-keeper algorithms-keeper Bot removed the tests are failing Do not merge until tests pass label May 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant