minte9
LearnRemember




S R Q

Sets

p124 A set is a collection of unique objects {A,B,C}. A permutation is a specific ordering of all elements of a set.
 
""" Head Permutations

A set is a collection of unique objects {A,B,C}.
Order doesn't matter for a set, {A,B,C} is the same as {B,A,C}
A set like {A,B,C,A} has repeate A and so is not a set.

Head permutations, we place the head in every posible location of the tail.
The permutation of a single char is the char itself (base case).
By putting the B in every possible location of C we get BC CB. 

    BC = None + B + C  # tail[0:0] = None
    CB = C + B + None  # tail[1:]  = None
"""

def head_permutations(chars):

    head = chars[0]  # B
    tail = chars[1:] # C
    prms = []
    for k in range(len(tail) + 1):     
        prms.append(tail[0:k] + head + tail[k:]) 
        
    return prms

print(', '.join(head_permutations('BC')))  # BC, CB
print(', '.join(head_permutations('BCD'))) # BCD, CBD, CDB

Permutations

p127 A permutation of a set is a specific ordering of all elements.
 
""" Permutations / Without repetition

A permutation of a set is a specific ordering of all elements.
For example {A,B,C} has six permutations ABC ACB BAC BCA CAB CBA

We select one of the elements from the set as the head.
We get all the permutations from the rest of elements (the tail).
For each permutation we place the head in every posible location.

The permutation of a single char is the char itself (base case).
By putting the B in every possible location of C we get BC CB. 
"""

def get_permutations(chars):
    
    if len(chars) == 1:
        return [chars] # C

    head = chars[0]  # A
    tail = chars[1:] # BC
    tail_prms = get_permutations(tail) # C / BC CB

    prms = []
    for tail in tail_prms:
        for k in range(len(tail) + 1):
            prms.append(tail[0:k] + head + tail[k:])

    return prms # BC CB

print("Permutations without repetition:")
P1 = get_permutations('ABC')
P2 = get_permutations('ABCD')
print(len(P1), ' '.join(P1)) # 6  ABC BAC BCA ACB CAB CBA
print(len(P2), ' '.join(P2)) # 24 24 ABCD BACD BCAD BCDA ACBD ...

Questions    
Head-tail, Combinations