Skip to content

Fabric Stacks

Raymond Chen edited this page Sep 1, 2024 · 1 revision

Unit 4 Session 1 Advanced (Click for link to problem statements)

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q: What is the structure of the input?

    • A: The input is a list of tuples, where each tuple contains a fabric name (string) and its eco-friendliness rating (integer).
  • Q: What is the output?

    • A: The output is a list of fabric names in the order they would be retrieved from the stack, starting with the least eco-friendly fabric.
  • Q: How should the fabrics be organized?

    • A: The fabrics should be organized in a stack such that the least eco-friendly fabric is at the top of the stack (and thus retrieved first).
  • Q: Are there any constraints on the input, such as the fabrics needing to be sorted?

    • A: The fabrics do not need to be sorted initially; the function will handle sorting by eco-friendliness rating.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Sort the fabrics by their eco-friendliness rating, then push the fabric names onto a stack. Finally, pop the fabrics from the stack to retrieve them in the desired order.

1) Sort the `fabrics` list by the eco-friendliness rating in ascending order. 2) Initialize an empty list called `stack`. 3) For each `fabric` in `fabrics`: a) Push the `fabric[0]` (fabric name) onto the `stack`. 4) Initialize an empty list called `organized_fabrics`. 5) While the `stack` is not empty: a) Pop the top element from `stack` and append it to `organized_fabrics`. 6) Return the `organized_fabrics` list. **⚠️ Common Mistakes** - Forgetting to correctly sort the fabrics by their eco-friendliness rating. - Not correctly implementing the stack operations (push and pop).

I-mplement

def organize_fabrics(fabrics): fabrics.sort(key=lambda x: x[1]) # Sort fabrics by eco-friendliness rating stack = [] for fabric in fabrics: stack.append(fabric[0]) # Push fabric names onto the stack organized_fabrics = [] while stack: organized_fabrics.append(stack.pop()) # Pop fabrics from the stack in reverse order return organized_fabrics
Clone this wiki locally