WeixiangYan/CodeTransOcean huggingface dataset:
Task: Primes whose sum of digits is 25







Python: 

from itertools import takewhile



def primesWithGivenDigitSum(below, n):
    
    return list(
        takewhile(
            lambda x: below > x,
            (
                x for x in primes()
                if n == sum(int(c) for c in str(x))
            )
        )
    )




def main():
    
    matches = primesWithGivenDigitSum(5000, 25)
    print(
        str(len(matches)) + (
            ' primes below 5000 with a decimal digit sum of 25:\n'
        )
    )
    print(
        '\n'.join([
            ' '.join([str(x).rjust(4, ' ') for x in xs])
            for xs in chunksOf(4)(matches)
        ])
    )





def chunksOf(n):
    
    def go(xs):
        return (
            xs[i:n + i] for i in range(0, len(xs), n)
        ) if 0 < n else None
    return go



def primes():
    
    n = 2
    dct = {}
    while True:
        if n in dct:
            for p in dct[n]:
                dct.setdefault(n + p, []).append(p)
            del dct[n]
        else:
            yield n
            dct[n * n] = [n]
        n = 1 + n



if __name__ == '__main__':
    main()
Task: Numbers with prime digits whose sum is 13







Python: from collections import deque

def prime_digits_sum(r):
    q = deque([(r, 0)])
    while q:
        r, n = q.popleft()
        for d in 2, 3, 5, 7:
            if d >= r:
                if d == r: yield n + d
                break
            q.append((r - d, (n + d) * 10))

print(*prime_digits_sum(13))
Task: Circular primes







Python: import random

def is_Prime(n):
    
    if n!=int(n):
        return False
    n=int(n)
    
    if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
        return False

    if n==2 or n==3 or n==5 or n==7:
        return True
    s = 0
    d = n-1
    while d%2==0:
        d>>=1
        s+=1
    assert(2**s * d == n-1)

    def trial_composite(a):
        if pow(a, d, n) == 1:
            return False
        for i in range(s):
            if pow(a, 2**i * d, n) == n-1:
                return False
        return True

    for i in range(8):
        a = random.randrange(2, n)
        if trial_composite(a):
            return False

    return True

def isPrime(n: int) -> bool:
    
    
    if (n <= 1) :
        return False
    if (n <= 3) :
        return True
    
    
    if (n % 2 == 0 or n % 3 == 0) :
        return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

def rotations(n: int)-> set((int,)):
    
    a = str(n)
    return set(int(a[i:] + a[:i]) for i in range(len(a)))

def isCircular(n: int) -> bool:
    
    return all(isPrime(int(o)) for o in rotations(n))

from itertools import product

def main():
    result = [2, 3, 5, 7]
    first = '137'
    latter = '1379'
    for i in range(1, 6):
        s = set(int(''.join(a)) for a in product(first, *((latter,) * i)))
        while s:
            a = s.pop()
            b = rotations(a)
            if isCircular(a):
                result.append(min(b))
            s -= b
    result.sort()
    return result

assert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main()


repunit = lambda n: int('1' * n)

def repmain(n: int) -> list:
    
    result = []
    i = 2
    while len(result) < n:
        if is_Prime(repunit(i)):
            result.append(i)
        i += 1
    return result

assert [2, 19, 23, 317, 1031] == repmain(5)
Task: Frobenius numbers







Python: 

def isPrime(v):
  if v <= 1:
    return False
  if v < 4:
    return True
  if v % 2 == 0:
    return False
  if v < 9:
    return True
  if v % 3 == 0:
    return False
  else:
    r = round(pow(v,0.5))
    f = 5
    while f <= r:
      if v % f == 0 or v % (f + 2) == 0:
        return False
      f += 6
    return True

pn = 2
n = 0
for i in range(3, 9999, 2):
  if isPrime(i):
    n += 1
    f = (pn * i) - pn - i
    if f > 10000:
      break
    print (n, ' => ', f)
    pn = i
Task: Integer roots







