python遍歷多維序列搜尋 棧

2021-09-25 10:17:18 字數 1628 閱讀 7672

def

listfiand

(w,obj)

: li =w

k1 =

bate =

#外字典,記錄所有的元素

li2=

str(li)

h2 = li2.find(

"%s"

%obj)

#用字串搜尋obj的位置

print

("h2="

,h2)

print

("h3="

,li2.count(

"[",

0,h2)

)print

("h4="

,li2.count(

"]",

0,h2)

) h=1+

abs(li2.count(

"[",

0,h2)

-li2.count(

"]",

0,h2)

)#用"["和"]"之差鎖定在幾維列表中,元組可以用"()",如果混合可迭代物件(序列),可以盡可能的把h寫大

print

(h)for x, i in

enumerate

(li)

: bate[

"[%d]"

% x]

= i#將列表加入字典進行遍歷,字典的key值就是obj在多維列表的下標

while h:

h-=1 dis =

#迴圈字典

for k, v in bate.items():

iftype

(v)==

list

:for x, i in

enumerate

(v):

dis[k+

"[%d]"

% x]

= i#進行座標拼接

bate.update(dis)

#加入外部字典

list1=

for k , v in bate.items():

#遍歷外部字典,同時輸出key和values

if v == obj:

#判斷字典中的中的值是否符合

k=k.strip()[

1:-1

].split(

"]["

)#處理得到的座標,

list2=

for i in k :

int(i)

)#可以得到所有在序列中的obj的下標

print

(bate)

return k1

li =

["hello"

,'seven',[

[[[[

[[0,

[0]]

]]]]

]],[

"mon",[

"h",

"kelly"],

'all'],

123,

446]

print

(listfiand(li,0)

)#輸出:[[2, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 1, 0]]分別表示兩個零的座標

Python 二叉搜尋樹的後序遍歷序列

輸入乙個整數陣列,判斷該陣列是不是某二叉搜尋樹的後序遍歷的結果。如果是則輸出yes,否則輸出no。假設輸入餓陣列的任意兩個數字都互不相同。class treenode def init self,x self.val x self.left none self.right none class so...

二叉搜尋樹的後序遍歷序列和前序遍歷序列

輸入乙個整數陣列,判斷該陣列是否是某二叉搜尋樹的後序遍歷結果 注 二叉搜素樹的左子樹結點小於根結點 右子樹結點大於根結點 思路 可以先找到二叉樹的根結點,在基於根結點把整顆樹的遍歷序列拆分成左子樹對應的子串行和右子樹對應的子串行,在遞迴處理這兩個子串行 defsequence arr if len ...

python之 序列與字典遍歷

在python中有六種內建的序列 列表 元組 字串 unicode字串 buffer物件和xrange物件。在這裡暫時只討論字串 列表和元組的遍歷。一 序列遍歷 序列有兩種遍歷 一種通過值 另外一種通過索引 1.1 值遍歷 s abc for x in s print x z andy leaf f...