Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Below is my code for HW ======================== import http.client import json import csv class Graph: # Do not modify def __init__(self, with_nodes_file=None, with_edges_file=None): option

Below is my code for HW

========================

import http.client

import json

import csv

class Graph:

# Do not modify

def __init__(self, with_nodes_file=None, with_edges_file=None):

"""

option 1:init as an empty graph and add nodes

option 2: init by specifying a path to nodes & edges files

"""

self.nodes = []

self.edges = []

if with_nodes_file and with_edges_file:

nodes_CSV = csv.reader(open(with_nodes_file))

nodes_CSV = list(nodes_CSV)[1:]

self.nodes = [(n[0],n[1]) for n in nodes_CSV]

edges_CSV = csv.reader(open(with_edges_file))

edges_CSV = list(edges_CSV)[1:]

self.edges = [(e[0],e[1]) for e in edges_CSV]

def add_node(self, id: str, name: str)->None:

"""

add a tuple (id, name) representing a node to self.nodes if it does not already exist

The graph should not contain any duplicate nodes

"""

if (id,name) not in self.nodes:

self.nodes.append((id,name))

return self.nodes

def add_edge(self, source: str, target: str)->None:

"""

Add an edge between two nodes if it does not already exist.

An edge is represented by a tuple containing two strings: e.g.: ('source', 'target').

Where 'source' is the id of the source node and 'target' is the id of the target node

e.g., for two nodes with ids 'a' and 'b' respectively, add the tuple ('a', 'b') to self.edges

"""

edge = (source, target)

if edge not in self.edges:

self.edges.append(edge)

return self.edges

def total_nodes(self)->int:

"""

Returns an integer value for the total number of nodes in the graph

"""

return len(self.nodes)

def total_edges(self)->int:

"""

Returns an integer value for the total number of edges in the graph

"""

return len(self.edges)

def max_degree_nodes(self)->dict:

"""

Return the node(s) with the highest degree

Return multiple nodes in the event of a tie

Format is a dict where the key is the node_id and the value is an integer for the node degree

e.g. {'a': 8}

or {'a': 22, 'b': 22}

"""

degrees = {}

for i in self.nodes:

if i[0] not in degrees:

degrees[i[0]] = 1

else:

degrees[i[0]] += 1

max_degree = 0

for val in degrees.values():

if val>max_degree:

max_degree = val

max_degree_dict = {}

for node in degrees:

if degrees[node] ==max_degree:

max_degrees_dict[node] = max_degree

return max_degree_dict

def print_nodes(self):

"""

No further implementation required

May be used for de-bugging if necessary

"""

print(self.nodes)

def print_edges(self):

"""

No further implementation required

May be used for de-bugging if necessary

"""

print(self.edges)

# Do not modify

def write_edges_file(self, path="edges.csv")->None:

"""

#write all edges out as .csv

:param path: string

:return: None

"""

edges_path = path

edges_file = open(edges_path, 'w', encoding='utf-8')

edges_file.write("source" + "," + "target" + " ")

for e in self.edges:

edges_file.write(e[0] + "," + e[1] + " ")

edges_file.close()

print("finished writing edges to csv")

# Do not modify

def write_nodes_file(self, path="nodes.csv")->None:

"""

write all nodes out as .csv

:param path: string

:return: None

"""

nodes_path = path

nodes_file = open(nodes_path, 'w', encoding='utf-8')

nodes_file.write("id,name" + " ")

for n in self.nodes:

nodes_file.write(n[0] + "," + n[1] + " ")

nodes_file.close()

print("finished writing nodes to csv")

class TMDBAPIUtils:

movie_Cast_list = []

# Do not modify

def __init__(self, api_key:str):

self.api_key=api_key

def get_movie_cast( self , movie_id:str , limit:int=None, exclude_ids:list=None ) -> list:

