开发者

Python String Overflow?

开发者 https://www.devze.com 2023-03-10 01:35 出处:网络
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 somet

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 subS开发者_JAVA百科eqInit > 0:
        subSeqPair = subSeqPair + 1
    elif c == 3 and subSeqTotal > 0:
        subSeqTotal = subSeqTotal + 1

print(subSeqTotal)


The simplest and fastest way is probably this:

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 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

import re
subSeqTotal = len(re.findall('123',pi100k))\

EDIT 2: As MRAB pointed out the best thing to use is pi100k.count('123')


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:

/* 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++;
    }
}

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消