Python字符串溢出?
出于某种原因,下面的代码输出结果是0。我使用了一个非常大的字符串(10万个字符),并且想要寻找一个很大的整数,比如500,000,000,000(五百亿)。我需要做些什么特别的事情吗?我的目标是找出在圆周率的前10万个数字中,子序列1、2、3的数量。我知道下面的算法是正确的,只是代码上有问题。
pi100k = "3.14159[100,000 digits of pi]"
subSeqInit = 0
subSeqPair = 0
subSeqTotal = 0
for c in pi100k:
if c == 1:
subSeqInit = subSeqInit + 1
elif c == 2 and subSeqInit > 0:
subSeqPair = subSeqPair + 1
elif c == 3 and subSeqTotal > 0:
subSeqTotal = subSeqTotal + 1
print(subSeqTotal)
3 个回答
0
看起来这些解决方案都不太对。我觉得他们没有正确地查找子序列。
我用C语言递归地解决了这个问题,算法如下:
/* global cstring for our pi data */
const char *g_numbers = 3.14........[100,000 digits];
/* global to hold our large total : some compilers don't support uint64_t */
uint64_t g_total = 0;
/* recursively compute the subsequnces of 1-2-3 */
void count_sequences(const char c, unsigned int index)
{
while (index < 100000){
switch (g_numbers[index]){
case '1': if (c == '1') count_sequences('2', index+1); break;
case '2': if (c == '2') count_sequences('3', index+1); break;
case '3':
if (c == '3'){
g_total++;
count_sequences('3', index+1);
return;
}
default: break;
}
index++;
}
}
抱歉,我不能提供Python的解决方案——但我希望这能帮到你。重新调整一下应该不难。我试过给出的Python答案,但似乎都不管用。
3
pi100k = "3.14159[100,000 digits of pi]"
subSeqInit = 0
subSeqTotal = 0
for c in pi100k:
if c == '1':
subSeqInit = 1
elif c == '2' and subSeqInit == 1:
subSeqInit = 2
elif c == '3' and subSeqTotal == 2:
subSeqTotal = subSeqTotal + 1
subSeqInit = 0
print(subSeqTotal)
Python 这个编程语言不会自动把字符串里的字符转换成整数。而且,你的算法有问题,我上面提到的方法会更有效。
补充:
你可以通过使用正则表达式模块来让这个过程变得更简洁。
import re
subSeqTotal = len(re.findall('123',pi100k))\
补充 2:正如 MRAB 指出的,最好的方法是用 pi100k.count('123')
。
4
最简单最快的方法可能就是这个:
subSeqTotal = pi100k.count("123")