Reputation: 83
I completed an exercise in which I found and returned the common words between two strings in alphabetical order as a string, separated by commas. Though I was able to do it correctly, I am wondering if there is a better way. Better can be defined however you 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'
Upvotes: 2
Views: 214
Reputation: 4521
I tried to extend your question. Here is my answer.
def return_common(*data):
common_words = reduce(lambda a,b:a&b, map(lambda x: set(x.split(",")), data))
return ",".join(common_words)
example:
>>> return_common("two,three", "four,five,one,two,six,three", "three"):
'three'
Upvotes: 1
Reputation: 5473
The code can be shortened(into a line) like this -
def return_common(first, second):
return ",".join(sorted(set(first.split(","))&set(second.split(","))))
Testing it -
>>> return_common("one,two,three", "four,five,one,two,six,three")
'one,three,two'
Upvotes: 2
Reputation: 31270
The basic method is good but you are doing too much work. Repeated joins and splits, and turning things into lists that don't need to be. And do you need the result to be sorted?
You could do just
def return_common(first, second):
common_words = set(first.split(",")) & set(second.split(","))
return ",".join(common_words)
Upvotes: 1