Thursday, September 26, 2019

Python functions for generating all substrings/sublists, combinations, permutations, and sequences

def subs(xs, sub_len):
    '''Get all sublists/substrings from xs of the given sub-length.'''
    for i in range(len(xs) - sub_len + 1): #Get all indexes of the substrings that are at least sub_len long.
        yield xs[i:i+sub_len]

for x in subs('abcd', 2):
    print(x)
ab
bc
cd

def combinations(xs, comb_size):
    '''Get all combinations of the given combination size.'''
    if comb_size == 0:
        yield xs[:0] #Empty list/string
    else:
        for i in range(len(xs) - comb_size + 1):
            for ys in combinations(xs[i+1:], comb_size-1): #For every item, combine it with every item that comes after it.
                yield xs[i] + ys

for x in combinations('abcd', 2):
    print(x)
ab
ac
ad
bc
bd
cd

def perms(xs):
    '''Get all permutations.'''
    if len(xs) == 1:
        yield xs
    else:
        for i in range(len(xs)):
            for ys in perms(xs[:i] + xs[i+1:]): #For every item, combine it with every item except itself.
                yield xs[i] + ys

for x in perms('abc'):
    print(x)
abc
acb
bac
bca
cab
cba

def permutations(xs, perm_size):
    '''Get all permutations of the given permutation size.'''
    for cs in combinations(xs, perm_size):
        for p in perms(cs): #Get all the permutations of all the combinations.
            yield p

for x in permutations('abcd', 2):
    print(x)
ab
ba
ac
ca
ad
da
bc
cb
bd
db
cd
dc

def seqs(xs, seq_len):
    '''Get all sequences of a given length.'''
    if seq_len == 0:
        yield xs[:0] #Empty list/string
    else:
        for i in range(len(xs)):
            for ys in seqs(xs, seq_len-1): #For every item, combine it with every item including itself.
                yield xs[i] + ys

for x in seqs('abc', 2):
    print(x)
aa
ab
ac
ba
bb
bc
ca
cb
cc