Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Subanagram Generator in Python, v1
# This program receives as input an English word, and then
# delivers as output those English words which can be spelled with the
# letters in the input word.
# This script is Copyleft 2002, 2012 by Mitchell Szczepanczyk under the
# terms of the General Public License. Anyone is free to copy, modify,
# or distribute this script, without warranty, under the terms that any
# copy or copies of this script also fall under the terms of the
# General Public License.
import cgi
form = cgi.FieldStorage()
word_input = form.getvalue('word')
print "Content-type: text/html\n\n"
print """<HTML>
<TITLE>Sub-Anagram Generator: Result for %s</TITLE>
Sub-Anagram Generator: Result for "%s"\n
</H1>""" % (word_input, word_input)
counter = 0
letarray1 = {}
wordcounts = {}
for char in word_input:
letarray1[char.lower()] = letarray1[char.lower()] + 1
letarray1[char.lower()] = 1
words = open("ni2_ospd3.txt").readlines()
for word in words:
okay = 0
word = word[:-1]
letarray2 = {}
for char in word:
letarray2[char.lower()] = letarray2[char.lower()] + 1
letarray2[char.lower()] = 1
for k, v in letarray2.iteritems():
if letarray1[k] > 0 and letarray2[k] > 0:
if letarray2[k] <= letarray1[k]:
okay = okay + letarray2[k]
if okay == len(word):
counter = counter + 1
wordcounts[len(word)] = [word]
for k, v in wordcounts.iteritems():
subcounter = 0
if k == 1:
print "<B>Words that are 1 letter long:</B><BR>"
print "<B>Words that are %s letters long:</B><BR>" % k
for eachword in sorted(v):
print "%s<BR>" % eachword
subcounter = subcounter + 1
print "Number of %s-letter words: <B>%s</B><P><P>" % (k, subcounter)
print "<P><B>%s</B> total words were found in the word '%s'.<BR>" % (counter, word_input)
print """<HR>
<A HREF="">Find subanagrams for another word</A>.<BR>
This page was dynamically generated by a script written by <A HREF="">Mitchell Szczepanczyk</A>.
Copy link

danibarker commented Aug 6, 2020

this runs a little faster for checking if a word is a subanagram, especially for shorter inputs:

def issubanagram(subset, set):
	for item in [c in set for c in subset]:
		if not item:
			return False
	for item in [False for difference in [set.count(l)-subset.count(l) for l in subset] if difference<0]:
		if not item:
			return False
	return True

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment