Words generating in Python

joshua08 :

Let's consider we have an alphabet {'0','1'} and want to create a list of all words of length n, so they don't contain two zeros in a row. My idea of this implementation goes around:

def words(n):
    if n == 0:
        return ['']
    return [a+b for b in words(n-1) for a in ['0','1'] if a != '0' or b != '0']

The output of words(3) is the following:

['010', '110', '001', '101', '011', '111']
                 ^is the wrong one

Can you see my mistake or where my idea of generator goes wrong?

dedObed :

The problem with your implementation is that once b grows to more than one character, it can never evaluate as equal to '0'. As you actually ask about the first letter of b, python has a string method ready for you:

def words(n):                                                                                                                                                                                                
    if n == 0:                                                                                                                                                                                                     
        return ['']                                                                                                                                                                                                
    return [a+b for b in words(n-1) for a in ['0','1'] if a != '0' or not b.startswith('0')]                                                                                                                       

The interface is kept, so you can e.g.:

words(3)  # ['010', '110', '101', '011', '111']

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11347&siteId=1