Python: def root(a, b):
    if b < 2:
        return b
    a1 = a - 1
    c = 1
    d = (a1 * c + b // (c ** a1)) // a
    e = (a1 * d + b // (d ** a1)) // a
    while c not in (d, e):
        c, d, e = d, e, (a1 * e + b // (e ** a1)) // a
    return min(d, e)


print("First 2,001 digits of the square root of two:\n{}".format(
    root(2, 2 * 100 ** 2000)
))
Task: Fortunate numbers







Python: from sympy.ntheory.generate import primorial
from sympy.ntheory import isprime

def fortunate_number(n):
    
    
    
    i = 3
    primorial_ = primorial(n)
    while True:
        if isprime(primorial_ + i):
            return i
        i += 2

fortunate_numbers = set()
for i in range(1, 76):
    fortunate_numbers.add(fortunate_number(i))


first50 = sorted(list(fortunate_numbers))[:50]

print('The first 50 fortunate numbers:')
print(('{:<3} ' * 10).format(*(first50[:10])))
print(('{:<3} ' * 10).format(*(first50[10:20])))
print(('{:<3} ' * 10).format(*(first50[20:30])))
print(('{:<3} ' * 10).format(*(first50[30:40])))
print(('{:<3} ' * 10).format(*(first50[40:])))
Task: Modulinos







Python: 



def meaning_of_life():
  return 42

if __name__ == "__main__":
  print("Main: The meaning of life is %s" % meaning_of_life())
Task: Table creation







Python: >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute()
<sqlite3.Cursor object at 0x013263B0>
>>> 
c.execute()

<sqlite3.Cursor object at 0x013263B0>
>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ]:
	c.execute('insert into stocks values (?,?,?,?,?)', t)

	
<sqlite3.Cursor object at 0x013263B0>
<sqlite3.Cursor object at 0x013263B0>
<sqlite3.Cursor object at 0x013263B0>
>>> 
>>> c = conn.cursor()
>>> c.execute('select * from stocks order by price')
<sqlite3.Cursor object at 0x01326530>
>>> for row in c:
	print row

	
(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)
(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)
(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)
(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)
>>>
Task: Nice primes







Python: nicePrimes( s, e ) = { local( m );
    forprime( p = s, e,
        m = p;                      \\
        while( m > 9,               \\   m == p mod 9
            m = sumdigits( m ) );   \\
        if( isprime( m ),
            print1( p, " " ) ) ); 
}
Task: Random Latin squares







Python: from random import choice, shuffle
from copy import deepcopy

def rls(n):
    if n <= 0:
        return []
    else:
        symbols = list(range(n))
        square = _rls(symbols)
        return _shuffle_transpose_shuffle(square)


def _shuffle_transpose_shuffle(matrix):
    square = deepcopy(matrix)
    shuffle(square)
    trans = list(zip(*square))
    shuffle(trans)
    return trans


def _rls(symbols):
    n = len(symbols)
    if n == 1:
        return [symbols]
    else:
        sym = choice(symbols)
        symbols.remove(sym)
        square = _rls(symbols)
        square.append(square[0].copy())
        for i in range(n):
            square[i].insert(i, sym)
        return square

def _to_text(square):
    if square:
        width = max(len(str(sym)) for row in square for sym in row)
        txt = '\n'.join(' '.join(f"{sym:>{width}}" for sym in row)
                        for row in square)
    else:
        txt = ''
    return txt

def _check(square):
    transpose = list(zip(*square))
    assert _check_rows(square) and _check_rows(transpose), \
        "Not a Latin square"

def _check_rows(square):
    if not square:
        return True
    set_row0 = set(square[0])
    return all(len(row) == len(set(row)) and set(row) == set_row0
               for row in square)


if __name__ == '__main__':
    for i in [3, 3,  5, 5, 12]:
        square = rls(i)
        print(_to_text(square))
        _check(square)
        print()
Task: Teacup rim text







Python: 

from itertools import chain, groupby
from os.path import expanduser
from functools import reduce



def main():
    
    print('\n'.join(
        concatMap(circularGroup)(
            anagrams(3)(
                
                lines(readFile('~/mitWords.txt'))
            )
        )
    ))



def anagrams(n):
    
    def go(ws):
        def f(xs):
            return [
                [snd(x) for x in xs]
            ] if n <= len(xs) >= len(xs[0][0]) else []
        return concatMap(f)(groupBy(fst)(sorted(
            [(''.join(sorted(w)), w) for w in ws],
            key=fst
        )))
    return go



def circularGroup(ws):
    
    lex = set(ws)
    iLast = len(ws) - 1
    
    
    (i, blnCircular) = until(
        lambda tpl: tpl[1] or (tpl[0] > iLast)
    )(
        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))
    )(
        (0, False)
    )
    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []



