Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

python - Can I detect an infinitely nested list?

I've noticed an interesting property of Python objects, which is that they can be self-similar. For example, if you have a list and append itself to it, you'll get a list within a list within a list within a list...

x = []
x.append(x)
print(x)   # displayed as "[[...]]"

My question is, can you detect whether or not a list is infinitely nested? I tried x in x, but that's not foolproof -- the code below prints False when it should print True:

x = []
x.append(x)
y = [x, x]
print(y in y)

How can I solve this?

question from:https://stackoverflow.com/questions/65910097/can-i-detect-an-infinitely-nested-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure. Write a function that iterates through the list, building a reference list of IDs found in the list. If any ID appears in one of its sub-lists, you have infinite nesting.

Maintain the list of "ancestor" IDs and recur on each element that's a list.

Can you do the coding now?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...