2015-06-22 76 views
1

我在edx python課程中被分配來創建程序,該程序打印出從給定字符串按字母順序排列的最長子字符串。我寫了我的代碼,但是當我運行它時,我得到了「錯誤:檢查模塊中出現內部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:\Users\Yoav\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.4.3105.win-x86_64\lib\site-packages\IPython\core\ultratb.py", line 776, in structured_traceback 
    records = _fixed_getinnerframes(etb, context, tb_offset) 
    File "C:\Users\Yoav\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.4.3105.win-x86_64\lib\site-packages\IPython\core\ultratb.py", line 230, in wrapped 
    return f(*args, **kwargs) 
    File "C:\Users\Yoav\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.4.3105.win-x86_64\lib\site-packages\IPython\core\ultratb.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. 

謝謝!

回答

0

看起來代碼大部分工作正常,但是當你調用break時,它只會從else塊中跳出來,並繼續運行while,並且start的值大於s的max index。

嘗試把一個函數的代碼,並使用一回當你找到了正確的子

祝你好運!

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) 

哎呦,試試這個大小。

+0

代碼不起作用。我檢查了它的s ='azcbobobegghakl'(它應該打印'beggh',並且它打印'az' – Zoltan

+0

謝謝!現在它的工作原理 – Zoltan

+0

但我仍然不明白爲什麼我需要「start Zoltan