Reputation: 3
I want to create an algorithm that takes a list of strings as a parameter. It prints every string in the list that is a substring of the one that precedes it.
Example of output I want for function findSubStrs(lst)
:
findSubStrs(['hopefully','hope','hop','testing','test'])
hope
hop
test
What I have:
def findSubStrs(lst):
for word in lst:
for letter in word:
print(letter)
Upvotes: 0
Views: 31
Reputation: 9106
Here's a solution using functools.reduce
:
from functools import reduce
def find_substrings(array):
def inner(prev, this):
print(this) if this in prev else None
return this
reduce(inner, array)
find_substrings((['hopefully', 'hope', 'hop', 'testing', 'test'])
I could have done the if
/print
in two lines, but I was jealous of the brevity of @rioppi's solution :P
Upvotes: 0
Reputation: 25954
Use zip
to compare each element in the list with the one prior:
def find_substrs(li):
return [y for x,y in zip(li,li[1:]) if y in x]
find_substrs(['hopefully','hope','hop','testing','test'])
Out[49]: ['hope', 'hop', 'test']
Upvotes: 1