寻找最长的串数字的顺序一个字符串在Python字符串、顺序、最长、数字

2023-09-11 23:24:33 作者:诺言。一场华丽的谎言罢了

我有一个字符串数以千计一些在里面。我需要经过串并找到最长的一组是按照数字顺序字符。例如:

I have a string with thousands of number in it. I need to go through the string and find the longest set of characters that are in numerical order. For example:

string = '1223123341223455'

在字符串中的数字顺序字符的字符串,最长的是1223455,这是7个字符长。下面是我目前所面对的一个例子:

The longest string of characters in that string in numerical order is 1223455 and it is 7 characters long. Here is an example of what I have at the moment:

r=r2=''
a=b=0
 while a < len(string)+1:
    if string[a] <= string[b]:
        r += string[a]
    else:
        if len(r) < len(r2):
            r = r2
    a += 1
    b += 1

通过这个它告诉我,该字符串索引超出范围就行了:

With this it tells me that the string index is out of range on the line:

if string[a] <= string[b]

下面是我的逻辑:检查是否所述第一数目小于或等于所述第二数量。如果是,这两个数字是数字顺序。补充一下,第一个号码为空字符串。继续这样做,直到你碰到一个点,当第一个数字大于第二个数字。在达到这一点,节省你有什么作为一个字符串,并继续你离开的地方,但这次串连你积累到一个不同的字符串的数量。之后,你有两个数字字符串,比较两个走的较高者。继续下去,直到你完成处理字符串。我希望这是有道理的,一种很难解释的。

Here is my logic: Check to see if the first number is less than or equal to the second number. If it is, those two numbers are in numerical order. Add that first number to an empty string. Keep doing this until you run into a point when the first number is greater than the second number. After this point is reached, save what you have as a string and continue where you left off, except this time concatenate the number you accumulate to a different string. After you have two strings of numbers, compare the two and take the higher one. Continue this until you are done processing the string. I hope this makes sense, kind of hard to explain.

推荐答案

字符串都为0。因此,如果您尝试访问索引 some_str [LEN(some_str)] 您将获得 IndexError ,因为该字符串的最高指数 LEN(some_str) - 1 。改变你的,而条件:而&LT; LEN(MyString的):。此外,你不应该使用字符串作为一个变量,因为它可能会掩盖蟒蛇字符串模块的名称。

Strings are indexed at 0. So if you try to access some_str[len(some_str)] you will get an IndexError because the highest index of that string is len(some_str) - 1. Change your while condition to: while a < len(myString):. Also, you shouldn't use string as a variable, as it may overshadow the python string module name.