Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
01-21-2012, 03:30 PM #1
- Join Date
- Jan 2012
- 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?
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)
def verbing(s): if len(s) >= 3: if s[-3:] != 'ing': s = s + 'ing' else: s = s + 'ly' return s
01-22-2012, 03:25 PM #2
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.
01-23-2012, 03:18 AM #3
- Join Date
- Jul 2011
- 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.
// Replace this
// With this
// 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.