Python 字符串溢出?
由于某种原因,下面的结果是 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)
For some reason, the below results in an output of 0. I'm using a very large string (100,000 characters), and looking for a large integer, in the hundred billions, e.g 500,000,000,000. Is there something special I need to do? The goal is to find the number of sub-sequences of 1,2,3 in the first 100,000 digits of pi. I know the below is algorithmically correct. It's just not "code-correct."
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单、最快的方法可能是这样的:
The simplest and fastest way is probably this:
Python 不会将字符串字符隐式转换为整数。此外,你的算法并不健全,我上面的算法会更好。
编辑:
您可以通过使用正则表达式模块来缩短此时间
编辑2:正如 MRAB 指出的,最好使用的是
pi100k.count('123')
Python does not implicitly convert string characters to integers. Furthermore, your algorithm is not sound, what I have above will work better.
EDIT:
You could make this much shorter by using the regular expression module
EDIT 2: As MRAB pointed out the best thing to use is
pi100k.count('123')
看来这些解决方案都不正确。我认为他们没有正确搜索子序列。
我用 C 语言递归地解决了这个问题,使用了这个算法:
抱歉,我无法给出 Python 解决方案——但我希望这会有所帮助。重新工作应该不会太难。我在Python中尝试了给出的答案,但它们似乎不起作用。
It appears none of these solutions are correct. I don't think they search for the sub-sequence correctly.
I solved it recursively in C, with this algorithm:
Sorry I can't hand out the Python solution-- but I hope this helps. It shouldn't be too hard to re-work. I tried the given answers in Python and they didn't seem to work.