Use sets
import sys
import random
import itertools
def main(args):
target_num = int(999999999)
num_list = set(range(1, target_num))
rand_list = []
hit_list = []
for _ in itertools.repeat(None, target_num):
rand_list.append(random.randint(1, target_num))
for num in rand_list:
if num in num_list: # O(1)
print "hit"
if __name__ == "__main__":
main(sys.argv[1:])
Using a set for the first list, means that checking if the item is in that list is now reduced to an O(1)
As I am writing this, I realise you can even do better. The range function in python 3 returns a sequence, so you need python 3 for this next part
import sys
import random
import itertools
def main(args):
target_num = int(999999999)
num_list = range(1, target_num) # this is a generator
rand_list = []
hit_list = []
for _ in itertools.repeat(None, target_num):
rand_list.append(random.randint(1, target_num))
for num in rand_list:
if num in num_list: # Stil O(1)
print ("hit")
if __name__ == "__main__":
main(sys.argv[1:])
Even better, using range and do the checking within the first loop?
for _ in itertools.repeat(None, target_num):
rand_num = random.randint(1, target_num)
rand_list.append(rand_num)
if rand_num in num_list:
print ("hit")
listas a variable nameread_listorrand_list?rand_list = [random.randint(1, target_num) for _ in itertools.repeat(None, target_num)]). They are more efficient than using for loops as you don’t need to load the append attribute off of the list and call it as a function.