示例#1
0
"""
This module contains examples of how to use the functions in this library. 
"""

from find_max_value_path import findMaxValuePath
from generate_trees import generateTree
from nodes import buildTreeUpDown
from paths import findMaxPath

## Generate randomly a tree of 100 rows and save it to a file called
## 'random-tree.txt':
bigTree = generateTree(100, toFile="toFile", fileName="random-tree.txt")

## Convert the tree into a dictionary of nodes:
nodes = buildTreeUpDown(bigTree)

## Find the path in that three that yields the highest value:
highestPath, pathValue = findMaxValuePath(nodes)
print(highestPath, pathValue)

## Find the path that yields the highest value in a randomly generated tree
## of 10 rows:
highestPath, pathValue = findMaxValuePath(size=10)
print(highestPath, pathValue)

## Load a tree from a file and find the path in that tree that yields the
## highest value:
highestPath, pathValue = findMaxValuePath("random-tree.txt")
print(highestPath, pathValue)

#### The following code snippet illustrates how to use the functions from the
def findMaxValuePath(tree='random', size=5, printTree='no', fileName=None):
    """
    Returns the path which yields the highest value in a tree as a list, in which each
    member is an index that references the key value of the node in the tree. It also
    returns the sum of the nodes in that path.
    By default, it takes a small tree of 5 rows which is randomly generated, and
    returns its highest value path, together with the value of the nodes in that path.

    Parameters:
    ----------
    tree: set to 'random' by default, in which case the function builds a random tree.
          I you wish to pass in a specific tree, be sure it accords to one of the
          following data structures:
          1) A dictionary in which each element contains the following five properties:
             'value', 'position', 'row', 'L', 'R', as returned by the functions
             buildTreeUpDown and buildTreeGroundUp.
          2) A lists of lists, in which each sub-list is a row of the tree. Each row
             must be a list in which each member of the list is a float.
          3) A file name, which must be a string with extension .txt. The file must
             contain data representing a tree, with one row per line in the file, and
             numbers in each row separated by a single space. 

    size: in case you wish the function to work with a randomly generated tree, you
          can specify here how many rows you want the tree to have. Parameter must be
          int. Random: 5.

    printTree: in case you wish the function to work with a randomly generated tree,
               you can choose to print the tree to the interactive prompt or the
               standard output by setting this flat to 'yes'. Not recommended for big trees.

    fileName: in case you wish the function to work with a randomly generated tree, you
              can choose to save the tree data in a file, whose name (and if so desired,
              path) must be provided here as a string. The recommended file extension is
              .txt.     
    """

    if tree == 'random':
        
        if fileName:
            tree = generateTree(size, toFile='toFile', fileName=fileName)
            checkPrintTree(tree, printTree)
            highestPath, pathValue = getHighestPathAndPathValue

        elif fileName is None:
            tree = generateTree(size)
            checkPrintTree(tree, printTree)
            highestPath, pathValue = getHighestPathAndPathValue(tree)

        else: raise TypeError(fileName,
                              'Please provide a valid file name and extension.')

    properties = ['value',
                  'position',
                  'row',
                  'L',
                  'R'
                  ]
    if (isinstance(tree, dict) and [node.__contains__(pro)
                                     for key, node in tree.items()
                                     for pro in properties]):
        nodes = tree
        highestPath = maxValuePath(nodes, 1, [1])
        pathValue = getHighestPathValue(nodes, highestPath)

    elif isinstance(tree, str) and tree.endswith('.txt'):
        rawTree = getFromFile(tree)
        tree = getTree(rawTree)
        highestPath, pathValue = getHighestPathAndPathValue(tree)

    elif ([isinstance(row, list) 
           for row in tree]
          and [isinstance(num, float)
               for row in tree
               for num in row]):
        highestPath, pathValue = getHighestPathAndPathValue(tree)

    else: raise TypeError(tree, 'Plase provide a valid data structure.')

    return highestPath, pathValue