So I was writing up a simple binary tree in Python and came across [...]
I don\'t believe this to be related to the Ellipsis object, more it seems to have something
Ok, so in points:
You're creating infinite data structure:
def Keys(x,y=[])will use the same 'y' in each call. This just isn't correct.
The print
statement, however, is clever enough not to print an infinite data, but to mark self-reference with a [...] (known as Ellipsis)
a.keys()[1][1][1]and so on. Why shouldn't you?
y = y[:]
statement simply copies the list y. Can be done more soundly with y = list(y)
Try using the following code:
def Keys(x,y=None): if y is None: y = [] if len(x): y += [x[2], Keys(x[0],y), Keys(x[1],y)] return y
But still I guess that it can bite you. You're still using the same variable y (I mean the same object) in three places in one expression:
y += [x[2], Keys(x[0], y), Keys(x[1], y)]
Is that what you really want to achieve? Or maybe you should try:
def mKeys(x,y=None): if y is None: y = [] if len(x): z = [x[2], mKeys(x[0], y), mKeys(x[1],y)] return z return []
It can also appear if you have a circular structure with a list pointing to itself. Like this:
>>> a = [1,2]
>>> a.append(a)
>>> a
[1, 2, [...]]
>>>
Since python can't print out the structure (it would be an infinite loop) it uses the ellipsis to show that there is recursion in the structure.
I'm not quite sure if the question was what what going on or how to fix it, but I'll try to correct the functions above.
In both of them, you first make two recursive calls, which add data to the list y
, and then AGAIN append the returned data to y
. This means the same data will be present several times in the result.
Either just collect all the data without adding to any y
, with something like
return [x[2]]+keys(x[0])+keys(x[1])
or just do the appending in the calls, with something like
y += [x[2]]
keys(x[0], y) #Add left children to y...
keys(x[1], y) #Add right children to y...
return y
(Of course, both these snippets need handling for empty lists etc)
@Abgan also noted that you really don't want y=[]
in the initializer.
I don't understand your code above, but the [...] I think is the Python interpreter skipping infinite data structures. For example:
>>> a = [0, 1]
>>> a[0] = a
>>> a
[[...], 1]
It looks like your tree structure is becoming looped.
The answers about slice objects are beside the point.