TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
cards
of 2n
elements in the form [x1, x2, ..., xn, y1, y2, ..., yn]
.[x1, y1, x2, y2, ..., xn, yn]
.2n
elements, so the number of elements will always be even.Q: Is it acceptable to create a new list to store the shuffled elements?
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.
⚠️ Common Mistakes
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