def isCircular(lexicon):
    
    def go(w):
        def f(tpl):
            (i, _, x) = tpl
            return (1 + i, x in lexicon, rotated(x))

        iLast = len(w) - 1
        return until(
            lambda tpl: iLast < tpl[0] or (not tpl[1])
        )(f)(
            (0, True, rotated(w))
        )[1]
    return go



def allRotations(w):
    
    return takeIterate(len(w) - 1)(
        rotated
    )(w)





def concatMap(f):
    
    def go(xs):
        return chain.from_iterable(map(f, xs))
    return go



def fst(tpl):
    
    return tpl[0]



def groupBy(f):
    
    def go(xs):
        return [
            list(x[1]) for x in groupby(xs, key=f)
        ]
    return go



def lines(s):
    
    return s.splitlines()



def mapAccumL(f):
    
    def go(a, x):
        tpl = f(a[0], x)
        return (tpl[0], a[1] + [tpl[1]])
    return lambda acc: lambda xs: (
        reduce(go, xs, (acc, []))
    )



def readFile(fp):
    
    with open(expanduser(fp), 'r', encoding='utf-8') as f:
        return f.read()



def rotated(s):
    
    return s[1:] + s[0]



def snd(tpl):
    
    return tpl[1]



def takeIterate(n):
    
    def go(f):
        def g(x):
            def h(a, i):
                v = f(a) if i else x
                return (v, v)
            return mapAccumL(h)(x)(
                range(0, 1 + n)
            )[1]
        return g
    return go



def until(p):
    
    def go(f):
        def g(x):
            v = x
            while not p(v):
                v = f(v)
            return v
        return g
    return go



if __name__ == '__main__':
    main()
Task: Fairshare between two and more







Python: from itertools import count, islice

def _basechange_int(num, b):
    
    if num == 0:
        return [0]
    result = []
    while num != 0:
        num, d = divmod(num, b)
        result.append(d)
    return result[::-1]

def fairshare(b=2):
    for i in count():
        yield sum(_basechange_int(i, b)) % b

if __name__ == '__main__':
    for b in (2, 3, 5, 11):
        print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")
Task: Esthetic numbers







Python: from collections import deque
from itertools import dropwhile, islice, takewhile
from textwrap import wrap
from typing import Iterable, Iterator


Digits = str  


def esthetic_nums(base: int) -> Iterator[int]:
    
    queue: deque[tuple[int, int]] = deque()
    queue.extendleft((d, d) for d in range(1, base))
    while True:
        num, lsd = queue.pop()
        yield num
        new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)
        num *= base  
        queue.extendleft((num + d, d) for d in new_lsds)


def to_digits(num: int, base: int) -> Digits:
    
    digits: list[str] = []
    while num:
        num, d = divmod(num, base)
        digits.append("0123456789abcdef"[d])
    return "".join(reversed(digits)) if digits else "0"


def pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:
    
    joined = ", ".join(it)
    lines = wrap(joined, width=width - indent)
    for line in lines:
        print(f"{indent*' '}{line}")
    print()


