如何用Python畫樹?

時間 2021-12-21 20:11:10

1樓:半個馮博士

先寫乙個樹:

class

TreeNode

:def

__init__

(self

,key

):self

.key

=key

self

.right

=None

self

.left

=None

definsert

(self

,key

):if

self

.key

==key

:return

elif

self

.key

ifself

.right

isNone

:self

.right

=BstNode

(key

)else

:self

.right

.insert

(key

)else

:# self.key > key

ifself

.left

isNone

:self

.left

=BstNode

(key

)else

:self

.left

.insert

(key

)def

display

(self

):lines,*

_=self

._display_aux

()for

line

inlines

:print

(line

)def

_display_aux

(self

):"""Returns list of strings, width, height, and horizontal coordinate of the root."""

# No child.

ifself

.right

isNone

andself

.left

isNone

:line='

%s'%self

.key

width

=len

(line

)height=1

middle

=width//2

return

[line

],width

,height

,middle

# Only left child.

ifself

.right

isNone

:lines,n

,p,x

=self

.left

._display_aux()s

='%s'

%self

.keyu=

len(s)

first_line=(

x+1)

*' '+(

n-x-

1)*'_'+s

second_line=x

*' '

+'/'+(

n-x-

1+u)

*' '

shifted_lines=[

line+u

*' '

forline

inlines

]return

[first_line

,second_line]+

shifted_lines,n

+u,p

+2,n

+u//2

# Only right child.

ifself

.left

isNone

:lines,n

,p,x

=self

.right

._display_aux()s

='%s'

%self

.keyu=

len(s)

first_line=s

+x*'_'+(

n-x)

*' '

second_line=(

u+x)

*' '+'

\\'+(

n-x-

1)*' '

shifted_lines=[

u*' '+

line

forline

inlines

]return

[first_line

,second_line]+

shifted_lines,n

+u,p

+2,u

//2# Two children.

left,n

,p,x

=self

.left

._display_aux

()right,m

,q,y

=self

.right

._display_aux()s

='%s'

%self

.keyu=

len(s)

first_line=(

x+1)

*' '+(

n-x-

1)*'_'+s

+y*'_'+(

m-y)

*' '

second_line=x

*' '

+'/'+(

n-x-

1+u+

y)*' '+'

\\'+(

m-y-

1)*' 'ifp

left+=[

n*' ']*(

q-p)

elif

q

right+=[

m*' ']*(

p-q)

zipped_lines

=zip

(left

,right

)lines=[

first_line

,second_line]+

[a+u

*' '+b

fora,b

inzipped_lines

]return

lines,n

+m+u

,max(p

,q)+

2,n+

u//2呼叫主程式:

import

randomb=

TreeNode(50

)for_in

range(50

):b.insert

(random

.randint(0

,100))b

.display

()執行結果:

參考:print binary tree level by level in python

如何用python控制arduino?

FLAGYAN Arduino板子的韌體 下位機 在自帶的IDE裡面有,路徑Examples Firmata StandardFirmata,寫入這個韌體就可以在PC上寫python的程式直接控制,python直接執行在PC上,通過frimata協議給板子發命令執行相應的操作。 許俊彬 Arduin...

請問python如何用docker API和paramiko做webssh?

37丫37 或許可以看看這個 Django實現WebSSH操作Kubernetes Podpython 呼叫kubernetes api,實現對pod的ssh連線,從而進行命令執行等操作 還有一系列的WebSSH相關的文章可以參考 https blog.ops coffee.cn webssh 布道...

如何用python傳送email?

若月寒 fp open filename,rb 務必加上必要的頭,否則傳送後無法正常解碼file.add header Content Disposition attachment filename gbk filename file.add header Content ID 0 file.add...