Python Pig Latin Translator


#1

After reading some things on the forums about issues people were having with the Pig Latin translator, I decided it was time for me to write my own. (Outside of Codecademy)

After some playing with the code to get it to work properly, I’ve generated something that accommodates the basic vowel rules of Pig Latin, and creates functions to translate to and from Pig Latin. It works for both single or multiple words. Feel free to make suggestions on method or efficiency.


#2

i am going to be very mean, if i want to have a pyglatin translation of birthday, your code produces the wrong output

i know, its a corner case

the other thing that bothers me is here:

new=""

strings are immutable in python, given some mutation is happening to new, ideally new would be a list


#3

Immutable, yes, but not irreplaceable. += replaces the string.


#4

then we need to construct an entire new string in memory, its less memory efficient then using lists


#5

I won’t argue that. but in a simple situation such as this, += is not going to eat a lot of memory, and it gives it back each time. How much memory can the operation take on a single word? It’s only two bytes per letter and can’t use more memory or be less efficient than print.


#6

but this program can handle an entire sentence, if then look at this code:

  for word in start:
    first = word[0]
    if(first in vowels):
      new+=first
      
    for i in range(1,len(word)):
      new+=word[i]
    
    if(not (first in vowels)):
      new+=first
      
    new+="ay "
  return new

see the number of += operations (in a loop, adding each letter of word individually) ? it can use some optimization.


#7

There is no disputing that character operations are notoriously slow, but again, this is a small sample. Even with an hundred letters, The existing string is copied to a buffer, it is concatenated then assigned to the variable.

What I don’t understand why the loop, at all?

first = word[0]
rest = word[1:]

new = first + rest if first in vowels else rest + first
new += 'ay'

#8

yep, that would be a lot better :slight_smile: