Calling Python Function with string argument

I wrote this function to check if a word is abecedarian but I can't seem to use a string as an argument. I didn't know this since I've never had to use a string argument until now. Is there a way around this?

def is_abecedarian(word):
    prev_char_ord = 0

    for char in word.lower():
        if prev_char_ord <= ord(char):
            prev_char_ord = ord(char)
        else:
            return False
    return True

Upvotes: 0

Views: 239

Answers (2)

Yaiyan
Yaiyan

Reputation: 101

If you're setting prev_char_ord to 0 at the start of the function, no matter what character your string starts with, it will be higher than prev_char_ord.

Set prev_char_ord to either 255 (since ord only works for ascii characters), or use the first letter of your string to set the value (which can be accessed like an array, so the first character in lowercase would be word.lower()[0]).

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117866

You can check the original word against the sorted word

def is_abecedarian(word):
    return word == ''.join(sorted(word))

Testing

>>> is_abecedarian('test')
False

>>> is_abecedarian('abcde')
True

Upvotes: 1

Related Questions