Created
February 12, 2012 12:53
-
-
Save bootandy/1808341 to your computer and use it in GitHub Desktop.
Python. Backwards Loops: reversed > xrange > range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import random | |
import time | |
def main(): | |
list = [] #[5,6,3,6,8,3,10,0,4] | |
for i in range(0, 1000000): | |
list.append(int( random() * 1000000000 ) ) | |
with_reversed(list) | |
backwards_xrange(list) | |
backwards_range(list) | |
another_range(list) | |
""" reversed: (Fastest)""" | |
def with_reversed(list): | |
start_time = time.time() | |
profit = 0 | |
highest = list[-1] | |
for a in reversed(list): | |
if (highest - a) > profit: | |
profit = (highest - a) | |
if a > highest: | |
highest = a | |
print str(with_reversed.__name__) + " total time: "+ str( time.time() - start_time ) | |
print profit | |
""" Manually creating a xrange (xrange is faster than range)""" | |
def backwards_xrange(list): | |
start_time = time.time() | |
profit = 0 | |
highest = list[-1] | |
for i in xrange(len(list)-1, -1, -1): | |
a = list[i] | |
if (highest - a) > profit: | |
profit = (highest - a) | |
if a > highest: | |
highest = a | |
print str(backwards_xrange.__name__) + " total time: "+ str( time.time() - start_time ) | |
print profit | |
""" Manually creating a range. :""" | |
def backwards_range(list): | |
start_time = time.time() | |
profit = 0 | |
highest = list[-1] | |
for i in range(len(list)-1, -1, -1): | |
a = list[i] | |
if (highest - a) > profit: | |
profit = (highest - a) | |
if a > highest: | |
highest = a | |
print str(backwards_range.__name__) + " total time: "+ str( time.time() - start_time ) | |
print profit | |
""" Manually creating a range and read backwards using len(list): (slowest) """ | |
def another_range(list): | |
start_time = time.time() | |
profit = 0 | |
highest = list[-1] | |
for i in range(1, len(list) + 1 ): | |
a = list[len(list) - i] | |
if (highest - a) > profit: | |
profit = (highest - a) | |
if a > highest: | |
highest = a | |
print str(another_range.__name__) + " total time: "+ str( time.time() - start_time ) | |
print profit | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment