forked from exercism/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
27 lines (20 loc) · 654 Bytes
/
example.py
File metadata and controls
27 lines (20 loc) · 654 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from math import ceil, sqrt
import sys
if sys.version_info[0] == 2:
from itertools import izip_longest as zip_longest
else:
from itertools import zip_longest
def encode(msg):
msg = _cleanse(msg)
square_size = int(ceil(sqrt(len(msg))))
square = _chunks_of(msg, square_size)
return ' '.join([''.join(col)
for col in zip_longest(*square, fillvalue=' ')])
def _cleanse(s):
"""Lowercase a string and remove punctuation and whitespace
"""
return ''.join([c for c in s if c.isalnum()]).lower()
def _chunks_of(s, n):
if len(s) <= n:
return [s]
return [s[:n]] + _chunks_of(s[n:], n)