I fulfill a (typical) prime search assignment. I thought I would be smart and, for large numbers, skip the division process with this trick:
def div5(candidate):
return str(candidate)[-1] == "5"
Adding 5 to yourself a few thousand times seems like a waste (I only need the last item), but I wanted to be sure.
unutbu credit for measuring time elapsed in python?
%>python -mtimeit -s"import intDiv" "intDiv.div5(2147483645)"
1000000 loops, best of 3: 0.272 usec per loop
%>python -mtimeit -s"import strDiv" "strDiv.str5(2147483645)"
1000000 loops, best of 3: 0.582 usec per loop
For clarification, here are two methods that I have defined.
def div5(maxi): return not (maxi%5)
def str5(maxi): return str(maxi)[-1] == '5'
It is too slow. How can I parse the last member of str (maxi) without converting the whole number (unnecessarily)?
Thanks to @Claudiu for helping me clean my eyes.
source
share