3
\$\begingroup\$

I'm just trying to get the common values from two distinct files called file1.txt and file2.txt where I'm using Python's set method to get the results and this works.

However, I'm looking forward to see if there is better way to do this.

#!/grid/common/pkgs/python/v3.6.1/bin/python3
def common_member():
    a_set = dataset1
    b_set = dataset2
    if (a_set & b_set):
        print(a_set & b_set)
    else:
        print("No common elements")

with open('file1.txt', 'r') as a:
        dataset1 = set(a)
with open('file2.txt', 'r') as b:
    dataset2 = set(b)

common_member()

file1.txt

teraform101
azure233
teraform221
teraform223
teraform224

file2.txt

teraform101
azure109
teraform223
teraform226
teraform225
azure233

Result:

{ 'teraform101\n', 'azure233\n', 'teraform223\n' }
\$\endgroup\$
4
\$\begingroup\$

Global variables (dataset1 and dataset2) are bad. I'd rather see you write no function at all than a function that accepts its inputs through global variables:

with open('file1.txt') as file1, open('file2.txt') as file2:
    print((set(file1) & set(file2)) or "No common elements")

If you do write a function, then it should accept its inputs as parameters. Name the function's parameters however you want, but avoid unnecessary reassignments like a_set = dataset1 and b_set = dataset2.

def print_common_members(a, b):
    """
    Given two sets, print the intersection, or "No common elements".
    """
    print((a & b) or "No common elements")

with open('file1.txt') as file1, open('file2.txt') as file2:
    dataset1 = set(file1)
    dataset2 = set(file2)
    print_common_members(dataset1, dataset2)
\$\endgroup\$
  • \$\begingroup\$ This is indeed a great answer. \$\endgroup\$ – Karn Kumar Sep 6 '18 at 19:08
  • \$\begingroup\$ in case we need the resulting values into a new line , how could we do that into this code itself \$\endgroup\$ – Karn Kumar Sep 6 '18 at 19:12
  • 1
    \$\begingroup\$ @newTOcode: Assign common_members = a & b and then do with that variable whatever you want. \$\endgroup\$ – Graipher Sep 7 '18 at 8:00
  • 1
    \$\begingroup\$ @Graipher, thnx for your valuable inputs, its solved with using join method as print('\n'.join(s.strip('\n') for s in a & b) or "No common element") \$\endgroup\$ – Karn Kumar Sep 7 '18 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.