0

I want to find the sum of all the d values of this graph that are not recurring as an example, (a2 a3) and (a3 a2) are considered once

          graph = {
           'a1': {'a2':{'d':4,'t':2,'c':10},'a3':{'d':2,'t':4,'c':40}},
           'a2': { 'a3': {'d':1,'t':3,'c':20}, 'a4': {'d':5,'t':5,'c':60}},
           'a3': {  'a4': {'d':8,'t':15,'c':1000}, 'a5': {'d':10,'t':17,'c':150}, 'a2': {'d':1,'t':3,'c':20}},
           'a4': {  'a5': {'d':2,'t':4,'c':30},'a6': {'d':6,'t':9,'c':70}},
           'a5': { 'a6': {'d':5,'t':5,'c':60},'a4': {'d':2,'t':4,'c':30}},
           'a6': {'a4': {'d':6,'t':9,'c':70}}
    }

Here is the method I used

def getDistanceSum(graph):
    d = 0
    arrahsn = {}

    for key, value in graph.items():
        for i in value:
            newkey = key+','+i
            arrahsn[newkey] = value[i]['d']
            print(key,i,value[i]['d'])
            d += value[i]['d']
    print(arrahsn)


    return d

Here is the output currently I'm getting to get the sum, So is there anything easier to do to get the sum of the unique keys?

{'a1,a2': 4, 'a1,a3': 2, 'a2,a3': 1, 'a2,a4': 5, 'a3,a4': 8, 'a3,a5': 10, 'a3,a2': 1, 'a4,a5': 2, 'a4,a6': 6, 'a5,a6': 5, 'a5,a4': 2, 'a6,a4': 6}

The expected output is the sum of the unique values(as an example consider 'a1,a3': 2 and 'a3,a2': 1) once

sandulasanth-7
  • 199
  • 1
  • 2
  • 14
  • Can you show what you have tried so far ? – sushanth Aug 29 '20 at 11:04
  • @sushanth I created a loop to add all the values to a new array called arrahsn. like this >>{'a1,a2': 4, 'a1,a3': 2, 'a2,a3': 1, 'a2,a4': 5, 'a3,a4': 8, 'a3,a5': 10, 'a3,a2': 1, 'a4,a5': 2, 'a4,a6': 6, 'a5,a6': 5, 'a5,a4': 2, 'a6,a4': 6} – sandulasanth-7 Aug 29 '20 at 11:09
  • def getDistanceSum(graph): d = 0 arrahsn = {} for key, value in graph.items(): for i in value: newkey = key+','+i arrahsn[newkey] = value[i]['d'] print(key,i,value[i]['d']) d += value[i]['d'] print(arrahsn) return d Here the graph is above graph – sandulasanth-7 Aug 29 '20 at 11:09
  • What i was going to try is get the unique keys, but the unique key values are swapped like this 'a3,a2': 1 and 'a2,a3': 1 So I cant get unique values due to that – sandulasanth-7 Aug 29 '20 at 11:11
  • Include the code in the post along with expected output. – sushanth Aug 29 '20 at 11:12

0 Answers0