# To use, change the values of n and k below to whatever you want, # then press the run button in the upper left hand corner. n = 2 k = 9 def comma_free_dict(n, k): """Only guaranteed to work when k is odd""" # Maintain a list of lists of the words found in each stage. stages = [] current_stage = map(str,range(n)) # First stage is [0, 1, ..., n-1] while len(current_stage) > 0: # Keep going until the stage created is empty current_stage = next_stage(current_stage,k) stages.append(current_stage) # Finally, lump all the stages together, and # only keep the words whose length is the length we want return [w for w in sum(stages,[]) if len(w) == k] def next_stage(prev_stage,word_length): """ Given list of words in S_n, and the desired length of words in the dictionary, returns the list of words in S_{n+1}. """ # Find all odd length words, sorted by length odd_words = [w for (l,w) in sorted([(len(w),w) for w in prev_stage if len(w)%2 == 1])] if len(odd_words)==0: # If there aren't any odd words, we are done, so return the empty list return [] # Otherwise, the prefix we use the shortest odd word. prefix = odd_words[0] # Remove any words which are already long enough prev_stage = [w for w in prev_stage if len(w)<word_length] # Take all remaining words (except the prefix), and # place the prefix in front of them as many times as possible. # The sum(,[]) part takes all the lists given by expand, and concatenates them together return sum([expand(prefix,word,word_length) for word in prev_stage if word != prefix],[]) def expand(prefix, word, max_length): """Put the string 'prefix' in front of the string 'word' as many times as possible, without exceeding max_length. Returns a list of all such words. """ words = [] current = word while len(current)<= max_length: words.append(current) current = prefix + current return words dictionary = sorted(comma_free_dict(n,k))[::-1] line = '' while dictionary: if len(line)<80: line += dictionary.pop() + ' ' else: print line line = '' print line
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question