Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Subanagram Generator in Python, v1
#!/usr/bin/python
# subanagram.py
# 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>
<HEAD>
<TITLE>Sub-Anagram Generator: Result for %s</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF"><P>
<H1>
Sub-Anagram Generator: Result for "%s"\n
</H1>""" % (word_input, word_input)
counter = 0
letarray1 = {}
wordcounts = {}
for char in word_input:
try:
letarray1[char.lower()] = letarray1[char.lower()] + 1
except:
letarray1[char.lower()] = 1
words = open("ni2_ospd3.txt").readlines()
for word in words:
okay = 0
word = word[:-1]
letarray2 = {}
for char in word:
try:
letarray2[char.lower()] = letarray2[char.lower()] + 1
except:
letarray2[char.lower()] = 1
for k, v in letarray2.iteritems():
try:
if letarray1[k] > 0 and letarray2[k] > 0:
if letarray2[k] <= letarray1[k]:
okay = okay + letarray2[k]
except:
pass
if okay == len(word):
counter = counter + 1
try:
wordcounts[len(word)].append(word)
except:
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>"
else:
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="http://www.szcz.org/article/60">Find subanagrams for another word</A>.<BR>
This page was dynamically generated by a script written by <A HREF="http://www.szcz.org">Mitchell Szczepanczyk</A>.
</BODY></HTML>"""
@danibarker

This comment has been minimized.

Copy link

@danibarker 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
You can’t perform that action at this time.