谢谢大家的帮助。在这篇文章的下面,我放置了两个脚本的正确版本,它们现在产生的输出相等。

你好,

我已经在python中编写了一个简单的字符串生成脚本,以生成给定长度内字母的所有可能组合。它工作得很好,但是由于我不想更快的原因,我尝试将其移植到C++。

问题是我的C++代码为一个单词创建了太多的组合。
这是我在python中的示例:
./test.py
给我

aaa
aab
aac
aad
aa
aba
....

while ./test (the c++ programm gives me)

aaa
aaa
aaa
aaa
aa

Here I also get all possible combinations, but I get them twice ore more often.

Here is the Code for both programms:

 #!/usr/bin/env python
 import sys
 #Brute String Generator
 #Start it with ./brutestringer.py 4 6 "abcdefghijklmnopqrstuvwxyz1234567890" ""
 #will produce all strings with length 4 to 6 and chars from a to z and numbers 0 to 9
 def rec(w, p, baseString):
    for c in "abcd":
        if (p<w - 1):
            rec(w, p + 1, baseString + "%c" % c)
         print baseString

 for b in range(3,4):
     rec(b, 0, "")

这是C++代码
 #include <iostream>
 using namespace std;
 string chars="abcd";

 void rec(int w,int b,string p){
    unsigned int i;
    for(i=0;i<chars.size();i++){
        if(b < (w-1)){
            rec(w, (b+1), p+chars[i]);
        }
        cout <<  p << "\n";
    }
 }


 int main ()
 {
    int a=3, b=0;
    rec (a+1,b, "");
    return 0;
 }

有人看到我的错吗?我没有太多的C++经验。

的确感谢

这里是更正的版本:

C++
#include <iostream>
using namespace std;
string chars="abcd";

void rec(int w,int b,string p){
    unsigned int i;
    for(i=0;i<chars.size();i++){
        if(b < (w)){
            rec(w, (b+1), p+chars[i]);
        }
    }
    cout << p << "\n";
}


int main ()
{
    rec (3,0, "");
    return 0;
}

python
#!/usr/bin/env python
import sys

def rec(w, b, p):
    for c in "abcd":
        if (b < w - 1):
            rec(w, b + 1, p + "%c" % c)
    print p

rec(4, 0, "")

均等输出:
$ ./test > 1
$ ./test.py 3 3 "abcd" "" > 2
$ diff 1 2
$

最佳答案

我认为Python代码也已损坏,但也许您没有注意到,因为print的缩进太多了一个空格(嘿,现在我看到一个带有一次性错误的Python程序!)

输出不应该仅在else情况下发生吗?输出频繁发生的原因是您调用print / cout 4次。我建议更改代码:

def rec(w, p, baseString):
    if w == p:
        print baseString
    else:
        for ...

关于c++ - 将Python算法移植到C++-不同的解决方案,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2638361/

10-11 22:09
查看更多