...

Learning Python: efficiency question

SoccerGee
01-21-2012, 03:30 PM
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:
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:
def verbing(s):
if len(s) >= 3:
if s[-3:] != 'ing': s = s + 'ing'
else: s = s + 'ly'
return s

Apothem
01-22-2012, 03:25 PM
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.

BluePanther
01-23-2012, 03:18 AM
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?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum