Scenario: Employee Bonus Calculator
Imagine you're working for a company that wants to calculate employee bonuses based on their
performance and years of service. The company has the following rules:
1. Employees with a performance score above 80 get a bonus.
2.
The bonus is calculated as:
○ 10% of their salary if they've worked less than 5 years.
○
15% of their salary if they've worked 5-10 years.
○
20% of their salary if they've worked more than 10 years.
3.
4.
If the performance score is below 80, they get no bonus.
You're given a list of employee data in the form of dictionaries, and your task is to write a Python
function to calculate the bonuses and return a report.
Example Input:
python
WrapCopy
employees = [
{"name": "Alice", "salary": 60000, "performance_score": 85,
"years_of_service": 3},
{"name": "Bob", "salary": 75000, "performance_score": 92,
"years_of_service": 7},
{"name": "Charlie", "salary": 50000, "performance_score": 78,
"years_of_service": 12},
{"name": "Diana", "salary": 80000, "performance_score": 95,
"years_of_service": 15}
]
Expected Output:
A list of dictionaries showing each employee's name, bonus amount, and a message explaining
the result.
Solution
Here’s a Python script that solves this scenario:
python
WrapCopy
def calculate_bonus(employees):
report = []
for employee in employees:
name = employee["name"]
salary = employee["salary"]
score = employee["performance_score"]
years = employee["years_of_service"]
# Check if eligible for bonus
if score > 80:
# Determine bonus percentage based on years of service
if years < 5:
bonus_percentage = 0.10
elif 5 <= years <= 10:
bonus_percentage = 0.15
else:
bonus_percentage = 0.20
# Calculate bonus
bonus = salary * bonus_percentage
message = f"{name} gets a bonus of ${bonus:.2f} based on {years}
years of service."
else:
bonus = 0
message = f"{name} is not eligible for a bonus due to a
performance score of {score}."
# Add result to report
report.append({"name": name, "bonus": bonus, "message": message})
return report
# Test data
employees = [
{"name": "Alice", "salary": 60000, "performance_score": 85,
"years_of_service": 3},
{"name": "Bob", "salary": 75000, "performance_score": 92,
"years_of_service": 7},
{"name": "Charlie", "salary": 50000, "performance_score": 78,
"years_of_service": 12},
{"name": "Diana", "salary": 80000, "performance_score": 95,
"years_of_service": 15}
]
# Run the function and display results
results = calculate_bonus(employees)
for result in results:
print(result["message"])
Output
text
WrapCopy
Alice gets a bonus of $6000.00 based on 3 years of service.
Bob gets a bonus of $11250.00 based on 7 years of service.
Charlie is not eligible for a bonus due to a performance score of 78.
Diana gets a bonus of $16000.00 based on 15 years of service.
Why This is Helpful for an Interview
1. Problem-Solving: It shows you can break down a real-world problem into logical steps.
2.
Python Basics: Uses dictionaries, conditionals (if-elif-else), loops, and string formatting.
3.
Clarity: The code is readable and well-structured, which interviewers value.
4.
Edge Cases: You can discuss how to handle edge cases (e.g., negative salaries,
missing data) if asked.
5.
Scalability: You can extend this by adding features like input validation or sorting the
report.
How to Use This in an Interview
● Explain Your Approach: Start by walking through the problem (e.g., "First, I’ll check the
performance score, then calculate the bonus based on years of service").
●
Code Step-by-Step: Write the solution incrementally while explaining your thought
process.
●
Discuss Improvements: Mention how you could add error handling (e.g., try-except for
invalid inputs) or optimize it for larger datasets.
Scenario: Employee Bonus Calculator
Imagine you're working for a company that wants to calculate employee bonuses based on their
performance and years of service. The company has the following rules:
1. Employees with a performance score above 80 get a bonus.
2.
The bonus is calculated as:
○ 10% of their salary if they've worked less than 5 years.
○
15% of their salary if they've worked 5-10 years.
○
20% of their salary if they've worked more than 10 years.
3.
4.
If the performance score is below 80, they get no bonus.
You're given a list of employee data in the form of dictionaries, and your task is to write a Python
function to calculate the bonuses and return a report.
Example Input:
python
WrapCopy
employees = [
{"name": "Alice", "salary": 60000, "performance_score": 85,
"years_of_service": 3},
{"name": "Bob", "salary": 75000, "performance_score": 92,
"years_of_service": 7},
{"name": "Charlie", "salary": 50000, "performance_score": 78,
"years_of_service": 12},
{"name": "Diana", "salary": 80000, "performance_score": 95,
"years_of_service": 15}
]
Expected Output:
A list of dictionaries showing each employee's name, bonus amount, and a message explaining
the result.
Solution
Here’s a Python script that solves this scenario:
python
WrapCopy
def calculate_bonus(employees):
report = []
for employee in employees:
name = employee["name"]
salary = employee["salary"]
score = employee["performance_score"]
years = employee["years_of_service"]
# Check if eligible for bonus
if score > 80:
# Determine bonus percentage based on years of service
if years < 5:
bonus_percentage = 0.10
elif 5 <= years <= 10:
bonus_percentage = 0.15
else:
bonus_percentage = 0.20
# Calculate bonus
bonus = salary * bonus_percentage
message = f"{name} gets a bonus of ${bonus:.2f} based on {years}
years of service."
else:
bonus = 0
message = f"{name} is not eligible for a bonus due to a
performance score of {score}."
# Add result to report
report.append({"name": name, "bonus": bonus, "message": message})
return report
# Test data
employees = [
{"name": "Alice", "salary": 60000, "performance_score": 85,
"years_of_service": 3},
{"name": "Bob", "salary": 75000, "performance_score": 92,
"years_of_service": 7},
{"name": "Charlie", "salary": 50000, "performance_score": 78,
"years_of_service": 12},
{"name": "Diana", "salary": 80000, "performance_score": 95,
"years_of_service": 15}
]
# Run the function and display results
results = calculate_bonus(employees)
for result in results:
print(result["message"])
Output
text
WrapCopy
Alice gets a bonus of $6000.00 based on 3 years of service.
Bob gets a bonus of $11250.00 based on 7 years of service.
Charlie is not eligible for a bonus due to a performance score of 78.
Diana gets a bonus of $16000.00 based on 15 years of service.
Why This is Helpful for an Interview
1. Problem-Solving: It shows you can break down a real-world problem into logical steps.
2.
Python Basics: Uses dictionaries, conditionals (if-elif-else), loops, and string formatting.
3.
Clarity: The code is readable and well-structured, which interviewers value.
4.
Edge Cases: You can discuss how to handle edge cases (e.g., negative salaries,
missing data) if asked.
5.
Scalability: You can extend this by adding features like input validation or sorting the
report.
How to Use This in an Interview
● Explain Your Approach: Start by walking through the problem (e.g., "First, I’ll check the
performance score, then calculate the bonus based on years of service").
●
Code Step-by-Step: Write the solution incrementally while explaining your thought
process.
●
Discuss Improvements: Mention how you could add error handling (e.g., try-except for
invalid inputs) or optimize it for larger datasets.
Scenario 1: Word Frequency Counter
Problem
You're tasked with analyzing customer feedback for a product. The company wants to know the
most frequently used words in a list of feedback comments, excluding common words like "the,"
"and," or "is." Write a Python function that takes a list of feedback strings and a list of words to
ignore, then returns a dictionary with the top 3 most frequent words and their counts.
Example Input:
python
WrapCopy
feedback = [
"The app is fast and user-friendly",
"Fast loading and great design",
"The design is sleek but slow at times",
"User-friendly app with fast performance"
]
ignore_words = ["the", "is", "and", "at", "with"]
Expected Output:
A dictionary like:
python
WrapCopy
{
"fast": 3,
"user-friendly": 2,
"design": 2
}
Solution:
python
WrapCopy
def word_frequency(feedback, ignore_words):
# Combine all feedback into one string and convert to lowercase
combined_text = " ".join(feedback).lower()
# Replace punctuation with spaces and split into words
for char in ".,-!?":
combined_text = combined_text.replace(char, " ")
words = combined_text.split()
# Count word frequencies
word_count = {}
for word in words:
if word not in ignore_words:
word_count[word] = word_count.get(word, 0) + 1
# Sort by frequency (descending) and then alphabetically
sorted_words = sorted(word_count.items(), key=lambda x: (-x[1], x[0]))
# Return top 3 as a dictionary
return dict(sorted_words[:3])
# Test data
feedback = [
"The app is fast and user-friendly",
"Fast loading and great design",
"The design is sleek but slow at times",
"User-friendly app with fast performance"
]
ignore_words = ["the", "is", "and", "at", "with"]
# Run and display result
result = word_frequency(feedback, ignore_words)
print(result)
Output:
text
WrapCopy
{'fast': 3, 'design': 2, 'user-friendly': 2}
Interview Value:
● Skills Demonstrated: String manipulation, dictionary usage, sorting with custom keys
(lambda), and filtering.
●
Discussion Points: You could talk about handling edge cases (e.g., empty feedback),
optimizing for large datasets (e.g., using collections.Counter), or adding regex for better
text cleaning.
●
Relevance: Text analysis is common in data processing or NLP tasks.
Scenario 2: Recursive File System Size Calculator
Problem
Imagine you're building a tool to analyze disk usage. You're given a nested directory structure
represented as a dictionary, where each key is a folder or file name, and values are either
nested dictionaries (for folders) or integers (file sizes in KB). Write a recursive Python function to
calculate the total size of the directory.
Example Input:
python
WrapCopy
directory = {
"root": {
"folder1": {
"file1": 100,
"file2": 200
},
"folder2": {
"file3": 300
},
"file4": 50
}
Expected Output:
text
WrapCopy
650 # Total size in KB (100 + 200 + 300 + 50)
Solution:
python
WrapCopy
def calculate_directory_size(directory):
total_size = 0
# Iterate through each item in the dictionary
for item, value in directory.items():
if isinstance(value, dict):
# If it's a folder (dictionary), recursively calculate its size
total_size += calculate_directory_size(value)
elif isinstance(value, int):
# If it's a file (integer), add its size
total_size += value
return total_size
# Test data
directory = {
"root": {
"folder1": {
"file1": 100,
"file2": 200
},
"folder2": {
"file3": 300
},
"file4": 50
}
# Run and display result
result = calculate_directory_size(directory)
print(f"Total size: {result} KB")
Output:
text
WrapCopy
Total size: 650 KB
Interview Value:
● Skills Demonstrated: Recursion, type checking (isinstance), and working with nested
data structures.
●
Discussion Points: You could discuss handling invalid inputs (e.g., negative sizes),
adding error handling, or optimizing for performance with memoization if asked.
●
Relevance: Recursive problems are a staple in coding interviews, and this mimics
real-world file system traversal.
How to Leverage These in an Interview
1. Walk Through Logic: Explain your approach before coding (e.g., "For the word
frequency, I’ll clean the text, count words, and sort them").
2.
Show Adaptability: Be ready to modify your solution if the interviewer changes
requirements (e.g., "Return top 5 words instead" or "Add subfolder names to the
output").
3.
Highlight Python Features: Point out efficient tools like dict.get(), sorted() with key, or
recursion, showing your familiarity with the language.