Problem
Link to the original HackerRank problem
Task
Given an integer,
n
, perform the following conditional actions:
- If
n
is odd, printWeird
- If
n
is even and in the inclusive range of2
to5
, printNot Weird
- If
n
is even and in the inclusive range of6
to20
, printWeird
- If
n
is even and greater than 20, printNot Weird
Input Format
A single line containing a positive integer,
n
.Constraints
1 <= n <= 100
Output Format Print
Weird
if the number is weird. Otherwise, printNot Weird
.Sample Input 0
3
Sample Output 0
Weird
Explanation 0
n = 3
n
is odd and odd numbers are weird, so printWeird
.Sample Input 1
24
Sample Output 1
Not Weird
Explanation 1
n = 24
n > 20
andn
is even, so it is not weird.
Code
Starter
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
Solution
Straightforward
If we translate 1:1
the instructions given in the Problem section, we can quickly write each condition almost as-is in Python:
if __name__ == '__main__':
n = int(input().strip())
# If `n` is odd, print `Weird`
if n % 2 == 1:
print("Weird")
# If `n` is even and in the inclusive range of `2` to `5`, print `Not Weird`
elif (n % 2 == 0) and (2 <= n <= 5):
print("Not Weird")
# If `n` is even and in the inclusive range of `6` to `20`, print `Weird`
elif (n % 2 == 0) and (6 <= n <= 20):
print("Weird")
# If `n` is even and greater than 20, print `Not Weird`
else: # n % 2 == 0 and n > 20:
print("Not Weird")
One-liner Ternary
While the previous straightforward version works just fine, we can also decide to group the conditions by type of outcome, respectively, Weird
and Not Weird
, .i.e.,
Weird
:- Separate Conditions:
n % 2 == 1
, or(n % 2 == 0) and (6 <= n <= 20)
,
- Merged Conditions, note that if above
n
is not odd, it means it is then even, i.e.,n % 2 == 0
, from which we can derive:(n % 2 == 1) or ((n % 2 == 0) and (6 <= n <= 20))
and simplify to below:(n % 2 == 1) or (6 <= n <= 20)
- Separate Conditions:
Not Weird
:- Separate Conditions:
(n % 2 == 0) and (2 <= n <= 5)
, or(n % 2 == 0) and (n > 20)
- Merged Conditions, like what we did in the
Weird
Merged Conditions branch above, we can also factor out the fact that both conditions in theNot Weird
requiren
to be even (i.e.,n % 2 == 0
):(n % 2 == 0) and (2 <= n <= 5 or n > 20)
- Separate Conditions:
We can effectively have an implementation which is then a lot shorter, but it hinders mapping the original intent (you can think of them as specifications) with the actual implementation:
if __name__ == '__main__':
n = int(input().strip())
print("Weird" if (n % 2 == 1) or (6 <= n <= 20) else "Not Weird")
or conversely:
if __name__ == '__main__':
n = int(input().strip())
print("Not Weird" if (n % 2 == 0) and ((2 <= n <= 5) or (n > 20)) else "Weird")
Key Takeways
- Found it a bit of a shame that the PEP 656 Python Structural Pattern Matching brought in Python 3.10 could not be used to deliver a better