Reputation: 6168
one = open('one.txt')
two=open('two.txt')
def bres(obj1,obj2):
x=obj1.readline().split()
cc=obj2.readline().split()
ela=set(x)
elamou=set(cc)
print elamou|ela
bres(one,two)
the file one.txt
is like this: one two tree
the file two.txt
is like this: one four
I want to find the union of the two files. The result of this piece of code is a blank set . The correct answer is one
. Where is the error?
Upvotes: 0
Views: 280
Reputation: 95252
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"...
Upvotes: 1
Reputation: 6430
def bres(obj1,obj2):
x=obj1.readline().split()
cc=obj2.readline().split()
results=[]
for a in x:
if a in cc:
results.append(a)
return results
The above should work, and is based off of what code you gave.
To get the results, all you need to do is use print bres(file_object_1,file_object_2)
.
Upvotes: 0
Reputation: 6168
I found it !
def bres():
with open('one.txt') as f:
x=f.readline().split()
with open('two.txt') as f:
cc=f.readline().split()
ela=set(x)
elamou=set(cc)
print elamou&ela
bres()
Upvotes: 2