There is no function in the standard library to generate all strings with length 0-4 consisting only of the characters 0 and 1, but it is not hard to build one.
The special case of binary numbers
Notice that all the strings you want to check are binary representations below 16 (= 10000 in binary).
import re
def binary_numbers_below(n):
return [bin(k)[2:] for k in range(n)]
for word in binary_numbers_below(2**4):
if re.fullmatch('1*(011+)*1*'):
print(word) # word is part of your language
It is necessary to cut off the first two characters of bin(k)
, because bin(k)
outputs numbers in the form 0b1000
and we don't want the 0b
prefix.
The general case
If you want to generate all words of specific lengths for any given alphabet, you need to do more work:
import re
from itertools import product
def words_of_alphabet(alphabet, min_length, max_length):
return [''.join(characters)
for length in range(min_length, max_length+1)
for characters in product(alphabet, repeat=length)]
for word in words_of_alphabet(['0', '1'], 0, 4):
if re.fullmatch('1*(011+)*1*'):
print(word) # word is part of your language
words_of_alphabet(['0', '1'], 0, 4)
will also include the empty word, whereas the first method does not.
Using generators you can code both functions even more elegantly
def binary_numbers_below(n):
for k in range(n):
yield bin(k)[2:]
def words_of_alphabet(alphabet, min_length, max_length):
for length in range(min_length, max_length+1):
for characters in product(alphabet, repeat=length):
yield ''.join(characters)