由于某些原因,下面的结果输出为0。我使用一个非常大的字符串(100,000个字符),并寻找一个千亿级的大整数,例如500,000,000,000。有什么特别的需要我做的吗?目标是找到pi的前100,000位中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)发布于 2011-06-01 10:02:32
最简单、最快的方法可能是:
subSeqTotal = pi100k.count("123")发布于 2011-06-01 09:40:42
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')。
发布于 2011-12-28 11:06:57
这些解决方案似乎都不正确。我不认为他们搜索子序列是正确的。
我用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中尝试了给定的答案,它们似乎不起作用。
https://stackoverflow.com/questions/6195378
复制相似问题