def task_2() -> None:
    nums: Iterator[int]
    for base in range(2, 16 + 1):
        start, stop = 4 * base, 6 * base
        nums = esthetic_nums(base)
        nums = islice(nums, start - 1, stop)  
        print(
            f"Base-{base} esthetic numbers from "
            f"index {start} through index {stop} inclusive:\n"
        )
        pprint_it(to_digits(num, base) for num in nums)


def task_3(lower: int, upper: int, base: int = 10) -> None:
    nums: Iterator[int] = esthetic_nums(base)
    nums = dropwhile(lambda num: num < lower, nums)
    nums = takewhile(lambda num: num <= upper, nums)
    print(
        f"Base-{base} esthetic numbers with "
        f"magnitude between {lower:,} and {upper:,}:\n"
    )
    pprint_it(to_digits(num, base) for num in nums)


if __name__ == "__main__":
    print("======\nTask 2\n======\n")
    task_2()

    print("======\nTask 3\n======\n")
    task_3(1_000, 9_999)

    print("======\nTask 4\n======\n")
    task_3(100_000_000, 130_000_000)
Task: Descending primes







Python: from sympy import isprime

def descending(xs=range(10)):
    for x in xs:
        yield x
        yield from descending(x*10 + d for d in range(x%10))

for i, p in enumerate(sorted(filter(isprime, descending()))):
    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n')

print()
Task: Kolakoski sequence







Python: import itertools

def cycler(start_items):
	return itertools.cycle(start_items).__next__

def _kolakoski_gen(start_items):
    s, k = [], 0
    c = cycler(start_items)
    while True:
        c_next = c()
        s.append(c_next)
        sk = s[k]
        yield sk
        if sk > 1:
            s += [c_next] * (sk - 1)
        k += 1

def kolakoski(start_items=(1, 2), length=20):
    return list(itertools.islice(_kolakoski_gen(start_items), length))

def _run_len_encoding(truncated_series):
    return [len(list(group)) for grouper, group in itertools.groupby(truncated_series)][:-1]

def is_series_eq_its_rle(series):
    rle = _run_len_encoding(series)
    return (series[:len(rle)] == rle) if rle else not series

if __name__ == '__main__':
    for start_items, length in [((1, 2), 20), ((2, 1), 20), 
                                ((1, 3, 1, 2), 30), ((1, 3, 2, 1), 30)]:
        print(f'\n
        s = kolakoski(start_items, length)
        print(f'  {s}')
        ans = 'YES' if is_series_eq_its_rle(s) else 'NO'
        print(f'  Does it look like a Kolakoski sequence: {ans}')
Task: Variable declaration reset







Python: s = [1, 2, 2, 3, 4, 4, 5]
 
for i in range(len(s)):
    curr = s[i]
    if i > 0 and curr == prev:
        print(i)
    prev = curr
Task: Sequence_ smallest number with exactly n divisors







Python: def divisors(n):
    divs = [1]
    for ii in range(2, int(n ** 0.5) + 3):
        if n % ii == 0:
            divs.append(ii)
            divs.append(int(n / ii))
    divs.append(n)
    return list(set(divs))


def sequence(max_n=None):
    n = 0
    while True:
        n += 1
        ii = 0
        if max_n is not None:
            if n > max_n:
                break
        while True:
            ii += 1
            if len(divisors(ii)) == n:
                yield ii
                break


if __name__ == '__main__':
    for item in sequence(15):
        print(item)
Task: Levenshtein distance_Alignment







Python: from difflib import ndiff

def levenshtein(str1, str2):
    result = ""
    pos, removed = 0, 0
    for x in ndiff(str1, str2):
        if pos<len(str1) and str1[pos] == x[2]:
          pos += 1
          result += x[2]
          if x[0] == "-":
              removed += 1
          continue
        else:
          if removed > 0:
            removed -=1
          else:
            result += "-"
    print(result)

levenshtein("place","palace")
levenshtein("rosettacode","raisethysword")
Task: Odd and square numbers







Python: import math
szamok=[]
limit = 1000

for i in range(1,int(math.ceil(math.sqrt(limit))),2):
    num = i*i
    if (num < 1000 and num > 99):
        szamok.append(num)

print(szamok)
Task: Words from neighbour ones







Python: 

import urllib.request
from collections import Counter
 
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
 
dictionary = open("unixdict.txt","r")
 
wordList = dictionary.read().split('\n')
 
dictionary.close()
 
filteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]

