S1Q3 · Shuffle Digits¶
⚡ Quick Reference
Function: shuffle_digits(num: int) -> int
Core idea: Convert to string, pick digits by position in the required order, convert back to int.
Key rules:
- Positions are 0-indexed: s[0] = 1st digit, s[1] = 2nd, etc.
- New order is digit 2, digit 4, digit 1, digit 3 → indices [1, 3, 0, 2]
- Return an int, not a string
Problem Statement¶
Problem
Write a function shuffle_digits(num) that takes a 4-digit positive integer and rearranges its digits in the order 2-4-1-3: the 2nd digit becomes 1st, 4th becomes 2nd, 1st becomes 3rd, 3rd becomes 4th.
Examples:
shuffle_digits(1234)
2413
shuffle_digits(2413)
4321
Understanding the problem¶
The shuffle maps each position to a new one. Using 1-based positions as stated in the problem, then converting to 0-based string indices:
| New position | Takes digit from | 1-based pos | 0-based index |
|---|---|---|---|
| 1st | 2nd digit | 2 | s[1] |
| 2nd | 4th digit | 4 | s[3] |
| 3rd | 1st digit | 1 | s[0] |
| 4th | 3rd digit | 3 | s[2] |
Trace with 1234:
| Digit | d1=1 |
d2=2 |
d3=3 |
d4=4 |
|---|---|---|---|---|
| New order | pos 3 | pos 1 | pos 4 | pos 2 |
| Result | 2 |
4 |
1 |
3 |
Output: 2413 ✅
The four examples form a cycle
1234 → 2413 → 4321 → 3142 → 1234. Applying the shuffle four times brings you back to the original number. This is a useful self-check: call the function four times on any input and verify you get the original back.
Solution approaches¶
Key takeaways¶
String indexing for digit access
Converting to a string with str(num) makes each digit individually addressable by index. This is simpler than arithmetic extraction (// 10, % 10) when rearranging digits in arbitrary order.
1-based to 0-based index translation
Problem statements describe positions starting from 1 ("2nd digit"), but Python strings are 0-indexed. Subtract 1: position 2 → s[1], position 4 → s[3]. Always do this translation explicitly before writing the code.
String concatenation then int()
Build the result as a string by concatenating individual character digits, then wrap in int() to return the correct type. Leading zeros (e.g. if the 2nd digit is 0) are automatically dropped by int().