Question

In: Computer Science

Write a Python/NetworkX function add_weights(G1, G1), where G1 and G1 are intended to be graphs with...

Write a Python/NetworkX function add_weights(G1, G1), where G1 and G1 are intended to be graphs with exactly the same edges and such that each edge has either no attribute or a single attribute, ‘weight’, with a numerical value. It returns a graph, say, G3, that has the same edges as G1 and G2. Each edge e of G3 has a single attribute, ‘weight’, whose value is the sum of the ‘weight’ attributes of e in G1 and of e in G2 if ein G1 and e in G2 both have attribute ‘weight’. Otherwise, if e in one of G1 or G2 has attribute ‘weight’, then the value of ‘weight’ in G3 is the value of that ‘weight’ attribute. Otherwise (i.e., neither e in G1 nor e in G2 has attribute ‘weight’), the value of attribute ‘weight’ in e in G3is 0. This function returns G3.

Note that, where G is a graph with an edge (u, v), G[u][v] counts as False in a position expecting a Boolean value if the edge (u, v)in G has no edge attributes. This is useful in this problem since an edge either has a single attribute, ‘weight’, or has no attribute.

The following is test code, followed by its output.

if __name__ == "__main__"  :     

    Ga = nx.Graph()

    Ga.add_edges_from([(0, 1, {'weight': 2}), (1, 2, {'weight': 4}),

                      (2, 3), (3, 1, {'weight': 2}), (0, 3)])

    Gb = nx.Graph()

    Gb.add_edges_from([(0, 1, {'weight': 3}), (1, 2, {'weight': 5}),

                      (2, 3, {'weight':3}), (3, 1), (0, 3)])

           

    for u, v, attr in add_weights(Ga, Gb).edges(data=True):

        wGa = Ga[u][v]['weight'] if Ga[u][v] else None

        wGb = Gb[u][v]['weight'] if Gb[u][v] else None

        print("Edge ({}, {}): {} + {} = {}".format(u, v, wGa, wGb,

                                                    attr['weight']))

Output:

Edge (0, 1): 2 + 3 = 5

Edge (0, 3): None + None = 0

Edge (1, 2): 4 + 5 = 9

Edge (1, 3): 2 + None = 2

Edge (3, 2): None + 3 = 3

Solutions

Expert Solution

Below is the function in python/networkx

def add_weights(G1,G2):
    G3 = nx.Graph()
    edgelist = []
    for u,v in G1.edges():
        sum = 0
        if G1[u][v]:
            sum += G1[u][v]['weight']
        if G2[u][v]:
            sum += G2[u][v]['weight']
        edgelist.append(u,v,{'weight':sum})
    
    G3.add_edges_from(edgelist)
    return G3

After including this function, when you run the complete code given in question , the following is the output

Output

Edge (0, 1): 2 + 3 = 5

Edge (0, 3): None + None = 0

Edge (1, 2): 4 + 5 = 9

Edge (1, 3): 2 + None = 2

Edge (3, 2): None + 3 = 3

Below is the code screenshot for indentation reference. Please let me know if you have any questions/doubts etc. I would help further. Thanks


Related Solutions

For the following exercises, use the graphs to write an equation for the function.
For the following exercises, use the graphs to write an equation for the function.
how to write a unit test for a write function in python? is there a better...
how to write a unit test for a write function in python? is there a better way than running main once and checking whether the new file path exists?
PYTHON: Write a function insertInOrder that takes in a list and a number. This function should...
PYTHON: Write a function insertInOrder that takes in a list and a number. This function should assume that the list is already in ascending order. The function should insert the number into the correct position of the list so that the list stays in ascending order. It should modify the list, not build a new list. It does not need to return the list, because it is modifying it.   Hint: Use a whlie loop and list methods lst = [1,3,5,7]...
Write a Python function that takes a list of string as arguments. When the function is...
Write a Python function that takes a list of string as arguments. When the function is called it should ask the user to make a selection from the options listed in the given list. The it should get input from the user. Place " >" in front of user input. if the user doesn't input one of the given choices, then the program should repeatedly ask the user to pick from the list. Finally, the function should return the word...
Python: Write a function that receives a one dimensional array of integers and returns a Python...
Python: Write a function that receives a one dimensional array of integers and returns a Python tuple with two values - minimum and maximum values in the input array. You may assume that the input array will contain only integers and will have at least one element. You do not need to check for those conditions. Restrictions: No built-in Python data structures are allowed (lists, dictionaries etc). OK to use a Python tuple to store and return the result. Below...
For the following exercises, use the graphs to write a polynomial function of least degree.
For the following exercises, use the graphs to write a polynomial function of least degree.
In python write a function whose input is a string. This function determines the data type...
In python write a function whose input is a string. This function determines the data type of the input string. The data types can be a float, int, or string. Most pass the following assertions: assert determine_data_type('1.2') == float assert determine_data_type('4') == int assert determine_data_type('EAS503') == str
Write a python function to fulfill the requirements. The function accepts a string, a current state,...
Write a python function to fulfill the requirements. The function accepts a string, a current state, edges’ information, and an accepting state. The output of the function is a boolean value verifying if the string can pass the finite state machine or not.             ### Finite State Machine Simulator in Python ### Provide s1 and s2 that are both accepted, but s1 != s2. s1 = "bdf" s2 = "bdgbdf" edges = {(1,'a') : 2,                (1,'b') : 3,       ...
This is python: #Write a function called count_positive_evens. This function #should take as input a list...
This is python: #Write a function called count_positive_evens. This function #should take as input a list of integers, and return as #output a single integer. The number the function returns #should be the count of numbers from the list that were both #positive and even. # #For example: # # count_positive_evens([5, 7, 9, 8, -1, -2, -3]) -> 1 # count_positive_evens([2, 4, 6, 8, 10, 12, 15]) -> 6 # count_positive_evens([-2, -4, -6, -8, -10, 1]) -> 0 # #0...
Use Python for this quetions: Write a python functions that use Dictionary to: 1) function name...
Use Python for this quetions: Write a python functions that use Dictionary to: 1) function name it addToDictionary(s,r) that take a string and add it to a dictionary if the string exist increment its frequenc 2) function named freq(s,r) that take a string and a record if the string not exist in the dictinary it return 0 if it exist it should return its frequancy.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT