Untitled
unknown
python
3 years ago
2.4 kB
7
Indexable
import time
import random
# number of items to search (global constant)
N = 10000
# ----- Create data structures with random numbers ---------
# 1. Create a list and add random numbers to the list
print("Adding numbers to list ...", end = "")
number_list = []
while len(number_list) < N:
random_number = random.randint(0, N**3)
if random_number not in number_list:
number_list.append(random_number)
print("...done")
print(len(number_list))
# 2. Create a dictionary and add random numbers to the dict
print("Adding numbers to dict ...", end = "")
number_dict = {}
for i in range( len(number_list) ):
number_dict[number_list[i]] = number_list[i]
print("...done")
# print(number_list)
# print(number_dict)
print(f'\nTotal numbers: {N}')
# ------------------------------------------------------------ #
# Analyzing run-time - 1, searches evaluating to True
# Record the start time for list
tic = time.perf_counter()
# print(tic)
for n in number_list:
n in number_list # check if n is in number_list, always returns True
# Record the end time
toc = time.perf_counter()
# print(toc)
# Print the time difference
print(f"Time taken for {N} searches evaluating to True in a List : {round(toc-tic,4)} seconds")
####
# Record the start time for dict
tic = time.perf_counter()
for n in number_dict:
n in number_dict # check if n is in number_dict.keys(), always returns True
# Record the end time
toc = time.perf_counter()
# Print the time difference
print(f"Time taken for {N} searches evaluating to True in a Dict : {round(toc-tic,4)} seconds")
print()
# ------------------------------------------------------------ #
# Analyzing run-time - 2, searches evaluating to False
# Record the start time for list
tic = time.perf_counter()
for n in number_list:
-n in number_list # check if -n is in number_list, returns False always
# Record the end time
toc = time.perf_counter()
# Print the time difference
print(f"Time taken for {N} searches evaluating to False in a List : {round(toc-tic,4)} seconds")
####
# Record the start time for dict
tic = time.perf_counter()
for n in number_dict:
-n in number_dict # check if -n is in number_dict.keys(), always returns False
# Record the end time
toc = time.perf_counter()
# Print the time difference
print(f"Time taken for {N} searches evaluating to False in a Dict : {round(toc-tic,4)} seconds")pyEditor is loading...