"""

Get the movie cast for a given movie id, with optional parameters to exclude an cast member

from being returned and/or to limit the number of returned cast members

documentation url: https://developers.themoviedb.org/3/movies/get-movie-credits

:param integer movie_id: a movie_id

:param integer limit: number of returned cast members by their 'order' attribute

e.g., limit=5 will attempt to return the 5 cast members having 'order' attribute values between 0-4

If there are fewer cast members than the specified limit or the limit not specified, return all cast members

:param list exclude_ids: a list of ints containing ids (not cast_ids) of cast members that should be excluded from the returned result

e.g., if exclude_ids are [353, 455] then exclude these from any result.

:rtype: list

return a list of dicts, one dict per cast member with the following structure:

[{'cast_id': '97909' # the id of the cast member

'character': 'John Doe' # the name of the character played

'credit_id': '52fe4249c3a36847f8012927' # id of the credit}, ... ]

Important: the exclude_ids processing should occur prior to limiting output.

"""

global movie_Cast_list

movie_Cast_list = []

global movie_Cast

movie_Cast = []

conn = http.client.HTTPSConnection("api.themoviedb.org")

conn.request("GET", "/3/movie/{0}/credits?api_key={1}".format(movie_id, self.api_key))

r1 = conn.getresponse()

#print(r1.read())

#print(r1.status, r1.reason)

if r1.status == 200:

movie_data = r1.read()

movie_data_list = json.loads(movie_data.decode('utf-8'))

movie_Cast = movie_data_list['cast']

#movie_Cast_list = []

for dictat in movie_Cast:

#print(dictat)

movie_Cast_shrinked = {key_i: dictat[key_i] for key_i in dictat.keys() & {'cast_id', 'character','credit_id'}}

movie_Cast_list.append(movie_Cast_shrinked)

#print(movie_Cast_list)

if exclude_ids and limit :

#exlude ids first

exclude_ids_ = exclude_ids

mc_ID_filter = [d for d in movie_Cast_list if d['id'] not in exclude_ids_ ]

#select only the records where order is smaller than the limit

mc_order_filter = [d for d in mc_ID_filter if d['order'] < limit ]

#get only certain string from the filtered dict in the list

for dictat in mc_order_filter:

movie_Cast_shrinked = {key_i: dictat[key_i] for key_i in dictat.keys() & {'cast_id', 'character','credit_id'}}

movie_Cast_list = movie_Cast_list.append(movie_Cast_shrinked)

return movie_Cast_list

def get_movie_credits_for_person(self, person_id:str, vote_avg_threshold:float=None)->list:

"""

Using the c, get the movie credits for a person serving in a cast role

documentation url: https://developers.themoviedb.org/3/people/get-person-movie-credits

:param string person_id: the id of a person

:param vote_avg_threshold: optional parameter to return the movie credit if it is >=

the specified threshold.

e.g., if the vote_avg_threshold is 5.0, then only return credits with a vote_avg >= 5.0

:rtype: list

return a list of dicts, one dict per movie credit with the following structure:

[{'id': '97909' # the id of the movie credit

'title': 'Long, Stock and Two Smoking Barrels' # the title (not original title) of the credit

'vote_avg': 5.0 # the float value of the vote average value for the credit}, ... ]

"""

#create a TCP connection that you will use to communicate with the remote server.

connection = http.client.HTTPSConnection('api.themoviedb.org')

#send an HTTP request to over the HTTPS connection with given person id using f-string

connection.request('GET', f'/3/person/{person_id}/movie_credits?api_key={self.api_key}')

#Get the response and read it to json object

response = connection.getresponse()

string = response.read().decode('utf-8')

data = json.loads(string)

# if vote_avg threshold is not none loop through all the movie credits,get the requiredinformation where vote-average is greater than given vote_avg

if vote_avg_threshold is not None:

return_list = [{"id":item["id"],"title":item["title"],"vote_avg":item["vote_average"]} for item in data["cast"] if item["vote_average"]>=vote_avg_threshold]

# else just return all the data with required parameters

else:

return_list = [{"id":item["id"],"title":item["title"],"vote_avg":item["vote_average"]} for item in data["cast"]]

return return_list

apiKey = 'mykey'

======================

My question is, how can I produce node.csv and edges.csv with this code?

When you see the bold part, in my understanding, any csv file should be provided to execute

if with_nodes_file and with_edges_file:

this if function.

If I did something wrong, please let me know and please provide me code to produce node.csv and edges.csv

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Modern Dental Assisting

Authors: Doni Bird, Debbie Robinson

13th Edition

978-0323624855, 0323624855

Students also viewed these Programming questions