Skip to content

Instantly share code, notes, and snippets.

@yngwie74
Last active December 15, 2015 05:29
Show Gist options
  • Save yngwie74/5209254 to your computer and use it in GitHub Desktop.
Save yngwie74/5209254 to your computer and use it in GitHub Desktop.
Word wrap kata in Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
def wrap(s, w):
def split(s, at, gap=0):
return s[:at] + '\n' + wrap(s[at + gap:], w)
if w <= 0 or len(s) <= w:
return s
p = s.rfind(' ', 0, w + 1)
# refactoring... refactoring...
return split(s, at=p, gap=1) if p >= 0 else split(s, at=w)
class testWrap(unittest.TestCase):
def test_wrap(self):
# degenerate case
self.assertEqual('', wrap('', 1))
# check for zero length
self.assertEqual('1', wrap('1', 0))
# s fits in w
self.assertEqual('1', wrap('1', 1))
# s still fits in w
self.assertEqual('1 2', wrap('1 2', 3))
# s no longer fits in w, but has space before w
self.assertEqual('1\n23', wrap('1 23', 3))
# s has space at w
self.assertEqual('12\n3', wrap('12 3', 3))
# s has more than one space
self.assertEqual('12\n3 4', wrap('12 3 4', 3))
self.assertEqual('1 2\n3 4', wrap('1 2 3 4', 3))
# s is long enough to wrap twice: at w...
self.assertEqual('123\n456\n7', wrap('123 456 7', 3))
self.assertEqual('1 2\n3 4\n5', wrap('1 2 3 4 5', 3))
# ... and before w...
self.assertEqual('12\n34\n567', wrap('12 34 567', 3))
self.assertEqual('1\n23\n456\n7', wrap('1 23 456 7', 3))
# s no longer fits in w, but has no space either
self.assertEqual('123\n4', wrap('1234', 3))
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment