[Snark] Python procedure

Christopher Vollick 0 at psycoti.ca
Sat Nov 17 17:38:03 UTC 2018


On Wed, Oct 24, 2018 at 06:53:33PM -0500, Brian Chan wrote:
> #!/usr/bin/python3

Python 3?

> VOWELS = 'aeiou'
> CONSONANTS = 'bcdfghjklmnpqrstvwxyz'

Well named, straight forward, constants?

> def convert(s):
>  # rule 1
>  if s[0] in VOWELS or s.startswith('xr') or s.startswith('yt'):
>    return s + 'ay'

Comments tying the code back to problem statement?

>  # rule 2
>  if len(s) >= 2 and s[0] in CONSONANTS and s[1] in VOWELS:
>    return s[1:] + s[0] + 'ay'
>  if len(s) >= 3 and s[0] in CONSONANTS and s[1] in CONSONANTS and s[2] in VOWELS:
>    return s[2:] + s[0:2] + 'ay'
>  if len(s) >= 4 and s[0] in CONSONANTS and s[1] in CONSONANTS and s[2] in CONSONANTS and s[3] in VOWELS:
>    return s[3:] + s[0:3] + 'ay'

All in all, I find this code actually pretty easy to read and reason about.
Besides all `if`s instead of `if..elif` I think it's probably the most straight-forward way of solving the problem.
And if I were to read this without knowing the problem it'd probably only take me a few minutes to deduce what problem this was solving.

The use of string slicing everywhere is maybe a little interesting, but all in all I think this isn't bad code at all.

> if __name__ == '__main__':
>  sentence = sys.argv[1]
>  words = sentence.split(' ')
>  new_words = map(convert, words)
>  new_sentence = ' '.join(new_words)
>  print(new_sentence)

Seem pretty simple to me...


More information about the Snark mailing list