1
def scan_for_match(T1, T2):
    i = 0
    j = 0
    while i <= (len(T1)):
        if T1[i] == T2[j]:
            keywords = open('keywords.txt', 'w+')
            keywords.write(T1.pop(i))
            T2.pop(j)
        if i > (len(T1)):
            i = 0
            j += 1
        if j > (len(T2)):
            print "All words have been scanned through"
            print "These are the matches found:\n ", keywords.readlines()
        i += 1

I thought that this was a pretty straight forward piece of code, but...

T1 = ["me", "gusta", "espanol"]; T2 = ["si", "no", "espanol"]; scan_for_match(T1, T2)

Will just give me:

Traceback (most recent call last):
  File "stdin", line 1, in module
  File "stdin", line 5, in scan_for_match
IndexError: list index out of range

The line in question is just a harmless if T1[i] == T2[j]: Which for me just doesn't make sense since:

i = 0
j = 0
T1[i] = 'me'
T2[j] = 'si'

So this should just return a False result instead of an IndexError, right?

2 Answers2

2

while i <= (len(T1)): is wrong, when i equals the length, it will have IndexError, change it to <. Index is starting from 0 to (length - 1)

I suggest not using pop() method, it will remove element(s) from your list, scan for match doesn't need the matching elements to be removed, right? :)

Alternatively, you can find the match in this way:

>>> t2= ["si", "no", "espanol"]
>>> t1=  ["me", "gusta", "espanol"]
>>> set(t2) & set(t1)
{'espanol'}
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
1

Change the condition on the while to:

while i < len(T1)
#       ^

When i = len(T1) and you try to index your list, you'll get an IndexError because your index starts counting from zero.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139