2
\$\begingroup\$

Wrote a basic pig latin script in python where the input is a string and it outputs the pig latin equivalent. I was just wondering what the runtime of this code would be and if there was a way to make it quicker. Off the time of my head, I would assume that the runtime would be \$O(26)\$ or just constant because all you do is look at the last letter and compare it to the list.

def pig_latin(string):
    consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
    if string[-1] in consonants:
        string = string[1:] + string[0] + "ay"
    else:
        string = string + "way"
    return string
\$\endgroup\$
2
  • \$\begingroup\$ Your code only works on one word at a time, not a whole sentence. I believe you need to split on spaces first. \$\endgroup\$
    – Snowbody
    Dec 1, 2017 at 18:33
  • \$\begingroup\$ Your runtime is going to depend on two things: the number of words of the input, and the method you use to determine if the last character is a consonant or a vowel. \$\endgroup\$
    – Snowbody
    Dec 1, 2017 at 18:35

1 Answer 1

1
\$\begingroup\$

I don't think speed should be your primary concern in this case. The only thing I could come up with as an improvement is to change consonants:

from string import ascii_lowercase

VOWELS = ("a", "e", "i", "u", "o", "y", "w")
CONSONANTS = tuple(char for char in ascii_lowercase if char not in VOWELS)
# These can be constants because they're always the same (at least for the latin alphabet).

Also, you don't handle the case where string is not lowercase. To account for that:

def pig_latin(string):
    string = string.lower()  
    if string[-1] in CONSONANTS:
        string = string[1:] + string[0] + "ay"
    else:
        string = string + "way"
    return string

As @Ludisposed suggested, you don't actually have to convert the entire string to lowercase, if string[-1].lower() in CONSONANTS would do.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ You don't have to lower() the entire string, just lower the last char in it should suffice. As a side effect of that the returned string will always be lowercase, I dont know if that is OP's intention. \$\endgroup\$
    – Ludisposed
    Dec 1, 2017 at 16:18
  • \$\begingroup\$ Since your CONSONANTS is a generator expression, it will be gradually exhausted with each call of the pig_latin() function. Better to make it a set. \$\endgroup\$ May 18, 2018 at 14:48
  • \$\begingroup\$ @200_success Thanks, I meant to create a tuple. \$\endgroup\$
    – Daniel
    May 18, 2018 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.