Python elements of the stack returned are the same as the original stack in the opposite order

StackOverflow https://stackoverflow.com/questions/22429546

  •  15-06-2023
  •  | 
  •  

Question

You will write the Python function reverse. It will take a single argument, a stack, and return a stack.

The elements of the stack returned are the same as the original stack but in the opposite order. The reverse function should only use the stack operations and may not mutate the original stack.

I am thinking of this:

def reverse(stack):
    return stack

but, I just want to know what does the question mean by:

elements of the stack returned are the same as the original stack but in the opposite order. The reverse function should only use the stack operations and may not mutate the original stack.

Can somebody explain it to me please?

Was it helpful?

Solution

[T]he part where it says "elements of the stack returned are the same as the original stack but in the opposite order". My question is which elements does the statement mean?

By way of example, consider a stack that contains the numbers 1, 3, 2, 5, 9 and 11, in that order. When applied to this stack, the function would return another stack. This other stack would contain the numbers 11, 9, 5, 2, 3 and 1.

The bit about mutating is indeed confusing: I guess they mean that at the end the original stack must be as it was at the start; I imagine you are allowed to modify it in the interim (as long as you put everything back where it was).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top