简体   繁体   中英

How to print out a hierarchy tree of the employees

Given a list of employees and their bosses as a csv file , write a function that will print out a hierarchy tree of the employees.

Sample input from csv file

Sam, Ian, technical lead, 2009 / Ian, NULL, CEO,2007/ Fred, Sam,developer, 2010

The format is name, supervisor, designation, year of joining.

The output should be

Ian CEO 2007

-Sam Technical lead 2009

--Fred Developer 2010

I am not sure but I have tried it as below. Please suggest changes to this code or any other solutions you have.

strq = "Sam, Ian, technical lead, 2009 / Ian, NULL, CEO,2007/Fred, Sam, developer, 2010"
def treeEmployee(infoStr):
    str1 = infoStr.split("/")
    s2 = []
    for i in str1:
        s2.append(i.split(","))
    for i in range(len(s2)):
        for j in range(1, len(s2)):
            if s2[i][1] == s2[j][0]:
                s2[i], s2[j] = s2[j], s2[i]
            return s2

print treeEmployee(strq)

I want the output to be

Ian CEO 2007

-Sam Technical lead 2009

--Fred Developer 2010

Fixing the indentation like this should work. Indentation is extremely important in python.

strq = "Sam, Ian, technical lead, 2009 / Ian, NULL, CEO,2007/Fred, Sam, developer, 2010"
def treeEmployee(infoStr):
    str1 = infoStr.split("/")
    s2 = []
    for i in str1:
        s2.append(i.split(","))
    for i in range(len(s2)):
        for j in range(1, len(s2)):
            if s2[i][1] == s2[j][0]:
                s2[i], s2[j] = s2[j], s2[i]
                return s2

This generates a hierarchy tree from your inputs in JS.

 function wrapper(str) { var elem; str = str.split('/'); function tree(parent, arr, level) { if (!parent) { parent = 'NULL'; } if (!arr) { arr = []; } if (!level) { level = 0; } var obj, children = findChild(parent); for (var i = 0, len = children.length; i < len; i += 1) { elem = children[i]; obj = { name: elem[0], supervisor: parent, designation: elem[2], yearOfJoining: elem[3], children: [], level: level }; arr.push(obj); console.log(dashGenerator(level) + obj.name + ' ' + obj.designation + ' ' + obj.yearOfJoining); tree(elem[0], obj.children, level + 1); } return arr; } function dashGenerator(level) { var str = ''; for (var i = 0; i < level; i += 1) { str += '-'; } return str; } function findChild(parent) { var child = []; for (var i = 0, len = str.length; i < len; i += 1) { elem = str[i].split(',') if (elem[1].trim() === parent.trim()) { child.push(elem); } } return child; } tree(); } wrapper("Sam, Ian, technical lead, 2009 / Ian, NULL, CEO,2007/ Fred, Sam,developer, 2010"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM