Reputation: 1
def sucontain(A):
C = A.split()
def magic(x):
B = [C[i]==C[i+1] for i in range(len(C)-1)]
return any(B)
N = [x for x in C if magic(x)]
return N
Phrase = "So flee fleeting candy can and bandage"
print (sucontain(Phrase))
The goal of this function is to create a list of the words that are inside of each successive word. For example the function would take the string ""So flee fleeting candy can and bandage" as input and return ['flee', 'and'] because flee is inside fleeting (the next word) and 'and' is inside 'bandage'. If no cases like these are found, an empty list [] should be returned. My code right now is returning [] instead of ['flee', 'and']. Can someone point out what I'm doing wrong? thank you
Upvotes: 0
Views: 93
Reputation: 184191
Looking ahead can be problematic. Instead of testing whether the current word is in the next one, check to see whether the previous word is in the current one. This almost always makes things simpler.
Also, use descriptive variable names instead of C
and A
and x
and B
and N
and magic
.
def succotash(text): # okay, so that isn't very descriptive
lastword = " " # space won't ever be in a word
results = []
for currentword in text.split():
if lastword in currentword:
results.append(currentword)
lastword = currentword
return results
print succotash("So flee fleeting candy can and bandage")
Upvotes: 0
Reputation: 2101
Just pair the consecutive words, then it becomes an easy list comprehension…
>>> s = "So flee fleeting candy can and bandage"
>>> words = s.split()
>>> [i for i, k in zip(words, words[1:]) if i in k]
['flee', 'and']
Upvotes: 7
Reputation: 208475
There is definitely something wrong with your magic
function. It accepts x
as an argument but doesn't use it anywhere.
Here is an alternate version that doesn't use an additional function:
def sucontain(A):
C = A.split()
return [w for i, w in enumerate(C[:-1]) if w in C[i+1]]
The enumerate()
function allows us to loop over the indices and the values together, which makes it very straight forward to perform the test. C[i+1]
is the next value and w
is the current value so w in C[i+1]
checks to see if the current value is contained in the next value. We use C[:-1]
to make sure that we stop one before the last item, otherwise C[i+1]
would result in an IndexError.
Upvotes: 2