TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What is the input to the function?
n
.Q: What is the expected output of the function?
Q: What are the specific rules for the output?
i
is divisible by 3
and 5
, the output should be "HulkSmash".i
is divisible by 3
, the output should be "Hulk".i
is divisible by 5
, the output should be "Smash".i
itself as a string.Q: What should the function return if n
is 1?
"1"
.Q: Are there any constraints on the input?
n
is assumed to be a positive integer.-The function hulk_smash()
should take an integer n
and return a 1-indexed string array answer
where:
answer[i] == "HulkSmash"
if i
is divisible by 3 and 5.
answer[i] == "Hulk"
if i
is divisible by 3.
answer[i] == "Smash"
if i
is divisible by 5.
answer[i] == i (as a string)
if none of the above conditions are true.
HAPPY CASE
Input: 3
Expected Output: ["1", "2", "Hulk"]
Input: 5
Expected Output: ["1", "2", "Hulk", "4", "Smash"]
Input: 15
Expected Output: ["1", "2", "Hulk", "4", "Smash", "Hulk", "7", "8", "Hulk", "Smash", "11", "Hulk", "13", "14", "HulkSmash"]
EDGE CASE
Input: 1
Expected Output: ["1"]
Input: 0
Expected Output: []
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate from 1 to n, applying the given rules to determine the string to append to the result list.
1. Initialize an empty list `answer`.
2. Iterate through the range from 1 to `n` (inclusive).
a. If the current number is divisible by 3 and 5, append "HulkSmash" to `answer`.
b. If the current number is divisible by 3, append "Hulk" to `answer`.
c. If the current number is divisible by 5, append "Smash" to `answer`.
d. If none of the above conditions are true, append the current number (as a string) to `answer`.
3. Return `answer`.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def hulk_smash(n):
answer = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
answer.append("HulkSmash")
elif i % 3 == 0:
answer.append("Hulk")
elif i % 5 == 0:
answer.append("Smash")
else:
answer.append(str(i))
return answer