在edx python课程中,我被指派创建一个程序,从给定字符串中按字母顺序打印出最长的子字符串。我已经写了代码,但当我运行它时,我得到了"错误:检查模块中的内部Python错误。"。我不明白为什么。如果有人能帮我弄清楚那就太好了。这是代码:
s = 'azcbobobegghakl'
start=0
temp=0
while start<len(s):
initial=start
while True:
if ord(s[start])<=ord(s[start+1]):
start+=1
else:
start+=1
if len(s[initial:start])>temp:
sub=s[initial:start]
temp=len(sub)
break
print sub
这就是完整的错误:
Traceback (most recent call last):
File "C:UsersYoavAppDataLocalEnthoughtCanopyAppappdatacanopy-1.5.4.3105.win-x86_64libsite-packagesIPythoncoreultratb.py", line 776, in structured_traceback
records = _fixed_getinnerframes(etb, context, tb_offset)
File "C:UsersYoavAppDataLocalEnthoughtCanopyAppappdatacanopy-1.5.4.3105.win-x86_64libsite-packagesIPythoncoreultratb.py", line 230, in wrapped
return f(*args, **kwargs)
File "C:UsersYoavAppDataLocalEnthoughtCanopyAppappdatacanopy-1.5.4.3105.win-x86_64libsite-packagesIPythoncoreultratb.py", line 267, in _fixed_getinnerframes
if rname == '<ipython console>' or rname.endswith('<string>'):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 3: ordinal not in range(128)
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.
Unfortunately, your original traceback can not be constructed.
谢谢!
看起来代码大部分都能工作,但当您调用break时,它只从else块中中断,并继续运行,其中start的值大于s的最大索引。
尝试将此代码放入函数中,并在找到正确的子字符串时使用返回
祝你好运!
def sub_finder(s):
start=0
temp=0
while start<len(s):
initial=start
while True:
if (start < len(s) - 1):
if ord(s[start])<=ord(s[start+1]):
start+=1
else:
start+=1
if len(s[initial:start])>temp:
sub=s[initial:start]
temp=len(sub)
break
else:
start+=1
if len(s[initial:start])>temp:
sub=s[initial:start]
temp=len(sub)
return sub
test = 'abcdaabcdefgaaaaaaaaaaaaaaaaaaaaaaaaaaaabbcdefg'
print sub_finder(test)
哎呀,试试这个尺码。