# Do you ever wish you could talk like Siegfried of KAOS ?

## YES, of course you do!

https://en.wikipedia.org/wiki/Get_Smart



# Task

Write the function ```siegfried``` to replace the letters of a given sentence.

Apply the rules using the course notes below. Each week you will learn some more rules.

Und by ze fifz vek yu vil be speakink viz un aksent lik Siegfried viz no trubl at al!


# Lessons

## Week 1

* ```ci``` -> ```si```
* ```ce``` -> ```se```
* ```c``` -> ```k``` (except ```ch``` leave alone)

## Week 2

* ```ph``` -> ```f```

## Week 3

* remove trailing ```e``` (except for all 2 and 3 letter words)
* replace double letters with single letters (e.g. ```tt``` -> ```t```)

## Week 4

* ```th``` -> ```z```
* ```wr``` -> ```r```
* ```wh``` -> ```v```
* ```w``` -> ```v```

## Week 5

* ```ou``` -> ```u```
* ```an``` -> ```un```
* ```ing``` -> ```ink``` (but only when ending words)
* ```sm``` -> ```schm``` (but only when beginning words)



# Notes

* You must retain the case of the original sentence
* Apply rules strictly in the order given above
* Rules are cummulative. So for week 3 first apply week 1 rules, then week 2 rules, then week 3 rules

Difficulty: introductory

Starter code:

def siegfried(week, txt):
	

Solutions:
import re

PATTERNS = [re.compile(r'(?i)ci|ce|c(?!h)'),
            re.compile(r'(?i)ph'),
            re.compile(r'(?i)(?<!\b[a-z]{1})(?<!\b[a-z]{2})e\b|([a-z])\1'),
            re.compile(r'(?i)th|w[rh]?'),
            re.compile(r'(?i)ou|an|ing\b|\bsm')]
            
CHANGES  = {"ci": "si", "ce": "se", "c":"k",                     # Week 1
            "ph": "f",                                           # Week 2
            "th": "z",  "wr": "r",  "wh":  "v",   "w": "v",      # Week 4
            "ou": "u",  "an": "un", "ing": "ink", "sm": "schm"}  # Week 5

def change(m):
    tok = m.group(0)
    rep = CHANGES.get( tok.lower(), "" if None in m.groups() else m.group()[0] )        # default value used for week 3 only
    if tok[0].isupper(): rep = rep.title()
    return rep
        
def siegfried(week, txt):
    for n in range(week):
        txt = PATTERNS[n].sub(change, txt)
    return txt

import re
def siegfried(week, txt):
    if week >= 1: txt = re.sub('c(?!h)', 'k', re.sub('C(?!h)', 'K', txt.replace('ci', 'si').replace('Ci', 'Si').replace('ce', 'se').replace('Ce', 'Se')))
    if week >= 2: txt = txt.replace('ph', 'f').replace('Ph', 'F')
    if week >= 3: txt = re.sub('([A-z]{2,})e([-!?]+)', r'\1\2', ' '.join([x.rstrip('e') if len(x)>3 else x for x in re.sub(r'([A-z])\1', r'\1', txt, flags=re.I).split()]))
    if week >= 4: txt = txt.replace('th', 'z').replace('Th', 'Z').replace('wr', 'r').replace('Wr', 'R').replace('wh', 'v').replace('Wh', 'V').replace('w', 'v').replace('W', 'V')
    if week >= 5: txt =(' ' + txt + ' ').replace('ou', 'u').replace('Ou', 'U').replace('an', 'un').replace('An', 'Un').replace('ing ', 'ink ').replace(' sm', ' schm').replace(' Sm', ' Schm')      
    return txt.strip()

import re

