【发布时间】:2010-04-14 14:49:32
【问题描述】:
感谢大家的帮助。在这篇文章的下方,我放置了两个脚本的更正版本,它们现在产生了相同的输出。
你好,
我在 python 中编写了一个粗略的字符串生成脚本来生成给定长度内的所有可能的字母组合。它工作得很好,但出于我不想让它更快的原因,我尝试将它移植到 C++。
问题是我的 C++ 代码为一个单词创建了太多的组合。 这是我在 python 中的示例:
./test.py
给我
aaa aab aac 广告 啊 阿坝 ....
而./test(c++ 程序给了我)
aaa 啊啊啊 啊啊啊 啊啊啊 啊
在这里我也得到了所有可能的组合,但我得到它们的频率更高。
这是两个程序的代码:
#!/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
$
【问题讨论】: