2014-09-22 72 views
0

我試圖解決pythonchallenge上的一個挑戰..它給你一個帶有不同情況的信件的文本牆,並且你試圖找到被3個包圍的小寫字母從每邊大寫字母.. 這裏是我的嘗試通過字符串循環來檢查特定的大小寫匹配

text=open("challenge.txt") 
thedata=text.read() 

def check(s,c): 
    upper='ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
    lower="abcdefghijklmnopqrstuvwxyz" 
    n=s.index(c) 
    if (c in lower) and (s[n-2] in upper) and (s[n+1] in upper) and (s[n-1] in upper) and (s[n+2] in upper) and (s[n-3] in upper) and (s[n+3] in upper): 
     return True 
    else: 
     return False 

def solver(s): 
    listOfSol=[] 
    for c in s: 
     try: 
      if check(s,c): 
       n=s.index(c) 
       entry= (s[n-3:n+4]) 
       if entry not in listOfS: 
        listOfSol.append(entry) 
     except KeyError: 
      continue 
    return listOfSol 

print solver(thedata) 

這是行不通的,我想知道爲什麼,請不要給我一個答案的快捷方式或嘗試給我挑戰的解決方案,因爲我認爲自己是一個Python初學者,我只想知道爲什麼這不起作用(總是返回一個空列表)。 由於事先

+0

如果字符串中每個字符有多個,該怎麼辦? 「aBCDaBCD」.index(「a」)給出了什麼? – jonrsharpe 2014-09-22 10:50:10

+0

哦,我沒有想到這一點,謝謝jonsharpe ..我會試着用* enumerate(s)*來解決這個問題,並且看看會發生什麼。 – 2014-09-22 11:33:49

回答

0

很抱歉,如果我已經解決了你太多,但你可以列舉了數據,然後使用中的for循環的附加變量來跳過匹配等,以使字母:

for index, letter in enumerate(thedata): 
     #'add' is a number we're adding to the index that we want to check, so it can be incremented by 7 to skip matching strings 
     add = 0 
     index2 = index + add 

     #use a try-except clause because there is going to be indexerrors checking the end of the string 
     try: 
     #if statement goes here 
      #add to matches 
      add += 7 

     except: 
     continue 
相關問題