def siegfried(week, txt):
    lessons = \
        [
            [   # Week 1
                (r'c(?=[ie])', { 'c':'s','C':'S' }),
                (r'c(?!h)', { 'c':'k','C':'K' })
            ],[ # Week 2
                (r'ph', { 'ph':'f','Ph': 'F' })
            ],[ # Week 3
                (r'(?<=\w\w\w)e(?=\W|\Z)', {'e':'','E':''}),
                (r'([a-z])\1',{})
            ],[ # Week 4
                (r'th', { 'th':'z','Th': 'Z' }),
                (r'wr', { 'wr':'r','Wr': 'R' }),
                (r'wh', { 'wh':'v','Wh': 'V' }),
                (r'w',  { 'w':'v','W': 'V' })
            ],[ # Week 5
                (r'ou', { 'ou':'u','Ou': 'U' }),
                (r'an', { 'an':'un','An': 'Un' }),
                (r'ing(?=\W|\Z)', { 'ing':'ink' }),
                (r'(?<=\W)sm|(?<=\A)sm', { 'sm':'schm','Sm': 'Schm' })
            ]
        ]
    
    result = txt
    for w in range(week):
        for rx,data in lessons[w]:
            repl = lambda m: data.get(m.group(0),m.group(0)[0])
            result = re.sub(rx,repl,result,flags=re.IGNORECASE)
    return result

import re
def siegfried(week, txt):
    if week == 1:
        txt = re.sub('ci', matchcase('si'), txt, flags=re.I)
        txt = re.sub('ce', matchcase('se'), txt, flags=re.I)
        txt = re.sub('(?!ch)[c]', matchcase('k'), txt, flags=re.I)
    elif week == 2:
        txt = siegfried(1, txt)
        txt = re.sub('ph', matchcase('f'), txt, flags=re.I)
    elif week == 3:
        txt = siegfried(2, txt)
        txt = re.sub(r'(?<=\w{3})e\b', '', txt)
        txt = re.sub(r'([a-z])\1', r'\1', txt, flags=re.I)
    elif week == 4:
        txt = siegfried(3, txt)
        txt = re.sub('th', matchcase('z'), txt, flags=re.I)
        txt = re.sub('wr', matchcase('r'), txt, flags=re.I)
        txt = re.sub('wh|w', matchcase('v'), txt, flags=re.I)
    elif week == 5:
        txt = siegfried(4, txt)
        txt = re.sub('ou', 'u', txt)
        txt = re.sub('an', matchcase('un'), txt, flags=re.I)
        txt = re.sub(r'ing\b', matchcase('ink'), txt, flags=re.I)
        txt = re.sub(r'\bsm', matchcase('schm'), txt, flags=re.I)
    return txt
    
def matchcase(word):
        def replace(m):
            text = m.group()
            if text.isupper():
                return word.upper()
            elif text.islower():
                return word.lower()
            elif text[0].isupper():
                return word.capitalize()
            else:
                return word
        return replace


RULES = [
    ['ci si', 'ce se', 'c(?!h) k'],
    ['ph f'],
    [r'(?<=\w{3})e+\b ', r'([a-z])\1 \1'],
    ['th z', 'wr r', 'wh v', 'w v'],
    ['ou u', 'an un', r'ing\b ink', r'\bsm schm'],
]

def siegfried(week, txt):
    import re
    
    def keep_case(repl):
        def wrapper(m):
            ref = re.match(r'\\(\d)', repl)
            strng = m.group(int(ref.group(1))) if ref else repl
            g = m.group(0)
            if g.islower(): return strng.lower()
            if g.isupper(): return strng.upper()
            if g.istitle(): return strng.title()
            return strng
        return wrapper

    for rules in RULES[:week]:
        for rule in rules:
            src, repl = rule.split(' ')
            txt = re.sub(src, keep_case(repl), txt, flags=re.I)
    return txt

