Python Forum
Trying to solve an exercise
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trying to solve an exercise
#1
Hello, I'm trying to solve this exercise from the book think python :
Exercise 9.6. Write a function called is_abecedarian that returns True if the letters in a word
appear in alphabetical order (double letters are ok). How many abecedarian words are there?

This is my solution :

def is_abecedarian(w):
    w = w.lower()
    if len(w) <= 1 :
        return True
    elif ord(w[0]) > ord(w[1]) :
        return False
    else :
        is_abecedarian(w[1:])
When I try to run the script it returns None. I don't uderstand why...
Reply
#2
Your return statements are not making it back through the recursions. Change the last line in your function to this :

return (is_abecedarian(w[1:]))
So the whole thing is:

def is_abecedarian(w):
	w = w.lower()
	if len(w) < 2:
		return True
	elif ord(w[0]) > ord(w[1]) :
		return False
	else :
		return (is_abecedarian(w[1:]))

print (is_abecedarian ('abcdefg'))
output = True
frafrog likes this post
Reply
#3
how did i miss that? Shifty thx
Reply
#4
I believe you have worked on this for a while, so think of this:
  • set return value variable to True
  • if length of word is not 1
  • get idx of 1 to length of word (hint use a loop)
  • if word[idx-1] > word[idx} then
    • set return value to False
    • exit loop
  • return value

def is_abecedarian(w):
    retval = True
    if not len(w) == 1:
        for i in range(1, len(w)):
            if w[i-1] > w[i]:
                retval = False
                break
    return retval
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020