问题描述
我有一个包含数千个数字的字符串。我需要遍历字符串并找到按数字顺序排列的最长字符集。例如:
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
。将您的 while
条件更改为: while< len(myString):
。另外,您不应该使用 string
作为变量,因为它可能使python string
模块名称黯然失色。
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.
这篇关于在Python字符串中按数字顺序查找最长的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!