Wednesday, December 17, 2014

Code Review: Finding every possible (unique) combination of words from a file. learnpython


For reasons I can't explain I saw this post in /r/GoForGold and saw that someone had already put together a list of words and thought "I haven't written any code in like a year, I should see what I can do with this in python!".


Granted, I realized after the fact that with 809 words in the list, there would be...a LOT of possible results, so this doesn't really help finding a coherent story...but I wanted to see if my overall method for finding unique permutations seems sound, or did I overthink this/not do things pythonically (beyond basic syntax, I've not played around much with stuff in the standard lib).


words.py:



#!/usr/bin/python import hashlib import itertools def make_list_from_file(file): with open(file,"r") as open_file: file_list = [word.strip() for word in open_file ] return file_list def make_str_from_tup(tup): combined = " ".join(word for word in tup) return combined words = make_list_from_file("/tmp/words.list") all_perms = itertools.permutations(words) uniq_perm_hashes = [] for k,v in enumerate(all_perms): file_num = str(k+1) file_name = "/tmp/g4g/permutation" + file_num perm_as_str = make_str_from_tup(v) hash_of_perm = hashlib.md5(perm_as_str).hexdigest() if hash_of_perm not in uniq_perm_hashes: print "Permutation %s was uniq so saving as %s\n" % (file_num,file_name) with open(file_name,"w") as open_file: open_file.write(perm_as_str) uniq_perm_hashes.append(hash_of_perm) else: print "Permutation %s was NOT uniq so ignoring it\n" % (file_num)





Submitted December 18, 2014 at 07:48AM by MrVonBuren http://ift.tt/1GtUauU learnpython

No comments:

Post a Comment