nht_cntt

Stack and while

Apr 13th, 2018
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. def tree(categories, tab=''):
  2.     if type(categories) == 'list' or len(categories):
  3.         stack = []
  4.         tab = ''
  5.         stack.append((categories, tab))
  6.         while len(stack) != 0:
  7.             tmp = stack.pop()
  8.             for category in tmp[0]:
  9.                 print tmp[1] + category['name']
  10.                 stack.append((category['children'], tab + "--+ ")) 
  11.  
  12. categories = [{
  13.         'name': 'Cat 1',
  14.         'children': [{
  15.                 'name': 'Sub 1 Cat 1',
  16.                 'children': [{
  17.                         'name': 'Sub 1 Sub 1 Cat 1',
  18.                         'children': [{
  19.                                 'name': 'Sub 1 Sub 1 Sub 1 Cat 1',
  20.                                 'children': []
  21.                             },
  22.                             {
  23.                                 'name': 'Sub 2 Sub 1 Sub 1 Cat 1',
  24.                                 'children': []
  25.                             }
  26.                         ]
  27.                     },
  28.                     {
  29.                         'name': 'Sub 2 Sub 1 Cat 1',
  30.                         'children': []
  31.                     }
  32.                 ]
  33.             },
  34.             {
  35.                 'name': 'Sub 2 Cat 1',
  36.                 'children': []
  37.             }
  38.         ]
  39.     },
  40.     {
  41.         'name': 'Cat 2',
  42.         'children': []
  43.     }
  44. ]
  45.  
  46. tree(categories)
Advertisement
Add Comment
Please, Sign In to add comment