algorithm to remove repeated elements in python

Asked

Viewed 190 times

-2

Write an algorithm that eliminates all elements equal to a certain value X from a stack, keeping the remaining values in the stack in the same relative order they are in. Note: Only destacking and stacking operations are permitted. Tip: Uses a Q auxiliary stack to solve this problem.

I managed to do it, but they ask with stacking and de-stacking

  • 1

    Hello, put the code in the question for users to analyze

1 answer

4

First, you need to remember that a stack has the English LIFO behavior last input, first output; i.e. the last one in will be the first one out. So, when you pop elements of P and stack them into Q, the order in Q will be reversed, so you need to reverse the order of Q by turning the elements to P.

The algorithm is basically this:

  1. As long as P is not empty:
    • Pops an element of P;
    • If element equals X, go back to step 1;
    • Stack element in Q;
  2. While Q is not empty:
    • Pops an element of Q;
    • Stack element in P;

That is to say:

P: Pilha<elementos de P>
Q: Pilha<vazia>

Enquanto P não estiver vazia faça:
    Elemento = P.desempilha()
    Se Elemento é diferente de X:
        Q.empilha(Elemento)

Enquanto Q não estiver vazia faça:
    Elemento = Q.desempilha()
    P.empilha(Elemento)

At the end, stack P will be the original stack, in the same order, without elements equal to X.

If it’s in Python, a lot can be simplified during code implementation.

  • this"#can create a class with the def() tabm functions? I think

Browser other questions tagged

You are not signed in. Login or sign up in order to post.