import re
def siegfried(week, s):
    d = {'ph': 'f', 'Ph': 'F','ci': 'si', 'ce': 'se', 'c': 'k', 'Ci': 'Si', 'Ce': 'Se', 'C': 'K','XX':'ch','xx':'Ch','ch':'XX','Ch':'xx','th': 'z', 'wr': 'r', 'wh': 'v', 'w': 'v', 'Th': 'Z', 
        'Wr': 'R', 'Wh': 'V', 'W': 'V','ou': 'u', 'an': 'un', 'ing': 'ink', 'sm': 'schm', 'Ou': 'U', 'An': 'Un', 'Ing': 'Ink', 'Sm': 'Schm'}
    week1=lambda s:re.sub(r'(xx)',lambda x:d[x.group()],re.sub(r'(ci|ce|c)',lambda x:d[x.group()],re.sub(r'(Ch|ch)',lambda x:d[x.group()] ,s),flags=re.I),flags=re.I)
    week2=lambda s:re.sub(r'ph', lambda x: d[x.group()], s, flags=re.I)
    week3=lambda s:re.sub(r'([a-zA-Z])\1', r'\1', re.sub(r'\b([a-zA-Z]+e+)\b',lambda x:x.group()if len(x.group())<=3 else x.group().rstrip('e'),s,flags=re.I), flags=re.I)
    week4=lambda s:re.sub(r'(th|wr|wh|w)', lambda x: d[x.group()], s, flags=re.I)
    week5=lambda s:re.sub(r'(ing(?= )|(?<= )sm)',lambda x:d[x.group()],re.sub(r'(ing$|^sm)',lambda x:d[x.group()],re.sub(r'(ou|an)',lambda x:d[x.group()],s,flags=re.I),flags=re.I),flags=re.I)
    li = [week1, week2, week3, week4, week5]
    for i in li[:week] : s = i(s)
    return s

def siegfried(week, txt):

    import re

    dict_week = \
        {
            1: {'Ci': 'Si', 'Ce': 'Se', 'Ch': 'Xxx', 'C': 'K', 'Xxx': 'Ch',
                'ci': 'si', 'ce': 'se', 'ch': 'xxx', 'c': 'k', 'xxx': 'ch'},
            2: {'Ph': 'F', 'ph': 'f'},
            3: {'': ''},
            4: {'Th': 'Z', 'Wr': 'R', 'Wh': 'V', 'W': 'V',
                'th': 'z', 'wr': 'r', 'wh': 'v', 'w': 'v'},
            5: {'Ou': 'U', 'An': 'Un', 'ou': 'u', 'an': 'un'}
        }

    dd = {}
    for i in range(1, week + 1):
        dd.update(dict_week[i])

    for k, v in dd.items():
        txt = txt.replace(k, v)

    if week >= 3:
        txt = ''.join(re.sub(r'e$', '', i) if len(i) > 3 else i for i in re.split(r'(\W)', txt))
        double_l = {re.search(r'([a-z])\1', i).group(0) for i in txt.lower().split() if re.search(r'([a-z])\1', i)}
        for i in double_l:
            txt = txt.replace(i, i[0])
            txt = txt.replace(i[0].upper() + i[1], i[0].upper())

    if week == 5:
        txt = ' '.join(re.sub(r'ing$', 'ink', i, flags=re.IGNORECASE) for i in txt.split())
        txt = ' '.join(re.sub(r'^sm', 'Schm', i, flags=re.IGNORECASE) for i in txt.split())

    return txt

import re


def siegfried(week, txt):
    weeks_have_passed = {0: week_one, 1: week_two, 2: week_three, 3: week_four, 4: week_five}

    for counter in range(0, week):

        txt = weeks_have_passed[counter](txt)
    
    return txt

def week_one(txt):

    letter_list = list(txt)

    copy_reverse_letter_list = letter_list.copy()


    last_letter = ''

    count = -1

    for letter in copy_reverse_letter_list[::-1]:

        lowercase_letter = letter.lower()

        if lowercase_letter == 'c':
            lowercase_letter += last_letter

            if letter.isupper():
                dict_to_know = {'ci': 'S', 'ce': 'S', 'ch': 'C'}
                to_return = 'K'
            else:
                dict_to_know = {'ci': 's', 'ce': 's', 'ch': 'c'}
                to_return = 'k'

            letter_list[count] = dict_to_know.get(lowercase_letter, to_return)

        count -= 1
        last_letter = letter

    final_txt = ''.join(letter_list)

    return final_txt


