Skip to content

Instantly share code, notes, and snippets.

@kra3
Created July 11, 2012 18:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kra3/3092361 to your computer and use it in GitHub Desktop.
Save kra3/3092361 to your computer and use it in GitHub Desktop.
Compare two files with numbers, one number in one line: python version
"""
# A shorter ugly version
total = set([i.strip() for i in open("total.txt").readlines()]) # list comprehension to remove \r\n from lines
coupon = set([i.strip() for i in open("coupon.txt").readlines()]) # set to remove duplicates and do set difference
open("result.txt", "w").write('\n'.join(sorted(total-coupon))) # use set difference and use sorted to sort then write in separate lines
"""
### Now see same thing above in beautiful & readable way
# reading file content into list
total = open("total.txt").readlines()
coupon = open("coupon.txt").readlines()
# striping "\r\n and/or spaces at ends from each line
total = [i.strip() for i in total]
coupon = [i.strip() for i in coupon]
#creating sets from list
total_set = set(total)
coupon_set = set(coupon)
# finding set difference
difference = total_set - coupon_set
#sorting the result
sorted_difference = sorted(difference)
# writing the result back into file, one number in a line
f_result = open("result.txt", "w")
f_result.write('\n'.join(sorted_diffrence))
f_result.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment