In: Computer Science
In this homework, you are provided a user pool (hw2_users_4m.txt) and a list of target users (hw2_targets.txt). Find if each target user is in the user pool. In python
1. Use list to store user pool and write the output into a file.
user_id_1,True
user_id_2, False
with open('hw2_targets.txt', 'r') as i: targets = [line.strip() for line in i] with open('hw2_users_4m.txt', 'r') as i: user_ids_list = [line.strip() for line in i] start_time = time.time() results_list = [] ################################## ## write your code for using list ################################## end_time = time.time() run_time = end_time - start_time print(round(run_time, 2))
with open('output_list.txt', 'w') as o: for result in results_list: o.write(result[0] + ',' + result[1])
Following updates have been made to the given code snippet:
1. Added import statement to use time() function.
2. Added for loops to iterate through every user in target list and determine even it exists in the given pool of users.
3. Storing our results in a list called results_list
4. Added a new line character while writing to output file.
Fianl program:
import time
with open('hw2_targets.txt', 'r') as i:
targets = [line.strip() for line in i]
with open('hw2_users_4m.txt', 'r') as i:
user_ids_list = [line.strip() for line in i]
start_time = time.time()
results_list = []
for tar in targets: #For each target user in the input file loop checks if it exists in the user pool
target_exist="False" #Variable to determine existence of a target user in given pool of users
for user in user_ids_list:
if tar == user:
target_exist="True"
results_list.append([tar,target_exist]) #Storing our result in the list
#If a match is found no need to check in rest of the pool of users. Thus, breaking flow of inner loop
break
if target_exist=="False": #Match for target user not found in user pool thus, storing False as result for that target user
results_list.append([tar,target_exist])
end_time = time.time()
run_time = end_time - start_time
print(round(run_time, 2))
with open('output_list.txt', 'w') as o:
for result in results_list:
o.write(result[0] + ',' + result[1])
o.write("\n") #Writing new line character to the file to display each result in a new line