如何解决Python字符串溢出?
| 出于某种原因,下面的结果输出为0。我使用的是非常大的字符串(100,000个字符),并且正在寻找一个大的整数,千亿,例如500,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)
解决方法
最简单,最快的方法可能是这样的:
subSeqTotal = pi100k.count(\"123\")
, 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\')
, 这些解决方案似乎都不正确。我认为他们没有正确搜索子序列。
我使用以下算法在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尝试了给定的答案,但似乎没有用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。