1

doing an exercise on CheckIO and I'm wondering as to why this won't work. Given a set of strings, I'm trying to return True if any of the strings are suffixes of any other string in the set. False otherwise. Using itertools I'm generating the necessary permutations in tuples first. Then for each tuple (each i), I wanted to see the hard way if the second tuple was in the end of the first tuple (option1). The otherway was using the .endwith function (option2), but neither will work for me. Why are these two options flawed?

import itertools

def checkio(words_set):
    for i in itertools.permutations(words_set, 2):
    #option1 ---- if i[1] in i[0][-len(i[1]):]:
    #option2 ---- if i[0].endswith(i[1]):
            return True
        else:
            return False

examples:

checkio({"hello", "lo", "he"}) == True

checkio({"hello", "la", "hellow", "cow"}) == False

I know this works as an answer. But just wondering why my original methods wouldn't take.

def checkio(words_set):
    for w1 in words_set:
        for w2 in words_set:
           if w1.endswith(w2) and w1 != w2:
               return True
    return False
SpicyClubSauce
  • 4,076
  • 13
  • 37
  • 62

3 Answers3

1

Your return False should be at the end of the for loop, otherwise the function will return True/False at every first comparison and will ignore all subsequent comparisons:

import itertools

def checkio(words_set):
    for i in itertools.permutations(words_set, 2):
        if i[0].endswith(i[1]):
            return True

    return False
Jake Griffin
  • 2,014
  • 12
  • 15
ODiogoSilva
  • 2,394
  • 1
  • 19
  • 20
0

Its because you return False right after the first check. and if it fails it will returns False you need to put it out of your for loop!

But as a more pythonic way you can use combinations and a generator expression within any function :

>>> from itertools import combinations
>>> s={"hello", "lo", "he"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s,2)))
True
>>> s2={"hello", "la", "hellow", "cow"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s2,2)))
False
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

Since it's an exercise, I won't give you the full answer, but are you sure that you really want to return False in the else clause?

Arkanosis
  • 2,229
  • 1
  • 12
  • 18