Python help read_file(fp) will have the file pointer fp passed into it. The firs
ID: 3864500 • Letter: P
Question
Python help read_file(fp) will have the file pointer fp passed into it. The first line of the file contains the value for the variable n, the number of users in the social network. We have provided the code to read n and initialize a list network containing n nested empty lists (e.g., n = 3 would correlate to creating the list [ [], [], [] ]). This list of lists will be used to hold the list of friends for each of the n users. You can then use a for loop to iterate over the remaining lines of the file. For each line of the file you will want to obtain the two user id values on that line—we denote those user ids as u and v. You need to place v into u’s list and also place u into v’s list, since they are mutual friends (hint: use the list append() method to place each user id into a list). Finally you will return network, which is the list of lists that was created. def read_file(fp): ''' Remember the docstring''' # Read n and initizlize the network to have n empty lists -- # one empty list for each member of the network n = fp.readline() n = int(n) network = [] for i in range(n): network.append([]) # You need to write the code to fill in the network as you read the file # Hint: append appropriate values to the appropriate lists. # Each iteration of the loop will have two appends -- why? return network
Explanation / Answer
Here is the code for you:
#!/usr/bin/python
def read_file(fp):
''' Remember the docstring'''
# Read n and initialize the network to have n empty lists --
# one empty list for each member of the network
n = fp.readline()
n = int(n)
network = []
for i in range(n):
network.append([])
# You need to write the code to fill in the network as you read the file
# Hint: append appropriate values to the appropriate lists.
# Each iteration of the loop will have two appends -- why?
while True:
line = fp.readline()
connection = line.split()
if len(connection) == 0:
break
src = int(connection[0])
dest = int(connection[1])
#tokens = line.split();
network[src-1].append(dest)
network[dest-1].append(src)
fp.close()
return network
f = file("network.txt", 'r')
try:
IOError
except:
print "File not found. Directories are not supported"
print read_file(f)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.