Python's sets can run a bit slower than lists (~4x slower). The problem below just figures out how many words in /usr/share/dict/words can be made from the letters of "paleontology" (especially if any of length 8 exist ;).
# from http://my-sketches.livejournal.com/104876.html
import sets, sys
if sys.argv[1] not in ["sets", "lists"]:
sys.exit("sets or lists?")
def is_in(needle, haystack):
test = False
for n in needle:
test = False
for i,h in enumerate(haystack):
if n == h:
del(haystack[i])
test = True
break
if test == False:
break
return test
def uniqueify(s):
c = {}
ret = []
for w in list(s):
c[w] = c.get(w,0) + 1
ret.append(w + "%s" % c[w] )
return ret
dict = "/usr/share/dict/words"
f = open(dict, "r")
words = []
for line in f:
word = line.rstrip()
if sys.argv[1] == "sets":
p = sets.Set(uniqueify("paleontology"))
if sets.Set(uniqueify(word)) <= p:
print word
if sys.argv[1] == "lists":
if is_in(list(word), list("paleontology")):
print word
Just out of curiosity, do you regularly do much Python coding? If so, for what kind of problems do you use it as opposed to Perl? -- David W
Let me rephrase David's question...Why in gods name would you choose Python over Perl??!?!?!?! :) - Nathan
Heh, no. This isn't the religion thread ;) -- David W
The there's more than one way to do it idea makes larger projects difficult to maintain. I have no real need, I'm just dinking around to learn it and see what it can do (yes, I realize the Turing-complete-idiocy of that statement ;).