One of the first chain emails I ever received was about a supposed Cambridge  University study that suggests your brain can read words no matter what order the letters are in, as long as the first and last letters of each word are correct.

Your task is to **create a function that can take any string and randomly jumble the letters within each word while leaving the first and last letters of the word in place.**

For example,
    
    mixwords('Winter is coming') // returns 'Wntier is cminog' or 'Wtiner is conimg'
    mixwords('Hey, friends!') // returns 'Hey, fierdns!' or 'Hey, fernids!'

* All punctuation should remain in place
* Words smaller than 3 letters should not change
* Letters must be randomly moved (and so calling the function multiple times with the same string should return different values
* Parameters that are not strings should return undefined

The tests do the following things to ensure a valid string is returned:
    
1. Check that the string returned is not equal to the string passed (you may have to revalidate the solution if your function randomly returns the same string)
2. Check that first and last letters of words remain in place
3. Check that punctuation remains in place
4. Checks string length remains the same
5. Checks the function returns `undefined` for non-strings
6. Checks that word interiors (the letters between the first and last) maintain the same letters, albeit in a different order
7. Checks that letters are randomly assigned.

Difficulty: introductory

Starter code:

def mix_words(s):
	

Solutions:
import re
from random import sample

def mix_words(string):
    return re.sub(
        r'(?<=[a-zA-Z])([a-zA-Z]{2,})(?=[a-zA-Z])',
        lambda match: ''.join(sample(match.group(1), len(match.group(1)))),
        string)


from re import sub
from random import shuffle

def scramble(m):
    s = list(m.group())
    shuffle(s)
    return ''.join(s)

def mix_words(string):
    return sub('\B\w+\B', scramble, string)

import random
import re
import numpy as np

def mix_words(text):
    words_list = text.split()
    result_list = []

    for word in words_list:
        punctuation = ''.join(re.findall("\W", word))
        # punctuation = ''.join(re.findall("[^a-zA-Z]", word))  #equivalent to line above, get non-alphanumeric characters
        
        # create 2 lists, the 1st as the word split into a list, the 2nd an empty list of the same size that will
        # be get filled in sequentially
        text_list = [x for x in word]
        blank_list = ['' for x in range(len(word))]

        # need to isolate the middle part of the word (not 1st, last, punctuation)
        # assumption that any punctuation is at the end of each word. e.g. hello!, not hel?lo
        lst = [x for x in range(1, ( len(text_list) - (len(punctuation) + 1) ))]
        lst2 = lst[:]

        # if there is only 1 randmisable character its position can't be changed  
        if len(lst) > 1:
            # shuffle the order of the randomisable characters, shuffle could return the same order (by chance) so perform
            # this operation inside a while loop
            while (np.array_equal(lst,lst2)):
                random.shuffle(lst2)

            # j variable is a counter for which element to take from the randomised characters list
            j = 0
            for i in range(len(word)):
                if i == 0: 
                    # Keep first character in position
                    blank_list[i] = text_list[i]
                elif (len(punctuation) > 0) and ((text_list[i] in punctuation) or (text_list[i+1] in punctuation)):
                    # Keep punctuation and last character (if there's punctuation) in position
                    blank_list[i] = text_list[i]
                elif (len(punctuation) == 0) and (i == len(word)-1):
                    # Keep last character in position, if no punctuation
                    blank_list[i] = text_list[i]
                else:
                    # if the character is not punctuation or first/last character then take from the randomised list
                    blank_list[i] = text_list[lst2[j]]
                    j += 1

            new_text = ''.join(blank_list)
            # join the individual list elements for each word together to create the randomised word
            result_list.append(new_text)
            # append the 
        else:
            # if the word is less than 3 characters return the original word
            result_list.append(word)
    result = ''.join([item + ' ' for item in result_list]).strip()
    
    if (len(lst) > 2) & (result == text):
        result = mix_words(text)
            
    return result

import random
import re

def sub(m):
    s = m.group()
    xs = list(s[1:-1])
    mid = list(s[1:-1])
    while mid == xs:
        random.shuffle(mid)
    return s[0] + ''.join(mid) + s[-1]

def mix_words(s):
    if not isinstance(s, str):
        return None
    return re.sub('[a-z]{4,}', sub, s, flags=re.I)

import re
from random import shuffle

def mix_words(string):
    def mix(s):
        s = list(s)
        shuffle(s)
        return "".join(s)
    
    return re.sub("(\w)(\w{2,})(\w)", lambda m: m.group(1) + mix(m.group(2)) + m.group(3), string)

from random import shuffle
import re

def scrambler(m):
    lst = list(m.group())
    shuffle(lst)
    return ''.join(lst)

def mix_words(s):
    if isinstance(s, str): return re.sub(r'(?<=\w)\w{2,}(?=\w)', scrambler, s)

import re
from random import sample
def mix_words(strng):
    if type(strng)!=str:
        return None
    return re.sub(r'[A-Za-z]{4,}',fu,strng)

def fu(w):
    w = w.group()
    r = w[1:-1]
    while r==w[1:-1]:
        r = ''.join(sample(r,len(r)))
    return w[0]+r+w[-1]

def mix_words(words):
  import re, random
  
  def slacrbme(word):
    mid = [c for c in word[1:-1]]
    random.shuffle(mid)
    return word[0] + ''.join(mid) + word[-1]
  
  return re.sub(r'(\w{3,})', lambda m: slacrbme(m.groups()[0]), words)

from random import shuffle

def mix_words(s):
    if type(s) != str:
        return "undefined"
    else:
        splitter = s.split(' ')
        for i, word in enumerate(splitter):
            punctuation = not word[-1].isalpha()
            if len(word) > 3 + punctuation:
                middle = list(word[1:-1 - punctuation])
                while middle == list(word[1:-1 - punctuation]):
                    shuffle(middle)
                splitter[i] = word[0] + ''.join(middle) + word[-1  - punctuation:]
        return ' '.join(splitter)