Try this code, it's equivalent to the one posted in the question, but written in a recursive style:
from string import ascii_lowercase
def abc(s):
f = [c for c in s.lower() if c in ascii_lowercase]
if aux(f, 0):
return s + " is abcdearian"
else:
return s + " is not abcdearian"
def aux(s, i):
if i >= len(s)-1:
return True
elif s[i] > s[i+1]:
return False
else:
return aux(s, i+1)
Use it like this:
while True:
s = input("String? ")
if not s:
break
print(abc(s))
Notice that I split the problem in two: first the, "main" function abc()
takes care of filtering the string, calling the aux
procedure with correct initial values and returning the result string at the end (alternatively: you could have returned a boolean, creating the result string elsewhere.)
The real work is done in the helper aux
function, which recursively traverses the string checking if the "abcdearian" condition is true for all pairs of consecutive characters in the string. The way aux
iterates over the string is efficient (putting aside the fact that we're using recursion), because it never creates additional intermediate strings with s[1:]
. It's also an example of a tail-recursive algorithm, and it closely mirrors the structure of the iterative solution.