def week_two(txt):

    letter_list = list(txt)

    copy_letter_list = letter_list.copy()
    copy_letter_list.append('')

    fix_position = 0

    for counter, letter in enumerate(copy_letter_list[:-1]):

        lowercase_letter = letter.lower()

        next_letter = copy_letter_list[counter+1]
        lowcase_next_letter = next_letter.lower()

        if lowercase_letter == 'p' and lowcase_next_letter == 'h':

            counter -= fix_position

            if letter.isupper():
                to_change = 'F'
            else:
                to_change = 'f'

            letter_list[counter: counter + 2] = to_change

            fix_position += 1

    new_txt = ''.join(letter_list)

    return new_txt


def week_three(txt):
    trailling_e = r'[a-zA-Z]{3,}e\b'

    trailling_list = re.findall(trailling_e, txt)

    new_txt = txt

    for trailling_e_word in trailling_list:
        new_txt = new_txt.replace(trailling_e_word, trailling_e_word[:-1])

    letter_list = list(new_txt)

    copy_letter_list = letter_list.copy()

    last_letter = ''

    position = -1

    for letter in copy_letter_list[::-1]:

        lowercase_letter = letter.lower()

        if lowercase_letter == last_letter and lowercase_letter.isalpha():

            del letter_list[position+1]

            position += 1

        last_letter = lowercase_letter

        position -= 1

    final_txt = ''.join(letter_list)

    return final_txt



def week_four(txt):

    letter_list = list(txt)

    copy_reverse_letter_list = letter_list.copy()

    last_letter = ''

    counter = -1

    for letter in copy_reverse_letter_list[::-1]:

        lowercase_letter = letter.lower()

        if lowercase_letter == 'w' or lowercase_letter == 't' and last_letter == 'h':
            lowercase_letter += last_letter

            if letter.isupper():
                dict_to_know = {'wr': 'R', 'wh': 'V', 'th': 'Z'}
                lonely_w = 'V'
            else:
                dict_to_know = {'wr': 'r', 'wh': 'v', 'th': 'z'}
                lonely_w = 'v'

            possible_last_letters = {'h', 'r'}

            if last_letter in possible_last_letters:
                letter_list[counter: counter+2] = dict_to_know[lowercase_letter]
                counter += 1

            else:
                letter_list[counter] = lonely_w

        counter -= 1
        last_letter = letter

    final_txt = ''.join(letter_list)

    return final_txt


def week_five(txt):
    letter_list = list(txt)

    copy_reverse_letter_list = letter_list.copy()

    last_letter = ''

    counter = -1

    for letter in copy_reverse_letter_list[::-1]:
        lowercase_letter = letter.lower()

        if lowercase_letter == 'o' and last_letter == 'u':
            lowercase_or_uppercase = {'o': 'u', 'O': 'U'}

            letter_list[counter: counter+2] = lowercase_or_uppercase[letter]

            counter += 1

        elif lowercase_letter == 'a' and last_letter == 'n':
            lowercase_or_uppercase_2 = {'a': 'u', 'A': 'U'}

            letter_list[counter] = lowercase_or_uppercase_2[letter]

        last_letter = lowercase_letter

        counter -= 1

    first_txt = ''.join(letter_list)

    re_to_find_ing = r'[a-zA-Z]{1,}ing\b'

    all_words_ending_with_ing = re.findall(re_to_find_ing, first_txt)

    second_txt = first_txt

    for word in all_words_ending_with_ing:
        new_word = word[:-1] + 'k'
        second_txt = second_txt.replace(word, new_word)

    re_to_find_sm = r'\b[sS][mM][a-zA-Z]*'


    all_words_starting_with_sm = re.findall(re_to_find_sm, second_txt)

    third_txt = second_txt

    for word in all_words_starting_with_sm:
        new_word = word[0] + 'ch' + word[1:]
        third_txt = third_txt.replace(word, new_word)

    final_txt = third_txt

    return final_txt

