PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, June 28, 2022

[FIXED] How to Get All Combination Node (Given dictionary and list) and sort by the longest node in Python

 June 28, 2022     graph, nodes, path, python, sorting     No comments   

Issue

How to get all combinations (listed) from a given dictionary, in python ?

My Dictionary Input :

node_data = {
    "1":["2","3","4","5"],#1
    "2":["7","8"],#2
    "3":["6"],#3
    "4":[],#4
    "5":[],#5
    "6":["11"],#6
    "7":[],#7
    "8":["9","10",],#8
    "9":["12"],#9
    "10":[],#10
    "11":["13"],#11
    "12":[],#12
    "13":["14"],#13
    "14":[]#14   
}

Desidered output (sort by the longest node):

["1","3","6","11","13","14"]
["1","2","8","9","12"]
["1","2","8","10"]
["1","2","7"]
["1","4"]
["1","5"]


Solution

I did something like this and it seems to work:

def recurse(current, nodes, path, all_path):
    path.append(current)
    if nodes[current]:
        for child in nodes[current]:
            recurse(child, nodes, path.copy(), all_path)
    else:
        all_path.append(path)
    return all_path
    
if __name__ == '__main__':
    node_data = {
        "1":["2","3","4","5"],#1
        "2":["7","8"],#2
        "3":["6"],#3
        "4":[],#4
        "5":[],#5
        "6":["11"],#6
        "7":[],#7
        "8":["9","10",],#8
        "9":["12"],#9
        "10":[],#10
        "11":["13"],#11
        "12":[],#12
        "13":["14"],#13
        "14":[]#14   
    }
    toto = recurse("1", node_data, [], [])
    toto.sort(key=len, reverse=True)
    print(toto)

Hope it'll help you



Answered By - Kyshio
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing