How can I fix the following code to enumerate words of length $k$ in an alphabet?

Question:

In Python 3, I am writing code to make a list of words of length k, where k is a positive integer, in some given alphabet. The alphabet should be a list (for example, [a,b,c,d]).

Here is the code:

def list_len_k_words(alphabet, k):
list = []
if k == 1:
    return alphabet
if k >= 2:
    for i in alphabet:
        for j in list_len_k_words(alphabet,k-1):
            list = list.append(i+j)
    return list

This throws the error “‘NoneType’ object has no attribute ‘append'”. I partially understand what is happening: if I print the values of i+j that the program generates, the last value is always None. This has something to do with the return statement of my code, but I do not see how to fix it.

Asked By: user514014

||

Answers:

The main problem in your code is that you assigned the output of list.append to list. append modifies your list in place, and returns nothing (in fact, it returns None, as all functions that don’t have an explicit return value). On the next loop, your list was None, so trying to append to it failed.

Note that I renamed your list to ‘words’, as list is the name of a Python builtin function.

def list_len_k_words(alphabet, k):
    words = []
    if k == 1:
        return alphabet
    if k >= 2:
        for i in alphabet:
            for j in list_len_k_words(alphabet,k-1):
                words.append(i+j)
        return words

list_len_k_words('abc', 2)
# ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']

You could also have used the itertools module to obtain the same result:

from itertools import permutations

def list_len_k_words(alphabet, k):
    return [''.join(perm) for perm in permutations(alphabet, k)]
Answered By: Thierry Lathuille
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.