Is there a way I could optimise my code?


#1



I'm going through the Pig Latin code converter with a link to the lesson below:

https://www.codecademy.com/courses/python-beginner-2W5v7/0/1?curriculum_id=4f89dab3d788890003000096#


My code runs and behaves correctly, however I think i've only written a basic form for the solution. Are there any advanced tricks to optimise the code?


I'm hoping to reach this level of proficiency someday
http://www.mit.edu/~johnp/6.189/solutions/piglatin.py


def pyglatin():
    
    # variable definitions
    user_input = raw_input('Enter your first word to translate:')

    if (len(user_input) > 0) and user_input.isalpha():
        print "You typed %s" % (user_input)
        pyg = "ay"
        word = user_input.lower()
        first = word[0]
        new_word = user_input
        pigword = word[1:len(user_input)]
        new_word = pigword + first + pyg
        print "The word in piglatin is %s" % (new_word)
        return True
    else:
        print "The word you entered is invalid, please try again"
        pyglatin()
    
print 'Welcome to the Pig Latin Translator!'
pyglatin()


#2

inserting advanced tricks will probably just be confusing at this point, i recommend to progress through the course, and then come back later to optimize to see how much you learned


#3

This is the easiest optimisation I could do. However it looks like the function can't take a sentence and for that a for loop is needed.

def pyglatin():
    
    # variable definitions
    user_input = raw_input('Enter your first word to translate:')
      
    if (len(user_input) > 0) and user_input.isalpha():
        print "You typed %s" % (user_input)
        new_word = ""
        new_word = user_input[1:] + user_input[0] + "ay"
        print "The word in piglatin is %s" % (new_word)
        return True
    else:
        print "The word you entered is invalid, please try again"
        pyglatin()
    
print 'Welcome to the Pig Latin Translator!'
pyglatin()

#4

yes, and spaces are not alpha numeric characters, so you would have to get rid of .isalpha() as well, but that is a concern for later


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.