(Python) PyProgram #8 – Cycling Alphabets

Kushal came down with a simple looking problem with constraints that might make solving it a bit not-a-needle-into-the-banana. As usual, me and Jacob sat down trying to solve it. Rather try finding various ways of solving it. The problem is, given one character within the range a-z or A-Z (not as a list, but from string.letters) we have to find the next character in the alphabetical order. When ‘z’ or ‘Z’ is encountered, the next alphabet returned should be ‘a’ or ‘A’ respectively. The constraint is that if or while conditions and for loops should not be used. And more importantly, the main solution should be of a single line. Though Kushal had a more mathematical solution, this is what me and Jacob managed to cook up as a more logical solution (note the ‘and’ and ‘or’ 😉 ),

import string

def thenext(theletter):
    return ((string.letters.find(theletter)+1) %26) and (string.letters[string.letters.find(theletter)\
+1]) or (string.letters[string.letters.find(theletter)-25])

print "for 'a' i get: "+thenext('a')
print "for 'g' i get: "+thenext('g')
print "for 'z' i get: "+thenext('z')
print "for 'A' i get: "+thenext('A')
print "for 'H' i get: "+thenext('H')
print "for 'Z' i get: "+thenext('Z')

The solution looks like..

for 'a' i get: b
for 'g' i get: h
for 'z' i get: a
for 'A' i get: B
for 'H' i get: I
for 'Z' i get: A
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s