Hi, I am solving elementary puzzles with checkio now and one question has arisen.

The task is as follows:

Two lines are given with comma separated words. Try to find what is common between these lines. Words within each line are not repeated.

Your function should find all the words that appear in both lines. The result should be presented as a string with words separated by commas and sorted alphabetically.

I did this:

def checkio(first, second): dbl = "" words = set(first.split(",") + second.split(",")) for word in words: if word in first.split(",") and word in second.split(","): dbl += " ".join(word) return sorted(dbl) checkio("one,two,three", "two,four,five,three") 

But, the string is supplemented character by character and I do not understand why. That is, instead of

 two,three 

he leads

 t,w,ot,h,r,e,e 

I want to figure out why, tell me where to look?

    1 answer 1

    The problem is that you add elements to a string, and then sort it, instead of sorting an array of words. The string is sorted character by character. In addition, the result of your function will be a list of strings, each of which contains exactly one character.

    In fact, your task can be solved much easier if you use the standard functions for working with sets, namely intersection :

     In [7]: def checkio(first, second): ...: return ','.join(sorted(set(first.split(',')) & set(second.split(',')))) ...: In [8]: checkio("one,two,three", "two,four,five,three") Out[8]: 'three,two' 

    It is worth noting that in your question the words two and three do not stand in alphabetical order.

    • Thanks for the advice. But if we replace dbl with a list, the output will still be ['t', 'w', 'o', 't', 'h', 'r', 'e', ​​'e'], although the iteration should already go by words, not by characters. - Chaosman
    • 'def checkio (first, second): dbl = [] words = set (first.split (",") + second.split (",")) for word in words: if word in first.split ("," ) and word in second.split (","): dbl + = word return dbl ' - Chaosman
    • And now implementation += comes in for lists. The fact is that this function expects an enumerated type, and when it receives a string as input, it happily lists it, resulting in characters. Try replacing strings with regular numbers: a = [1, 2, 3]; a += 4 a = [1, 2, 3]; a += 4 . Instead of the __iadd__ function, __iadd__ can use the append function. - awesoon
    • Now I understand everything. Thank. - Chaosman