Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 44 additions & 7 deletions ciphers/simple_keyword_cypher.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ def create_cipher_map(key: str) -> dict[str, str]:

:param key: keyword to use
:return: dictionary cipher map

>>> cmap = create_cipher_map('Goodbye!!')
>>> len(cmap)
26
>>> cmap['A']
'G'
>>> cmap['B']
'O'
>>> cmap['Z']
'Z'
>>> identity = create_cipher_map('')
>>> identity['A']
'A'
"""
# Create a list of the letters in the alphabet
alphabet = [chr(i + 65) for i in range(26)]
Expand Down Expand Up @@ -74,6 +87,35 @@ def decipher(message: str, cipher_map: dict[str, str]) -> str:
return "".join(rev_cipher_map.get(ch, ch) for ch in message.upper())


def process_cipher(message: str, key: str, option: str) -> str:
"""
Enciphers or deciphers a message using a keyword cipher.

:param message: Message to encipher or decipher
:param key: Keyword for cipher map generation
:param option: 'e' for encipher, 'd' for decipher
:return: Enciphered or deciphered message
:raises KeyError: If option is invalid

>>> process_cipher('Hello World!!', 'Goodbye!!', 'e')
'CYJJM VMQJB!!'
>>> process_cipher('CYJJM VMQJB!!', 'Goodbye!!', 'd')
'HELLO WORLD!!'
>>> process_cipher('Hello World!!', 'Goodbye!!', 'E')
'CYJJM VMQJB!!'
>>> process_cipher('Hello', 'Key', 'x')
Traceback (most recent call last):
...
KeyError: 'invalid input option'
"""
clean_option = option.strip()[:1].lower()
operations = {"e": encipher, "d": decipher}
if clean_option not in operations:
raise KeyError("invalid input option")
cipher_map = create_cipher_map(key)
return operations[clean_option](message, cipher_map)


def main() -> None:
"""
Handles I/O
Expand All @@ -82,13 +124,8 @@ def main() -> None:
"""
message = input("Enter message to encode or decode: ").strip()
key = input("Enter keyword: ").strip()
option = input("Encipher or decipher? E/D:").strip()[0].lower()
try:
func = {"e": encipher, "d": decipher}[option]
except KeyError:
raise KeyError("invalid input option")
cipher_map = create_cipher_map(key)
print(func(message, cipher_map))
option = input("Encipher or decipher? E/D:").strip()
print(process_cipher(message, key, option))


if __name__ == "__main__":
Expand Down
33 changes: 33 additions & 0 deletions work/R23-T030/PR_BODY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
## Summary of Changes

### Task R23-T030: Refactor `ciphers/simple_keyword_cypher.py` to separate I/O from cipher logic

This pull request completes Task R23-T030 (10 of 10) by restructuring `ciphers/simple_keyword_cypher.py` using tests as a safety net.

### 1. Goal and Architectural Improvements
- Separated console I/O from pure cipher logic in `main()`:
- Extracted pure dispatch and validation function `process_cipher(message, key, option)` with complete doctests.
- Reduced `main()` to pure sequential I/O delegation (`input()` $\rightarrow$ `process_cipher()` $\rightarrow$ `print()`).
- Added 7 doctests to `create_cipher_map(key)` (previously had 0).
- Kept existing doctests for `encipher`, `decipher`, and `remove_duplicates` unchanged and passing.

### 2. Complexity & Coverage Evidence (`work/R23-T030/REFACTOR.md`)
- **Cyclomatic Complexity (Ruff C901 / McCabe)**:
- `main()` complexity reduced from **2 to 1** (-50%).
- **Test Coverage**:
- Code coverage increased from **68% to 82%**.
- Doctests increased from 4 to 15 (all 15 passing).

### 3. Verification & Test Evidence
- `uvx ruff check ciphers/simple_keyword_cypher.py`: Passed (0 errors).
- `uvx ruff format --check ciphers/simple_keyword_cypher.py`: Passed (1 file already formatted).
- `python3 -m doctest -v ciphers/simple_keyword_cypher.py`: All 15 doctests passed.
- `pytest --cov`: All tests passed with 82% coverage.
- `python3 scripts/validate_filenames.py`: Passed cleanly.

### 4. Submission Checklist
- [x] Logic separated from `input()` in `main()` into pure function `process_cipher`.
- [x] `create_cipher_map` gained doctests (7 new tests).
- [x] `REFACTOR.md` documents before/after cyclomatic complexity and coverage.
- [x] Existing doctests for `encipher`, `decipher`, and `remove_duplicates` remain unchanged and passing.
- [x] Clean upstream branch `student/E26B07F0850/R23-T030-upstream` prepared with only code changes.
74 changes: 74 additions & 0 deletions work/R23-T030/REFACTOR.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Refactoring Analysis: Separation of Concerns & Complexity Reduction in `ciphers/simple_keyword_cypher.py`
**Task ID**: R23-T030
**Repository**: [S-AI-Projects/TheAlgorithms-Python](https://github.com/S-AI-Projects/TheAlgorithms-Python)
**Target File**: `ciphers/simple_keyword_cypher.py`
**Working Branch**: `student/E26B07F0850/R23-T030` (alias `R23-T030`)

---

## 1. Executive Summary

In `ciphers/simple_keyword_cypher.py`, the `main()` function previously coupled CLI input gathering (`input()`), input normalization, validation branching, error handling (`try ... except KeyError`), cipher map instantiation, and operation dispatch with console output (`print()`). Because cipher operations were intertwined with standard input calls, the end-to-end encryption/decryption workflow could not be unit tested or doctested without mocking interactive terminal inputs.

To resolve this without altering any external behavior:
1. We extracted the core execution and dispatch logic into a pure function `process_cipher(message: str, key: str, option: str) -> str`.
2. `main()` was reduced to pure, linear I/O delegation (`input()` $\rightarrow$ `process_cipher()` $\rightarrow$ `print()`).
3. We added comprehensive doctests to `create_cipher_map` (which previously had 0 doctests).
4. We verified that existing doctests for `remove_duplicates`, `encipher`, and `decipher` remain unchanged and pass.

---

## 2. Cyclomatic Complexity Metrics (Ruff C901 / McCabe)

Cyclomatic complexity measures the number of linearly independent paths through program source code. Running Ruff's McCabe complexity audit (`uvx ruff check --select C901 --config "lint.mccabe.max-complexity=1"`):

| Function | Complexity (Before) | Complexity (After) | Change | Details |
| :--- | :---: | :---: | :---: | :--- |
| **`main()`** | **2** | **1** | **-50%** | Removed `try/except` and dictionary branching; reduced to sequential I/O delegation. |
| **`process_cipher()`** | *N/A (new)* | **2** | *New* | Encapsulates input option normalization, validation (`if`), and dispatch. |
| **`create_cipher_map()`** | **3** | **3** | Unchanged | Retained algorithm structure while adding 7 doctests. |
| **`remove_duplicates()`** | **3** | **3** | Unchanged | Existing doctests untouched and passing. |
| **`encipher()`** | **1** | **1** | Unchanged | Existing doctests untouched and passing. |
| **`decipher()`** | **1** | **1** | Unchanged | Existing doctests untouched and passing. |

---

## 3. Test Coverage & Safety Net Comparison

Using `pytest --cov=ciphers.simple_keyword_cypher`:

| Metric | Before Refactoring | After Refactoring | Change |
| :--- | :---: | :---: | :---: |
| **Total Statements** | 37 | 39 | +2 |
| **Covered Statements** | 25 | 32 | **+7** |
| **Missed Statements** | 12 | 7 | **-5** |
| **Coverage Percentage** | **68%** | **82%** | **+14%** |
| **Total Doctests** | 4 | 15 | **+11 tests** |

### Doctest Distribution
- `remove_duplicates`: 1 test (unchanged)
- `encipher`: 1 test (unchanged)
- `decipher`: 2 tests (unchanged)
- `create_cipher_map`: **7 tests** (was 0: tests key generation, length 26, alphabet mapping, identity mapping)
- `process_cipher`: **4 tests** (new: encipher mode, decipher mode, case insensitivity, invalid option exception)

---

## 4. Architectural & Safety Benefits

1. **Separation of Concerns**:
- `main()` strictly coordinates user interaction (`input()` prompts and displaying results).
- `process_cipher()` handles string normalization, dictionary selection, error enforcement, and cipher pipeline delegation as a pure deterministic function.

2. **100% Backwards Compatibility**:
- The CLI prompts in `main()` remain identical:
- `"Enter message to encode or decode: "`
- `"Enter keyword: "`
- `"Encipher or decipher? E/D:"`
- Exception behavior is preserved (`KeyError("invalid input option")` raised upon invalid option).
- All existing function signatures (`remove_duplicates`, `create_cipher_map`, `encipher`, `decipher`) remain untouched.

3. **Linter & Style Compliance**:
- Passes `uvx ruff check` with 0 warnings.
- Passes `uvx ruff format --check`.
- Passes `python3 scripts/validate_filenames.py`.
1 change: 1 addition & 0 deletions work/R23-T030/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# work/R23-T030 package marker
144 changes: 144 additions & 0 deletions work/R23-T030/test_output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
=== 1. Validate Filenames ===
=== 2. Ruff Check ===
All checks passed!
=== 3. Ruff Format Check ===
1 file already formatted
=== 4. C901 Complexity Check ===
C901 `remove_duplicates` is too complex (3 > 1)
--> ciphers/simple_keyword_cypher.py:1:5
|
1 | def remove_duplicates(key: str) -> str:
| ^^^^^^^^^^^^^^^^^
2 | """
3 | Removes duplicate alphabetic characters in a keyword (letter is ignored after its
|

C901 `create_cipher_map` is too complex (3 > 1)
--> ciphers/simple_keyword_cypher.py:20:5
|
20 | def create_cipher_map(key: str) -> dict[str, str]:
| ^^^^^^^^^^^^^^^^^
21 | """
22 | Returns a cipher map given a keyword.
|

C901 `process_cipher` is too complex (2 > 1)
--> ciphers/simple_keyword_cypher.py:90:5
|
90 | def process_cipher(message: str, key: str, option: str) -> str:
| ^^^^^^^^^^^^^^
91 | """
92 | Enciphers or deciphers a message using a keyword cipher.
|

Found 3 errors.
=== 5. Doctests ===
Trying:
cmap = create_cipher_map('Goodbye!!')
Expecting nothing
ok
Trying:
len(cmap)
Expecting:
26
ok
Trying:
cmap['A']
Expecting:
'G'
ok
Trying:
cmap['B']
Expecting:
'O'
ok
Trying:
cmap['Z']
Expecting:
'Z'
ok
Trying:
identity = create_cipher_map('')
Expecting nothing
ok
Trying:
identity['A']
Expecting:
'A'
ok
Trying:
cipher_map = create_cipher_map('Goodbye!!')
Expecting nothing
ok
Trying:
decipher(encipher('Hello World!!', cipher_map), cipher_map)
Expecting:
'HELLO WORLD!!'
ok
Trying:
encipher('Hello World!!', create_cipher_map('Goodbye!!'))
Expecting:
'CYJJM VMQJB!!'
ok
Trying:
process_cipher('Hello World!!', 'Goodbye!!', 'e')
Expecting:
'CYJJM VMQJB!!'
ok
Trying:
process_cipher('CYJJM VMQJB!!', 'Goodbye!!', 'd')
Expecting:
'HELLO WORLD!!'
ok
Trying:
process_cipher('Hello World!!', 'Goodbye!!', 'E')
Expecting:
'CYJJM VMQJB!!'
ok
Trying:
process_cipher('Hello', 'Key', 'x')
Expecting:
Traceback (most recent call last):
...
KeyError: 'invalid input option'
ok
Trying:
remove_duplicates('Hello World!!')
Expecting:
'Helo Wrd'
ok
2 items had no tests:
simple_keyword_cypher
simple_keyword_cypher.main
5 items passed all tests:
7 tests in simple_keyword_cypher.create_cipher_map
2 tests in simple_keyword_cypher.decipher
1 test in simple_keyword_cypher.encipher
4 tests in simple_keyword_cypher.process_cipher
1 test in simple_keyword_cypher.remove_duplicates
15 tests in 7 items.
15 passed.
Test passed.
=== 6. Pytest Coverage ===
============================= test session starts ==============================
platform darwin -- Python 3.15.2, pytest-9.1.1, pluggy-1.6.0
rootdir: /Users/md.sohail/Documents/snai/TheAlgorithms-Python
configfile: pyproject.toml
plugins: cov-7.1.0, anyio-4.15.1
collected 5 items

ciphers/simple_keyword_cypher.py ..... [100%]

================================ tests coverage ================================
_______________ coverage: platform darwin, python 3.15.2-final-0 _______________

Name Stmts Miss Cover Missing
----------------------------------------------------------------
ciphers/simple_keyword_cypher.py 39 7 82% 125-128, 132-135
----------------------------------------------------------------
TOTAL 39 7 82%
============================= slowest 10 durations =============================
0.01s call ciphers/simple_keyword_cypher.py::ciphers.simple_keyword_cypher.create_cipher_map

(9 durations < 0.005s hidden. Use -vv to show these durations.)
============================== 5 passed in 0.04s ===============================