Created
June 1, 2015 08:12
-
-
Save napsternxg/924fb267dae075a88285 to your computer and use it in GitHub Desktop.
Anagram Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
logger = logging.getLogger('anagram') | |
logger.setLevel(logging.DEBUG) | |
def anagram(string_set): | |
if len(string_set) == 1: | |
logger.info("Reached Length 1") | |
return string_set # If the set has only one element then return that element. | |
logger.debug("Input: %s" % string_set) | |
temp = set() # Use a set to store all the possible anagrams. | |
for s in string_set: | |
excluded = string_set - set(s) # Get all elements of the set except the current element. | |
logger.debug("S: %s, excluded %s, temp: %s" %(s, excluded, temp)) | |
""" | |
Prepend all the anagrams of the excluded elements to the current element to create the final anagram. | |
""" | |
temp = temp.union(set([s+k for k in anagram(excluded)])) | |
logger.debug("Finished for %s, temp: %s" % (string_set, temp)) | |
return temp # Return the list of generated anagrams. | |
""" | |
Wrapper function for anagram generator. | |
""" | |
def get_anagram(string): | |
string = string.lower() # Convert the string to lowercase | |
return anagram(set(string)) # Pass a set of alphabets in the string | |
get_anagram("Shu") | |
""" | |
Output: | |
{'hsu', 'hus', 'shu', 'suh', 'uhs', 'ush'} | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DEBUG:anagram:Input: set(['h', 's', 'u'])
DEBUG:anagram:S: h, excluded set(['s', 'u']), temp: set([])
DEBUG:anagram:Input: set(['s', 'u'])
DEBUG:anagram:S: s, excluded set(['u']), temp: set([])
INFO:anagram:Reached Length 1
DEBUG:anagram:S: u, excluded set(['s']), temp: set(['su'])
INFO:anagram:Reached Length 1
DEBUG:anagram:Finished for set(['s', 'u']), temp: set(['us', 'su'])
DEBUG:anagram:S: s, excluded set(['h', 'u']), temp: set(['hus', 'hsu'])
DEBUG:anagram:Input: set(['h', 'u'])
DEBUG:anagram:S: h, excluded set(['u']), temp: set([])
INFO:anagram:Reached Length 1
DEBUG:anagram:S: u, excluded set(['h']), temp: set(['hu'])
INFO:anagram:Reached Length 1
DEBUG:anagram:Finished for set(['h', 'u']), temp: set(['uh', 'hu'])
DEBUG:anagram:S: u, excluded set(['h', 's']), temp: set(['hsu', 'shu', 'suh', 'hus'])
DEBUG:anagram:Input: set(['h', 's'])
DEBUG:anagram:S: h, excluded set(['s']), temp: set([])
INFO:anagram:Reached Length 1
DEBUG:anagram:S: s, excluded set(['h']), temp: set(['hs'])
INFO:anagram:Reached Length 1
DEBUG:anagram:Finished for set(['h', 's']), temp: set(['hs', 'sh'])
DEBUG:anagram:Finished for set(['h', 's', 'u']), temp: set(['ush', 'shu', 'hus', 'hsu', 'uhs', 'suh'])
{'hsu', 'hus', 'shu', 'suh', 'uhs', 'ush'}