c++ - 将 Python 算法移植到 C++ - 不同的解决方案

标签 c++ python

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


你好,

我在 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 的情况下吗?而输出更频繁发生的原因是你调用了 4 次 print/cout。我建议更改代码:

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

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

相关文章:

c++ - 使用只有一名成员的 union 的目的是什么?

Python - 在运行相同应用程序的网络上获取计算机的 IP 地址和主机名

python - "An error occurred initiating application server. Failed to launch application server"适用于 Windows 7 上的 PgAdmin 4

c++ - C++ 中的快速差异实现以获取大文件中的行差异量

c++ - C++平台游戏中的寻路

c++ - 为什么 cudaMemcpy 花费这么多时间?

python - 导入错误 : No module named cv2 with Python 2. 7

python - mysqldb 数据库主机未被接受?

python - 如何对从 beautifulsoup 抓取的 html 中的列表元素进行排序?

c++ - 使用 uncaught_exception 处理错误情况