2
\$\begingroup\$

How is it and can it be optimised?

sentence = input("Enter a sentence you want to convert to pig latin: ")

sentence = sentence.split()
for i in range(len(sentence)):
    if sentence[i][0] in "aeiou":
        sentence[i] += 'yay'
    else:
        sentence[i]=sentence[i][1:]+sentence[i][0]
        sentence[i]+='ay'
sentence = ' '.join(sentence)

print(sentence)
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You don't actually care about indexes during the iteration; you just want the contents. The loop would be better written as

sentence = input(…)
for word in sentence.split():
    if word[0] in "aeiou":
        …

How would you reassemble the results? Noting that each word can be translated independently, I would define a function for that, then use a generator expression.

def pig_latin(word):
    if word[0] in "aeiou":
        return word + 'yay'
    else:
        return word[1:] + word[0] + 'ay'

sentence = input("Enter a sentence you want to convert to pig latin: ")
print(' '.join(pig_latin(word) for word in sentence.split()))
\$\endgroup\$
1
  • 1
    \$\begingroup\$ you can get rid of else: in your def pig_latin(word) function, and outdent return word[1:] + word[0] + 'ay' \$\endgroup\$ Commented Jun 15, 2016 at 12:27

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.