for word in filteredWords[:-9]:
  position = filteredWords.index(word)
  newWord = "".join([filteredWords[position+i][i] for i in range(0,9)])
  if newWord in filteredWords:
   print(newWord)
Task: Sum of square and cube digits of an integer are primes







Python: 

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True

def digSum(n, b):
    s = 0
    while n:
        s += (n % b)
        n = n // b
    return s

if __name__ == '__main__':
    for n in range(11, 99):
        if isPrime(digSum(n**3, 10)) and isPrime(digSum(n**2, 10)):
            print(n, end = "  ")
Task: Dynamic variable names







Python: >>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
Task: Odd squarefree semiprimes







Python: 

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True


if __name__ == '__main__':
    for p in range(3, 999):
        if not isPrime(p):            
            continue
        for q in range(p+1, 1000//p):
            if not isPrime(q):
                continue
            print(p*q, end = " ");
Task: Primes with digits in nondecreasing order







Python: 

from operator import le
from itertools import takewhile



def monotonicDigits(base):
    
    def go(n):
        return monotonic(le)(
            showIntAtBase(base)(digitFromInt)(n)('')
        )
    return go



def monotonic(op):
    
    def go(xs):
        return all(map(op, xs, xs[1:]))
    return go




def main():
    
    xs = [
        str(n) for n in takewhile(
            lambda n: 1000 > n,
            filter(monotonicDigits(10), primes())
        )
    ]
    w = len(xs[-1])
    print(f'{len(xs)} matches for base 10:\n')
    print('\n'.join(
        ' '.join(row) for row in chunksOf(10)([
            x.rjust(w, ' ') for x in xs
        ])
    ))





def chunksOf(n):
    
    def go(xs):
        return (
            xs[i:n + i] for i in range(0, len(xs), n)
        ) if 0 < n else None
    return go



def digitFromInt(n):
    
    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (
        0 <= n < 36
    ) else '?'



def primes():
    
    n = 2
    dct = {}
    while True:
        if n in dct:
            for p in dct[n]:
                dct.setdefault(n + p, []).append(p)
            del dct[n]
        else:
            yield n
            dct[n * n] = [n]
        n = 1 + n




def showIntAtBase(base):
    
    def wrap(toChr, n, rs):
        def go(nd, r):
            n, d = nd
            r_ = toChr(d) + r
            return go(divmod(n, base), r_) if 0 != n else r_
        return 'unsupported base' if 1 >= base else (
            'negative number' if 0 > n else (
                go(divmod(n, base), rs))
        )
    return lambda toChr: lambda n: lambda rs: (
        wrap(toChr, n, rs)
    )



if __name__ == '__main__':
    main()
Task: Brilliant numbers







Python: from primesieve.numpy import primes
from math import isqrt
import numpy as np

max_order = 9
blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]

def smallest_brilliant(lb):
    pos = 1
    root = isqrt(lb)

    for blk in blocks:
        n = len(blk)
        if blk[-1]*blk[-1] < lb:
            pos += n*(n + 1)//2
            continue

        i = np.searchsorted(blk, root, 'left')
        i += blk[i]*blk[i] < lb

        if not i:
            return blk[0]*blk[0], pos

        p = blk[:i + 1]
        q = (lb - 1)//p
        idx = np.searchsorted(blk, q, 'right')

        sel = idx < n
        p, idx = p[sel], idx[sel]
        q = blk[idx]

        sel = q >= p
        p, q, idx = p[sel], q[sel], idx[sel]

        pos += np.sum(idx - np.arange(len(idx)))
        return np.min(p*q), pos

res = []
p = 0
for i in range(100):
    p, _ = smallest_brilliant(p + 1)
    res.append(p)

