-
Notifications
You must be signed in to change notification settings - Fork 243
Shuffle
TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 5 mins
- 🛠️ Topics: Lists, Iteration
Understand what the interviewer is asking for by using test cases and questions about the problem.
-
Q: What is the function's input?
- A: The input is a list
cards
of2n
elements in the form[x1, x2, ..., xn, y1, y2, ..., yn]
.
- A: The input is a list
-
Q: What should the function return?
- A: The function should return a list where the elements are shuffled to form
[x1, y1, x2, y2, ..., xn, yn]
.
- A: The function should return a list where the elements are shuffled to form
-
Q: Can the input list have an odd number of elements?
- A: No, the problem statement specifies that the list will have
2n
elements, so the number of elements will always be even.
- A: No, the problem statement specifies that the list will have
-
Q: Is it acceptable to create a new list to store the shuffled elements?
- A: Yes, the problem does not restrict the creation of a new list.
-
The function
shuffle()
should take a list of 2n elements in the format[x1, x2, ..., xn, y1, y2, ..., yn]
and return a new list in the format[x1, y1, x2, y2, ..., xn, yn]
.
HAPPY CASE
Input: ['Joker', 'Queen', 2, 3, 'Ace', 7]
Expected Output: ['Joker', 3, 'Queen', 'Ace', 2, 7]
Input: [9, 2, 3, 'Joker', 'Joker', 3, 2, 9]
Expected Output: [9, 'Joker', 2, 3, 3, 2, 'Joker', 9]
EDGE CASE
Input: [10, 10, 2, 2]
Expected Output: [10, 2, 10, 2]
Input: [] (empty list)
Expected Output: []
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Calculate the midpoint of the list, then iterate through the first half and append elements from both halves to a new list in the specified order.
1. Define the function `shuffle(cards)`.
2. Calculate `n` as half the length of the list `cards`.
3. Initialize an empty list `shuffled` to hold the result.
4. Iterate over the range from 0 to `n - 1`.
5. For each index `i`, append `cards[i]` and `cards[i + n]` to the `shuffled` list.
6. Return the `shuffled` list.
- Forgetting to calculate the midpoint correctly.
- Attempting to access indices that are out of range.
Implement the code to solve the algorithm.
def shuffle(cards):
n = len(cards) // 2
shuffled = []
for i in range(n):
shuffled.append(cards[i])
shuffled.append(cards[i + n])
return shuffled