Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

linear searching with two letters python

I have this program which should return (using linear searching) a list of all instances of single characters in 'corpus' that immediately follow 'last' (including duplicates). The characters should be in that same order as they appear in the corpus

Example:

    filter_possible_chars('lazy languid line', 'la')
        ['z', 'n']
        filter_possible_chars('pitter patter batton', 'tt')
        ['e', 'e', 'o']
filter_possible_chars('pitter pattor batt', 'tt')
    ['e', 'o']

But my program runs into a problem for the second example where after the third tt in the word batt, there is nothing after it so it obviously shouldnt put anything else in the list but I get the IndexError list index out of range?

This is the function:

def filter_possible_chars(corpus, last):

listo = []
last_list = []
final = []

for thing in corpus:
    listo.append(thing)
for last_word in last:
    last_list.append(last_word)
    
    
for index, letter in enumerate(listo):
    
    if letter == last_list[0]:
        if listo[index+1] == last_list[1]:
            final.append(listo[index+2])  
print(final)
question from:https://stackoverflow.com/questions/65649589/linear-searching-with-two-letters-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You seem to have identified the issue; you are sometimes trying to access a list element with an index that exceeds the maximum index of your list here: final.append(listo[index+2]) or here listo[index+1].

You can define a helper method that checks first that access will be successful.

def get(_list, index):
    if len(_list) >= index - 1:
        return _list[index]

my_list = [1, 2, 3]
idx = get(my_list, 2) # 3
idx = get(my_list, 4) # None
if idx is not None:
  # do stuff

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...