print(f'first 100 are {res}')

for i in range(max_order*2):
    thresh = 10**i
    p, pos = smallest_brilliant(thresh)
    print(f'Above 10^{i:2d}: {p:20d} at
Task: Calkin-Wilf sequence







Python: from fractions import Fraction
from math import floor
from itertools import islice, groupby


def cw():
    a = Fraction(1)
    while True:
        yield a
        a = 1 / (2 * floor(a) + 1 - a)

def r2cf(rational):
    num, den = rational.numerator, rational.denominator
    while den:
        num, (digit, den) = den, divmod(num, den)
        yield digit

def get_term_num(rational):
    ans, dig, pwr = 0, 1, 0
    for n in r2cf(rational):
        for _ in range(n):
            ans |= dig << pwr
            pwr += 1
        dig ^= 1
    return ans

          
if __name__ == '__main__':
    print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))
    x = Fraction(83116, 51639)
    print(f"\n{x} is the {get_term_num(x):_}'th term.")
Task: Prime words







Python: for i in range(65,123):
  check = 1
  for j in range(2,i):
    if i%j == 0:
     check = 0
  if check==1:
   print(chr(i),end='')
Task: Palindromic primes







Python: 

from itertools import takewhile



def palindromicPrimes():
    
    def p(n):
        s = str(n)
        return s == s[::-1]
    return (n for n in primes() if p(n))



def main():
    
    print('\n'.join(
        str(x) for x in takewhile(
            lambda n: 1000 > n,
            palindromicPrimes()
        )
    ))





def primes():
    
    n = 2
    dct = {}
    while True:
        if n in dct:
            for p in dct[n]:
                dct.setdefault(n + p, []).append(p)
            del dct[n]
        else:
            yield n
            dct[n * n] = [n]
        n = 1 + n



if __name__ == '__main__':
    main()
Task: Sylvester's sequence







Python: 

from functools import reduce
from itertools import count, islice



def sylvester():
    
    def go(n):
        return 1 + reduce(
            lambda a, x: a * go(x),
            range(0, n),
            1
        ) if 0 != n else 2

    return map(go, count(0))




def main():
    

    print("First 10 terms of OEIS A000058:")
    xs = list(islice(sylvester(), 10))
    print('\n'.join([
        str(x) for x in xs
    ]))

    print("\nSum of the reciprocals of the first 10 terms:")
    print(
        reduce(lambda a, x: a + 1 / x, xs, 0)
    )



if __name__ == '__main__':
    main()
Task: Harmonic series







Python: from  fractions import Fraction

def harmonic_series():
    n, h = Fraction(1), Fraction(1)
    while True:
        yield h
        h += 1 / (n + 1)
        n += 1

if __name__ == '__main__':
    from itertools import islice
    for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):
        print(n, '/', d)
Task: Reverse the gender of a string







Python: 

 
import re
male2female=u
 
re_nl=re.compile(r",[ \n]*")
m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ]
 
switch={}
words=[]
 
 
re_plural=re.compile("E*S$")
re_ES=re.compile("ES$")
 
def gen_pluralize(m,f):

  yield re_plural.sub("",m),re_plural.sub("",f)
  yield re_ES.sub("es",m),re_ES.sub("es",f)
  yield re_plural.sub("s",m),re_plural.sub("s",f)
 
def gen_capitalize_pluralize(m,f):
  for m,f in gen_pluralize(m,f):
    yield m.capitalize(), f.capitalize()
    yield m,f
 
def gen_switch_role_capitalize_pluralize(m,f):
  for m,f in gen_capitalize_pluralize(m,f):
    yield m,f
    yield f,m
 
for m,f in m2f:
  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):
    if xy not in switch: 
      switch[xy]=xx
      words.append(xy)
 
words="|".join(words)
 
re_word=re.compile(ur"\b("+words+ur")\b")
 
text=u
 
 
def rev_gender(text):
  text=re_word.split(text)
  return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]
 
print rev_gender(text)