Python字符串溢出?
问题描述:
由于某种原因,下面的结果输出为0.我使用了一个非常大的字符串(100,000个字符),并寻找一个大数字,数百亿,例如500,000,000,000。我需要做些什么特别的事吗?目标是在pi的前100,000个数字中找到1,2,3的子序列的数量。我知道下面的算法是正确的。这只是不“代码正确”。Python字符串溢出?
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)
答
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')
答
最简单和最快的方式可能是这样的:
subSeqTotal = pi100k.count("123")
+0
LOL我希望我想有时我会用'count'来让事情变得太复杂。 – GWW 2011-06-01 03:03:16
答
它出现这些解决方案都不是正确的。我不认为他们正确地搜索了子序列。
我用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 solution--但我希望这会有所帮助。重新工作不应该太难。我试着在Python中给出的答案,他们似乎没有工作。
也许你应该重新检查你的算法。我不明白subSeqTotal可能会如何从其初始值0改变。 – Ralph 2011-06-01 01:46:26