Проблема алгоритма: найти все последовательности, извлеченные из стека - PullRequest
0 голосов
/ 11 июля 2020

Предположим, что в стек имеется список от [1, 2, 3, 4] до pu sh, возможная последовательность извлечения из стека:

1 2 3 4                                                                                  
1 2 4 3                                                                                  
1 3 2 4                                                                                  
1 3 4 2                                                                                  
1 4 3 2                                                                                  
2 1 3 4                                                                                  
2 1 4 3                                                                                  
2 3 1 4                                                                                  
2 3 4 1                                                                                  
2 4 3 1                                                                                  
3 2 1 4                                                                                  
3 2 4 1                                                                                  
3 4 2 1                                                                                  
4 3 2 1

Я нашел версию алгоритма на C ++, она дает правильный вывод:

#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <string.h>
#include <cstdio>
#include <stdlib.h>
#include <cctype>
#include <stack>
#include <queue>
 
using namespace std;
 
 
void printAllOutStackSeq( queue<int> inQueue, int n, stack<int> st, queue<int> out )
{
    if( n <= 0 || ( inQueue.empty() && st.empty() && out.empty() ) )
    {
        return;
    }
 
    if( out.size() == n )
    {
        while( !out.empty() )
        {
            cout << out.front() << ' ';
            out.pop();
        }
 
        cout << endl;
        return;
    }
 
    stack<int> stCopy = st;
    queue<int> outCopy = out;
 
    if( !st.empty() )
    {
        out.push( st.top() );
        st.pop();
        printAllOutStackSeq( inQueue, n, st, out ); 
    }
    
    
    if( !inQueue.empty() )
    {
        stCopy.push( inQueue.front() );
        inQueue.pop();
        printAllOutStackSeq( inQueue, n, stCopy, outCopy ); 
    }
    
    return;
}
 
 
int main()
{
    int ret = 0;
    
    int a[] = { 1, 2, 3, 4 };
    queue<int> inQueue;
 
    for( int i = 0; i < 4; i++ )
    {
        inQueue.push( a[i] );
    }


    int n;
    stack<int> st;
    queue<int> out;
 
    printAllOutStackSeq( inQueue, 4, st, out );
 
    return ret;
}

После того, как я преобразовал C ++ в Python, как показано ниже:

from typing import List
import copy

def print_out_stack_seq(to_push: List[int], n,
                        stack: List[int],
                        popped: List[int]):
    if n <= 0 or (not to_push and not stack and not popped):
        return
    
    if len(popped) == n:
        while len(popped):
            print(popped.pop(0), end=' ')
        print()
        return
    
    stack_copy = copy.copy(stack)
    popped_copy = copy.copy(popped)
    
    if stack:
        popped.append(stack.pop())
        print_out_stack_seq(to_push, n, stack, popped)
        
    if to_push:
        stack_copy.append(to_push.pop(0))
        print_out_stack_seq(to_push, n, stack_copy, popped_copy)
    
    return


to_push = [1, 2, 3, 4]
n = len(to_push)

stack = []
popped = []

print_out_stack_seq(to_push, n, stack, popped)

Он просто напечатает первую строку:

1 2 3 4

I правда не знаю почему, может кто-нибудь мне помочь?

1 Ответ

1 голос
/ 11 июля 2020

В вашей версии C ++ inQueue передается копией в рекурсивных вызовах. Это не так в вашей версии python, где inQueue - это to_pu sh.

Добавление копии to_pu sh перед вызовом print_out_stack_seq, похоже, решит вашу проблему.

from typing import List
import copy

def print_out_stack_seq(to_push: List[int], n,
                        stack: List[int],
                        popped: List[int]):
    if n <= 0 or (not to_push and not stack and not popped):
        return

    if len(popped) == n:
        while len(popped):
            print(popped.pop(0), end=' ')
        print()
        return

    stack_copy = copy.copy(stack)
    popped_copy = copy.copy(popped)

    if stack:
        popped.append(stack.pop())
        print_out_stack_seq(copy.copy(to_push), n, stack, popped)

    if to_push:
        stack_copy.append(to_push.pop(0))
        print_out_stack_seq(copy.copy(to_push), n, stack_copy, popped_copy)

    return


to_push = [1, 2, 3, 4]
n = len(to_push)

stack = []
popped = []

print_out_stack_seq(to_push, n, stack, popped)

Вывод:

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 3 1
3 2 1 4
3 2 4 1
3 4 2 1
4 3 2 1

Однако этот вывод не кажется правильным ответом, поскольку последовательность (4 3 1 2) действительна, но не печатается. Как уже упоминалось, вы печатаете список всех перестановок. В python это можно сделать с помощью следующего кода:

import itertools

to_push = [1, 2, 3, 4]
for p in itertools.permutations(to_push):
    print(p)

Вывод:

(1, 2, 3, 4)
(1, 2, 4, 3)
(1, 3, 2, 4)
(1, 3, 4, 2)
(1, 4, 2, 3)
(1, 4, 3, 2)
(2, 1, 3, 4)
(2, 1, 4, 3)
(2, 3, 1, 4)
(2, 3, 4, 1)
(2, 4, 1, 3)
(2, 4, 3, 1)
(3, 1, 2, 4)
(3, 1, 4, 2)
(3, 2, 1, 4)
(3, 2, 4, 1)
(3, 4, 1, 2)
(3, 4, 2, 1)
(4, 1, 2, 3)
(4, 1, 3, 2)
(4, 2, 1, 3)
(4, 2, 3, 1)
(4, 3, 1, 2)
(4, 3, 2, 1)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...