我有一个包含数千个数字的字符串。我需要浏览字符串并找到按数字顺序排列的最长字符集。例如:
string = '1223123341223455'
该字符串中按字母顺序排列的最长字符串数为1223455,长度为7个字符。以下是我目前所拥有的一个例子:
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
有了它,它告诉我字符串索引超出了行的范围:
if string[a] <= string[b]
这是我的逻辑:检查第一个数字是否小于或等于第二个数字。如果是,则这两个数字按数字顺序排列。将第一个数字添加到空字符串。继续这样做,直到遇到第一个数字大于第二个数字的点。达到此点后,将您拥有的字符串保存为字符串,然后从中断处继续,除非此时将您累积的数字连接到不同的字符串。有两串数字后,比较两者并取较高的数字。继续这个,直到你完成处理字符串。我希望这是有道理的,有点难以解释。
答案 0 :(得分:2)
字符串的索引为0.因此,如果您尝试访问some_str[len(some_str)]
,则会得到IndexError
,因为该字符串的最高索引为len(some_str) - 1
。将您的while
条件更改为:while a < len(myString):
。此外,您不应将string
用作变量,因为它可能会使python string
模块名称蒙上阴影。
答案 1 :(得分:1)
问题在于您将a
递增太多次。因此,当a等于字符串的长度(a = 16
)时,程序会中断。将第3行更改为while a < len(string):
应修复此问题。
另外,我不太确定你对你的变量做了什么。你声明从未使用过的r1,并且在没有声明的情况下使用r2。问题可以比你的方法更容易解决 - 以下代码似乎做你想要的:
>>> r=longest=''
>>> for a in range(1:len(string)):
if (string[a-1] <= string[a]) or len(r)==0:
r += string[a]
else:
r = string[a] // We need to reset r if the string is not in numerical order
if len(r) > len(longest):
longest = r
a += 1
>>> longest
'1223455'
答案 2 :(得分:1)
首先要确保你有几件要测试的东西和预期的结果,包括边界情况。
strings = {
'1223123341223455': '1223455', # at the end
'1': '1', # just one
'12321': '123', # at the start
'212321': '123', # in the middle
'': '', # empty
'123234': '123', # two of same length, take the first
'12231233412234552': '1223455', # at the end -1 testing the try
}
然后搜索最长的字符串,不用将到目前为止找到的实际字符附加到某个临时字符串。这是低效的。您只需要知道最长字符串的起始索引及其长度:
def longest(s):
max_start = 0
this_start = 0
max_length_minus_one = 0
for x in range(len(s)-1):
if s[x] > s[x+1]:
length_found = x - this_start
if length_found > max_length_minus_one:
max_length_minus_one = length_found
max_start = this_start
this_start = x + 1
try:
# test the final string position
length_found = x + 1 - this_start
if length_found > max_length_minus_one:
max_length_minus_one = length_found
max_start = this_start
except UnboundLocalError:
pass # empty string throws this exception
return s[max_start:max_start+max_length_minus_one+1]
现在在测试用例上运行它并检查输出:
for s, check in strings.iteritems():
res = longest(s)
print repr(s), repr(res), 'OK' if res == check else '<<<<< ERROR'
答案 3 :(得分:0)
string = '1223123341223455'
longest = ''
r = ''
for i in range(len(string)):
j = i+1
r += string[i]
if j > len(string)-1 or string[i] > string[j]:
if len(r) > len(longest):
longest = r
r = ''
print longest # 1223455