Adding Items To List When They Already Exist And When Using For Loop
This is a pretty simple question about lists and for loop. Assuming I have the following 2d-list: [ ['c', 'a', 't', 'c', 'a', 't'] ['a', 'b', 'c', 'a', 't, 'l'] ['c', 'a', 't',
Solution 1:
The problem is you're not checking how many times that substring occurs in the string. You also need to account for overlapping matches:
import re
defsearch_for_words(word_list, matrix):
results = []
for word in word_list:
for line in matrix:
line_string = ''.join(line)
# find all overlapping matches of word in line_string
matches = re.findall(r'(?=(' + word + '))', line_string)
results.extend(matches)
return results
If we run this on your second matrix:
m = [['a', 'p', 'p', 'l', 'e'],
['a', 'g', 'o', 'd', 'o'],
['n', 'n', 'e', 'r', 't'],
['g', 'a', 'T', 'A', 'C'],
['m', 'i', 'c', 's', 'r'],
['P', 'o', 'P', 'o', 'P']]
word_list = ['apple', 'god', 'dog', 'CAT', 'PoP', 'poeT']
print(search_for_words(word_list, m))
we see the following output:
['apple', 'god', 'PoP', 'PoP']
Solution 2:
The answer to your first question is pretty simple. Just build a string and check it each time. Lose the first letter of the string if the string is longer than the target word.
outer= [['c', 'a', 't', 'c', 'a', 't'],
['a', 'b', 'c', 'a', 't', 'l'],
['c', 'a', 't', 'w', 'x', 'y']]
forinnerinouter:
word = ""
target = "cat"
t_len = len(target)
for letter ininner:
word += letter
if len(word) > t_len:
word = word[1:]
if word in target:
print(target)
For the answer to your second question, you're probably best to just "".join()
all of the strings and parse them with regex.
Post a Comment for "Adding Items To List When They Already Exist And When Using For Loop"