Module: (Python) Subroutines. recursion


Problem

11/12

Iterating over lines #1

Theory Click to read/hide

Task
In the alphabet of the language of the tribe «Tumba-Yumba» four letters: "K", "L", "M" and "N". It is necessary to display on the screen all words consisting of n letters that can be built from the letters of this alphabet

The problem is a normal brute-force problem that can be reduced to a smaller problem.
We will sequentially substitute letters for the word.
The first position of a word can be one of the 4 letters of the alphabet (K, L, M, N).
First, put the letter 'K' first. Then, in order to get all variants with the first letter 'K', you need to enumerate all possible combinations of letters in the remaining n-1 positions and .etc. (see picture)
Thus, we came up with a recursive solution: in a loop, go through all possible first letters (putting each letter of the alphabet in turn in the first place) and for each case build all possible "tails"; length n-1.
 
Recursive iteration of characters
You need to stop the recursion and output the finished word when the remaining part is empty (n = 0), i.e. all letters are already selected. 
The recursive procedure would look like this: 
def TumbaWords(word, alphabet, n):
    if n < 1:
        print(word)
        return
    for c in alphabet:
        TumbaWords(word+c, alphabet, n - 1)

Problem

In the alphabet of the language of the tribe «tumba-yumba» four letters: "K", "L", "M" and "N". You need to display all the words consisting of N  letters that can be built from the letters of this alphabet.