Skip to content Skip to sidebar Skip to footer

For Loop To Iterate Through Words

My previous post caused a lot of confusion and it flooded with answers that is not relevant to my questions. (My fault for not clarifying things) I flagged that post and this is th

Solution 1:

I think your rule goes something like this: If the first string has a suffix that's also a prefix of the second string, chop it off. Then merge the two strings.

If you search backward, starting with the whole string and working down instead of starting with a single character and working up, you don't need to keep track of anything at all, other than the current suffix you're testing. In other words:

def frags(strings):
    left, right= strings
    for i in reversed(range(len(left))):
        if right.startswith(left[-i:]):
            returnleft[:-i] +rightreturnleft+right

Solution 2:

String slicing will likely make the code much simpler. Here's something to get you started:

def overlap(left, right):
    for i in reversed(range(len(left))):
            if left[-i:] ==right[:i]:
                break
    returnleft+right[i:]

for pair in [
    ('keyboard', 'ardjimmy'),
    ('jimmy', 'myolita'),
    ('myolita', 'jimmy'),
]:
    left, right= pair
    print pair, '-->', overlap(left, right), overlap(right, left)

Post a Comment for "For Loop To Iterate Through Words"