Это не рекурсивно, но я думаю, что оно делает то, что вы хотите.
doc = 'a b c d e f'
words = doc.split(None)
max = 3
for index in xrange(len(words)):
for n in xrange(max):
if index + n < len(words):
print ' '.join(words[index:index+n+1])
А вот рекурсивное решение:
def find_terms(words, max_words_per_term):
if len(words) == 0: return []
return [" ".join(words[:i+1]) for i in xrange(min(len(words), max_words_per_term))] + find_terms(words[1:], max_words_per_term)
doc = 'a b c d e f'
words = doc.split(None)
for term in find_terms(words, 3):
print term
Вот снова рекурсивная функция с некоторыми поясняющими переменными и комментариями.
def find_terms(words, max_words_per_term):
# If there are no words, you've reached the end. Stop.
if len(words) == 0:
return []
# What's the max term length you could generate from the remaining
# words? It's the lesser of max_words_per_term and how many words
# you have left.
max_term_len = min(len(words), max_words_per_term)
# Find all the terms that start with the first word.
initial_terms = [" ".join(words[:i+1]) for i in xrange(max_term_len)]
# Here's the recursion. Find all of the terms in the list
# of all but the first word.
other_terms = find_terms(words[1:], max_words_per_term)
# Now put the two lists of terms together to get the answer.
return initial_terms + other_terms