python - Better way to find common words in a tuple? -
i completed exercise in found , returned common words between 2 strings in alphabetical order string, separated commas. though able correctly, wondering if there better way. better can defined define it.
def return_common(first, second): first = first.split(',') second = second.split(',') newlist = ",".join(list(set(first) & set(second))) #newlist = list(newlist) newlist = newlist.split(',') newlist = sorted(newlist) newlist = ",".join(newlist) return newlist return_common("one,two,three", "four,five,one,two,six,three") #above returns 'one,three,two'
the code can shortened(into line) -
def return_common(first, second): return ",".join(sorted(set(first.split(","))&set(second.split(","))))
testing -
>>> return_common("one,two,three", "four,five,one,two,six,three") 'one,three,two'
Comments
Post a Comment