简体   繁体   中英

Printing a text tree in python

How would you print a tree in python so it looks like the following:

          /\
         /  \
        /    \
       /      \
      /        \
     /          \
    /            \
   /              \
  /                \
 /                  \

The height should be changeable.

def tree(n):
    treeStr = ""
    for i in range(0,n):
        level = " "*(n-i) + "/" + " "*(2*i) + "\\"
        treeStr += level.center(n+1) + "\n"
    print(treeStr)

tree(10); 

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