import collections
import random
import statistics

letters = 'abcdefghijklmnopqrstuvwxyz'

def blum(f, g, s):
  out = [0] * len(s)
  out[0] = g[(f[s[0]] + f[s[-1]]) % 10]
  for i in range(1, len(s)):
    out[i] = g[(out[i-1] + f[s[i]]) % 10]
  return out

def genkey(seed=None):
  random.seed(seed)
  f = { c: random.randrange(10) for c in letters }
  perm = [ i for i in range(10) ]
  random.shuffle(perm)
  g = { i: perm[i] for i in range(10) }
  return (f, g)

def extendg(f, g, cleartext, hashed):
  g = { k: v for k, v in g.items() }
  for c, fc in f.items():
    for i in range(1, len(cleartext)):
      if cleartext[i] == c:
        e, d = hashed[i - 1], hashed[i]
        g[(e + fc) % 10] = d
  return g

def extendf(f, g, cleartext, hashed):
  f = { k: v for k, v in f.items() }
  for d, b in g.items():
    for i in range(1, len(hashed)):
      if hashed[i] == b:
        a, c = hashed[i - 1], cleartext[i]
        f[c] = (d - a) % 10
  return f

def derive(ps, cleartext, hashed):
  out = []
  for f, g in ps:
    while True:
      g = extendg(f, g, cleartext, hashed)
      nf = extendf(f, g, cleartext, hashed)
      if f == nf: break
      f = nf
    if len(f) < 26 or len(g) < 10 or blum(f, g, cleartext) == hashed:
      out.append((f, g))
  return out

def crack(kf, kg, chunk_len=50):
  characters = 0
  ct = ''.join(random.choice(letters) for _ in range(chunk_len))
  c = collections.Counter(ct).most_common(1)[0][0]
  possibilities = [ ({ c: i }, {}) for i in range(10) ]
  while (len(possibilities) != 1 or
         len(possibilities[0][0]) != 26 or 
         len(possibilities[0][1]) != 10):
    possibilities = derive(possibilities, ct, blum(kf, kg, ct))
    ct = ''.join(random.choice(letters) for _ in range(chunk_len))
    characters += chunk_len
  assert blum(possibilities[0][0], possibilities[0][1], ct) == blum(kf, kg, ct)
  return characters

for chunk in [5, 10, 20, 40, 60, 80, 100, 120, 140, 160]:
  cs = []
  for seed in range(1000):
    f, g = genkey(seed)
    cs.append(crack(f, g, chunk))
  print(chunk, statistics.mean(cs), statistics.median(cs))
