Last active
August 29, 2015 13:58
-
-
Save benjaminmgross/10007808 to your computer and use it in GitHub Desktop.
Differences between Numpy & List Comprehensions
This file contains hidden or 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
def gen_tickers(num_tickers, num_new): | |
""" | |
This function generates `num_tickers` of random, length 3 tickers and | |
`num_new` random, length 3 tickers | |
""" | |
s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' | |
r = numpy.random.randint(1, 27, 3) | |
ticks = [] | |
#create the list of tickers | |
for i in numpy.arange(num_tickers): | |
ticks.append( | |
reduce(lambda x, y: x + y, map(lambda x: s[x], numpy.random.randint( | |
0, 26, 3) )) ) | |
new_ticks = [] | |
#create the list of tickers to append | |
for i in numpy.arange(num_new): | |
new_ticks.append( | |
reduce(lambda x, y: x + y, map(lambda x: s[x], numpy.random.randint( | |
0, 26, 3) )) ) | |
return ticks, new_ticks | |
def list_method(ticks, new_ticks): | |
""" | |
Uses list comprehensions to accomplish the goal | |
""" | |
bool_map = map(lambda x: x in ticks, new_ticks) | |
return [tick for (tick, bool_val) in zip(new_ticks, bool_map) if not bool_val] | |
def np_one_method(ticks, new_ticks): | |
""" | |
Uses `numpy`, and simply takes lists as arguments to the | |
`numpy` function | |
""" | |
return numpy.setdiff1d(new_ticks, ticks ) | |
def np_too_method (ticks, new_ticks): | |
""" | |
Uses `numpy`, but converts the lists to `numpy.ndarrays` before | |
running the searches | |
""" | |
return numpy.setdiff1d(numpy.array(new_ticks), numpy.array(ticks) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment