Good afternoon friends! The task is to find common words in two lines, that is:

checkio("hello,world", "hello,earth") == "hello" 

or

 checkio("one,two,three", "four,five,six") == "" 

I wrote the code to solve this problem. Please judge STRICTLY. This code is not validated.

 def checkio(first, second): list_one = first.split(',') list_two = second.split(',') list_new = [] for word in list_one: if word in list_two: list_new.append(word) return list_new if __name__ == '__main__': assert checkio("hello,world", "hello,earth") == "hello", "Hello" assert checkio("one,two,three", "four,five,six") == "", "Too different" assert checkio("one,two,three", "four,five,one,two,six,three") == "one,three,two", "1 2 3" 

The code does not pass, because the list is returned in the form ['hello'] , and the return is expected in the form of "hello" .

I understand that my question is most likely absolutely basic, but alas, I cannot find an answer to it, I ask for your help.

Also, please show me how you can “in a normal way” write these lines of code (I am sure that you can write them humanly, and not like mine):

 list_one = first.split(',') list_two = second.split(',') 

and

 for word in list_one: if word in list_two: list_new.append(word) 

Thank you very much.

  • and what do you expect as a result: checkio('one,two,three', 'two,one') ? - MaxU
  • one
    Do you have a question how to get 'hello' from ['hello'] ? Where did you get the assert? (a specific link to checkio.org, if possible) Do you want to know the logic that explains why the answer is "one,three,two" , and not the other five options? - jfs

2 answers 2

To find common words in two lists:

 common_words = set(list_one).intersection(list_two) 

To make assert work, just sort the words and combine them with a comma:

 result = ','.join(sorted(common_words)) 

    I would do that:

     In [107]: def checkio(l1, l2): ...: return list(set(l1.split(',')) & set(l2.split(','))) ...: In [108]: checkio("one,two,three", "four,five,six") Out[108]: [] In [109]: checkio("hello,world", "hello,earth") Out[109]: ['hello'] 

    Here is a slightly more versatile option that can be compared regardless of the register (attention returns a list of words converted to lower case)

     In [110]: def checkio(l1, l2, case_insensitive=False): ...: if case_insensitive: ...: return list(set(l1.lower().split(',')) & set(l2.lower().split(','))) ...: else: ...: return list(set(l1.split(',')) & set(l2.split(','))) ...: In [111]: checkio("hello,world", "Hello,earth") Out[111]: [] In [112]: checkio("hello,world", "Hello,earth", case_insensitive=True) Out[112]: ['hello']