def siegfried(week, txt):

    symbols = [' ', '.', '!', '-', '\n']

    if week >= 1:
        rules = [['ci', 'si'], ['Ci', 'Si'],
                ['ce', 'se'], ['Ce', 'Se'],
                ['ch', '$$'], ['Ch', '$%'],
                ['c', 'k'], ['C', 'K'],
                ['$$', 'ch'], ['$%', 'Ch']]
        for translation in rules:
            txt = txt.replace(translation[0], translation[1])

    if week >= 2:
        rules = [['ph', 'f'], ['Ph', 'F']]
        for translation in rules:
            txt = txt.replace(translation[0], translation[1])

    if week >= 3:
        for position, letter in enumerate(txt):
            if letter == 'e' and position == len(txt) - 1 \
                    and txt[position - 2] not in symbols \
                    and txt[position - 3] not in symbols:
                txt = txt[:position] + '$'
            elif letter == 'e' and position not in [0, 1, 2, len(txt) - 1] \
                    and txt[position + 1] in symbols \
                    and txt[position - 2] not in symbols \
                    and txt[position - 3] not in symbols:
                txt = txt[:position] + '$' + txt[position + 1:]
        txt = txt.replace('$', '')

        for position, letter in enumerate(txt):
            if txt[position].lower() == txt[position - 1].lower() \
                    and position != 0\
                    and letter.isalpha() \
                    and letter not in symbols:
                txt = txt[:position] + '$' + txt[position + 1:]
        txt = txt.replace('$', '')

    if week >= 4:
        rules = [['th', 'z'], ['Th', 'Z'],
                 ['wr', 'r'], ['Wr', 'R'],
                 ['wh', 'v'], ['Wh', 'V'],
                 ['w', 'v'], ['W', 'V']]
        for translation in rules:
            txt = txt.replace(translation[0], translation[1])

    if week >= 5:
        rules = [['ou', 'u'], ['Ou', 'U'],
                 ['an', 'un'], ['An', 'Un']]
        for translation in rules:
            txt = txt.replace(translation[0], translation[1])

        for position, letter in enumerate(txt):
            if letter == 'i' and position == len(txt) - 3 \
                    and txt[position + 1] == 'n' \
                    and txt[position + 2] == 'g':
                txt = txt[:position + 2] + '$' + txt[position + 3:]
            elif letter == 'i' \
                    and txt[position + 1] == 'n' \
                    and txt[position + 2] == 'g' \
                    and txt[position + 3] in symbols:
                txt = txt[:position + 2] + '$' + txt[position + 3:]
        txt = txt.replace('$', 'k')

        for position, letter in enumerate(txt):
            if letter == 'S' \
                    and txt[position + 1] == 'm' \
                    and (txt[position - 1] in symbols or position == 0):
                txt = txt[:position] + '$$' + txt[position + 2:]
        txt = txt.replace('$$', 'Schm')

    return txt

import re
def siegfried(week, txt):
    w = []
    t = txt.replace('ci', 'si').replace('Ci', 'Si').replace('ce', 'se').replace('Ce', 'Se').replace('c', 'k').replace('C', 'K').replace('kh', 'ch').replace('Kh', 'Ch')
    w.append(t)
    t = t.replace('ph', 'f').replace('Ph', 'F')
    w.append(t)
    t = re.sub(r'([A-Za-z])\1', r'\1', re.sub(r'([a-zA-Z]{3,})e\b', r'\1', t), flags = re.I)
    w.append(t)
    t = t.replace('th', 'z').replace('Th', 'Z').replace('wr', 'r').replace('Wr', 'R').replace('wh', 'v').replace('Wh', 'V').replace('w', 'v').replace('W', 'V')
    w.append(t)
    t = re.sub(r'\b(s|S)(m)', r'\1ch\2', re.sub(r'ing\b', r'ink', t.replace('ou', 'u').replace('an', 'un').replace('An', 'Un')))
    w.append(t)
    return w[week-1]