As a matter of style, I would pass the filenames into bres
, and have it return a list which you then print out from the caller.
def bres(file1, file2):
sets = []
for n in (file1, file2):
with open(n) as f:
sets.append( set( f.readline().split() ) )
return list(sets[0] & sets[1])
print ' '.join(bres('one.txt', 'two.txt'))
Using with
as above (and as you did) is the cleanest and most explicit way to deal with opening and reading the files. If, however, you are interested in shorter code for some reason, and you don't mind relying on garbage collection to close the file handles for you, you can shorten the creation of the set list to one line using a list comprehension:
def bres(file1, file2):
sets = [ set( file(f).readline().split() ) for f in (file1, file2) ]
return list(sets[0] & sets[1])
print ' '.join(bres('one.txt', 'two.txt'))
I was tempted to import operator
and use reduce(operator.and_, sets)
to generalize things - those explicit indexes just bug me. But that would probably be filed under "reasons Guido dislikes functional programming"...