Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jan 2012
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Learning Python: efficiency question

    I'm new to Python and a beginner at programming in general.

    Is there an efficiency difference between Code A and Code B?

    Code A:
    Code:
    def verbing(s):
      if len(s) > 3 and s[-3:] == 'ing':
        return str(s) + 'ly'
      if len(s) > 3:
        return str(s) + 'ing'
      if len(s) <= 3:
        return str(s)
    Code B:
    Code:
    def verbing(s):
      if len(s) >= 3:
        if s[-3:] != 'ing': s = s + 'ing'
        else: s = s + 'ly'
      return s

  • #2
    Regular Coder Apothem's Avatar
    Join Date
    Mar 2008
    Posts
    380
    Thanks
    36
    Thanked 25 Times in 25 Posts
    I would think so, yes.

    1. Code A is calling len() a lot more. At worse, you're calling it 3 times. If the string is quite large, it'd be quite inefficient.
    2. Code A has more conditions.

    That's all I an think of.

  • #3
    Senior Coder
    Join Date
    Jul 2011
    Posts
    1,226
    Thanks
    3
    Thanked 171 Times in 171 Posts
    Code B is better, for all the reasons posted above. It also shows better logic, through your use of 1 return of s.

    But, the code does slightly different things. Code A won't append anything to s if s is = to 3, whereas Code B will. Is this a mistake?
    Useful function to retrieve difference in times
    The best PHP resource
    A good PHP FAQ
    PLEASE remember to wrap your code in [PHP] tags.
    PHP Code:
    // Replace this
    if(isset($_POST['submitButton']))
    // With this
    if(!empty($_POST))
    // Then check for values/forms. Some IE versions don't send the submit button 
    Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •