Source
Simple Pig Latin - Codewars
My solution
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| import doctest
import pytest
from os import system
def rindex_alnum(mystr: str) -> int:
'''Return index of the last alphanumeric character.
>>> rindex_alnum('foo!')
2
'''
slen: int = len(mystr) - 1
while slen > 0:
if not mystr[slen].isalnum():
slen -= 1
else:
break
return slen
def pig_latin(mystr: str) -> str:
'''Given a string, piglatinify it.
>>> pig_latin('foobar')
'oobarfay'
'''
if not mystr:
return mystr
last_alnum: int = rindex_alnum(mystr)
trimmed: str = mystr[:last_alnum + 1]
end: str = mystr[last_alnum + 1:] if trimmed != mystr else ''
trimmed = ' '.join(f'{x[1:]}{x[0]}ay' for x in trimmed.split(' '))
return f'{trimmed}{end}'
def test_mytest():
assert pig_latin('') == '', 'failed on empty string'
assert pig_latin('a') == 'aay', 'failed on one-char string'
assert pig_latin('ab') == 'baay'
assert pig_latin('foo') == 'oofay'
assert pig_latin('pig') == 'igpay'
assert pig_latin('foo bar') == 'oofay arbay'
assert pig_latin('foo bar !') == 'oofay arbay !'
def test_provided():
assert pig_latin('Hello world !') == 'elloHay orldway !'
assert pig_latin('Pig latin is cool') == 'igPay atinlay siay oolcay'
if __name__ == '__main__':
pytest.main(['-q', __file__])
doctest.testmod(optionflags=doctest.FAIL_FAST)
system(f'mypy {__file__} --ignore-missing-imports')
system(f'flake8 {__file__}')
|