Go Back   CodingForums.com > :: Server side development > Other server side languages/ issues > Python

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-21-2012, 03:30 PM   PM User | #1
SoccerGee
New to the CF scene

 
Join Date: Jan 2012
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
SoccerGee is an unknown quantity at this point
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
SoccerGee is offline   Reply With Quote
Old 01-22-2012, 03:25 PM   PM User | #2
Apothem
Regular Coder

 
Apothem's Avatar
 
Join Date: Mar 2008
Posts: 380
Thanks: 36
Thanked 25 Times in 25 Posts
Apothem is an unknown quantity at this point
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.
Apothem is offline   Reply With Quote
Old 01-23-2012, 03:18 AM   PM User | #3
BluePanther
Senior Coder

 
Join Date: Jul 2011
Posts: 1,226
Thanks: 3
Thanked 171 Times in 171 Posts
BluePanther is on a distinguished road
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 
Quote:
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
BluePanther is offline   Reply With Quote
Reply

Bookmarks

Tags
efficiency

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 04:37 AM.


Advertisement
Log in to turn off these ads.