[Snark] Python procedure
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:
> VOWELS = 'aeiou'
> CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
Well named, straight forward, constants?
> def convert(s):
> # rule 1
> if s 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 in CONSONANTS and s in VOWELS:
> return s[1:] + s + 'ay'
> if len(s) >= 3 and s in CONSONANTS and s in CONSONANTS and s in VOWELS:
> return s[2:] + s[0:2] + 'ay'
> if len(s) >= 4 and s in CONSONANTS and s in CONSONANTS and s in CONSONANTS and s 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
> words = sentence.split(' ')
> new_words = map(convert, words)
> new_sentence = ' '.join(new_words)
Seem pretty simple to me...
More information about the Snark