Full disclosure, this is part of a homework assignment (though a small snippet, the project itself is a game playing AI).
I have this function built into a tree node class:
def recursive_score_calc(self):
current_score = self.board
for c in self.children:
child_score = c.recursive_score_calc()
if(turn_color == 1):
if(child_score > current_score):
current_score = child_score
else:
if(child_score < current_score):
current_score = child_score
self.recursive_score = current_score
return current_score
On a tree of depth 1 (a root and some children), it hits the Python recursion limit already. The function is designed to use dynamic programming to build a min-max tree from the bottom up. To be honest, I have no idea why this isn't working as intended, but I am fairly new to Python as well.
Good people of Stack Overflow: Why does this code give me a stack overflow?
The Entire Class in question:
from Numeric import *
class TreeNode:
children = []
numChildren = 0
board = zeros([8,8], Int)
turn_color = 0 # signifies NEXT to act
board_score = 0 # tally together board items
recursive_score = 0 # set when the recursive score function is called
def __init__(self, board, turn_color):
self.board = copy.deepcopy(board)
self.turn_color = turn_color
for x in range (0,7):
for y in range (0,7):
self.board_score = self.board_score + self.board[x][y]
def add_child(self, child):
self.children.append(child)
self.numChildren = self.numChildren + 1
def recursive_score_calc(self):
current_score = self.board # if no valid moves, we are the board. no move will make our score worse
for c in self.children:
child_score = c.recursive_score_calc()
if(turn_color == 1):
if(child_score > current_score):
current_score = child_score
else:
if(child_score < current_score):
current_score = child_score
self.recursive_score = current_score
return current_score
The function that interacts with this (Please Note, this is bordering on the edge of what is appropriate to post here, I'll remove this part after I accept an answer): [It didn't turn out to be the critical part anyways]
This bit of your code:
class TreeNode:
children = []
means that every instance of the class shares the same children list. So, in this bit:
def add_child(self, child):
self.children.append(child)
you're appending to the "class-global" list. So, of course, every node is a child of every other node, and disaster is guaranteed.
Fix: change your class to
class TreeNode(object):
numChildren = 0
board = zeros([8,8], Int)
turn_color = 0 # signifies NEXT to act
board_score = 0 # tally together board items
recursive_score = 0 # set when the recursive score function is called
def __init__(self, board, turn_color):
self.children = []
self.board = copy.deepcopy(board)
self.turn_color = turn_color
... etc, etc ...
the rest doesn't need to change to fix this bug (though there may be opportunities to improve it or fix other bugs, I have not inspected it deeply), but failing to assign self.children in __init__ is causing your current bug, and failing to inherit from object (unless you're using Python 3, but I'd hope you would mention this little detail if so;-) is just a bug waiting to happen.
It looks like self.children contains self.
EDIT:
The children property is being initialized to the same array instance for every instance of the TreeNode class.
You need to create a separate array instance for each TreeNode instance by adding self.children = [] to __init__.
The board array has the same problem.
Related
I'm writing a linked list in Python and I've come across an issue which is really troublesome and terrible for debugging and I feel like I'm missing something about Python. I'm supposed to create a singly linked list with some basic functionalities. One of them is the take() function, which is meant to create a new list of n first elements of the original list.
However, creating a new instance of the LinkedList class seems to change the .self parameter and the variable node is modified, as the attribute .next is turned to None. In result, when creating a list and then trying to make a new one out of the n elements of it, the program runs indefinitely, but no matter which part I look at, I cannot find the loop or the reason behind it.
class LinkedList:
def __init__(self, head=None):
self.head = head
def is_empty(self):
if self.head == None:
return True
else:
return False
def add_last(self, node):
if self.is_empty():
self.head = node
return
nextEl = self.head
while True:
if nextEl.next is None:
nextEl.next = node
return
nextEl = nextEl.next
def take(self, n):
node = self.head
newHead = self.head
newHead.next = None
newList = LinkedList(newHead)
count = 0
while count < n:
newList.add_last(node.next)
node = node.next
count += 1
return newList
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
Thank you for all your help.
In the take() function the line
newHead.next = None
modifies a node of the linked list, breaking this list. You can fix this as follows:
def take(self, n):
node = self.head
newHead = Node(self.head.data)
newList = LinkedList(newHead)
count = 0
while count < n:
newList.add_last(node.next)
node = node.next
count += 1
return newList
This, however, still will not work correctly since there is a problem with the add_last() function too. This function, I think, is supposed to add a node as the last element of a linked list, but since you do not modify the next attribute of the node, you actually append a whole linked list starting with that node. This can be fixed in the following way:
def add_last(self, node):
if self.is_empty():
self.head = node
return
nextEl = self.head
while True:
if nextEl.next is None:
nextEl.next = Node(node.data)
return
nextEl = nextEl.next
There are more issues. For example, take(sefl, n) will actually create a list of n+1 elements and will throw an exception if it is applied to a linked list that does not have that many elements.
I have to count nodes in a binary tree recursively. I'm new to python and can't find any solution for my problem to finish my code.
This is what I have already tried. As you can see it is not complete, and I can't figure out where to go.
class Tree:
def __init__(self, root):
self.root = root
def add(self, subtree):
self.root.children.append(subtree)
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children if children is not None else []
def check_root(tree):
if tree.root is None:
return 0
if tree.root is not None:
return count_nodes(tree)
def count_nodes(tree):
if tree.root.children is not None:
j = 0
for i in tree.root.children:
j = 1 + count_nodes(tree)
return j
print(count_nodes(Tree(None))) # 0
print(count_nodes(Tree(Node(10)))) # 1
print(count_nodes(Tree(Node(5, [Node(6), Node(17)])))) #3
With every new step I'm getting different error. E.g. with this code I have exceeded maximum recursion depth.
Thank you for your time reading this. Any hint or help what to do next would be greatly appreciated.
I would start by passing the root node to the count_nodes function -
print(count_nodes(Tree(None)).root) # 0
print(count_nodes(Tree(Node(10))).root) # 1
print(count_nodes(Tree(Node(5, [Node(6), Node(17)]))).root) #3
or make a helper function for that.
Then the count_nodes function can simply look like this
def count_nodes(node):
return 1 + sum(count_nodes(child) for child in node.children)
EDIT: I have just noticed, you can have a None root, this means, you should also handle that:
def count_nodes(node):
if node is None:
return 0
return 1 + sum(count_nodes(child) for child in node.children)
And if you really want to handle tree or node in one function, you can make it a bit uglier:
def count_nodes(tree_or_node):
if isinstance(tree_or_node, Tree):
return count_nodes(tree_or_node.root)
if tree_or_node is None:
return 0
return 1 + sum(count_nodes(child) for child in tree_or_node.children)
and then you can call it like you originally did.
Your problem is that you're counting the same tree infinitely. Take a look at this line:
j = 1 + count_nodes(tree)
An Easy Way:
Lets assume, A is a binary tree with children or nodes which are not NULL. e.g.
3
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Now in order to count number of nodes, we have a simple workaround.
Recursive Method: >>> get_count(root)
For a binary tree, the basic idea of Recursion is to traverse the tree in Post-Order. Here, if the current node is full, we increment result by 1 and add returned values of the left and right sub-trees such as:
class TestNode():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
Now we move forward to get the count of full nodes in binary tree by using the method below:
def get_count(root):
if (root == None):
return 0
res = 0
if (root.left and root.right):
res += 1
res += (get_count(root.left) +
get_count(root.right))
return res
At the end, in order to run the code, we'll manage a main scope:
Here we create our binary tree A as given above:
if __name__ == '__main__':
root = TestNode(3)
root.left = TestNode(7)
root.right = TestNode(5)
root.left.right = TestNode(6)
root.left.right.left = TestNode(1)
root.left.right.right = TestNode(4)
Now at the end, inside main scope we will print count of binary tree nodes such as:
print(get_Count(root))
Here is the time complexity of this recursive function to get_count for binary tree A.
Time Complexity: O(n)
The objective of my code is to get each seperate word from a txt file and put it into a list and then making a binary search tree using that list to count the frequency of each word and printing each word in alphabetical order along with its frequency. Each word in the can only contain letters, numbers, -, or ' The part that I am unable to do with my beginner programming knowledge is to make the Binary Search Tree using the list I have (I am only able to insert the whole list in one Node instead of putting each word in a Node to make the tree). The code I have so far is this:
def read_words(filename):
openfile = open(filename, "r")
templist = []
letterslist = []
for lines in openfile:
for i in lines:
ii = i.lower()
letterslist.append(ii)
for p in letterslist:
if p not in ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',"'","-",' '] and p.isdigit() == False:
letterslist.remove(p)
wordslist = list("".join(letterslist).split())
return wordslist
class BinaryTree:
class _Node:
def __init__(self, value, left=None, right=None):
self._left = left
self._right = right
self._value = value
self._count = 1
def __init__(self):
self.root = None
def isEmpty(self):
return self.root == None
def insert(self, value) :
if self.isEmpty() :
self.root = self._Node(value)
return
parent = None
pointer = self.root
while (pointer != None) :
if value == pointer._value:
pointer._count += 1
return
elif value < pointer._value:
parent = pointer
pointer = pointer._left
else :
parent = pointer
pointer = pointer._right
if (value <= parent._value) :
parent._left = self._Node(value)
else :
parent._right = self._Node(value)
def printTree(self):
pointer = self.root
if pointer._left is not None:
pointer._left.printTree()
print(str(pointer._value) + " " + str(pointer._count))
if pointer._right is not None:
pointer._right.printTree()
def createTree(self,words):
if len(words) > 0:
for word in words:
BinaryTree().insert(word)
return BinaryTree()
else:
return None
def search(self,tree, word):
node = tree
depth = 0
count = 0
while True:
print(node.value)
depth += 1
if node.value == word:
count = node.count
break
elif word < node.value:
node = node.left
elif word > node.value:
node = node.right
return depth, count
def main():
words = read_words('sample.txt')
b = BinaryTree()
b.insert(words)
b.createTree(words)
b.printTree()
Since you're a beginner I'd advice to implement the tree methods with recursion instead of iteration since this will result to simpler implementation. While recursion might seem a bit difficult concept at first often it is the easiest approach.
Here's a draft implementation of a binary tree which uses recursion for insertion, searching and printing the tree, it should support the functionality you need.
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.count = 1
def __str__(self):
return 'value: {0}, count: {1}'.format(self.value, self.count)
def insert(root, value):
if not root:
return Node(value)
elif root.value == value:
root.count += 1
elif value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
def create(seq):
root = None
for word in seq:
root = insert(root, word)
return root
def search(root, word, depth=1):
if not root:
return 0, 0
elif root.value == word:
return depth, root.count
elif word < root.value:
return search(root.left, word, depth + 1)
else:
return search(root.right, word, depth + 1)
def print_tree(root):
if root:
print_tree(root.left)
print root
print_tree(root.right)
src = ['foo', 'bar', 'foobar', 'bar', 'barfoo']
tree = create(src)
print_tree(tree)
for word in src:
print 'search {0}, result: {1}'.format(word, search(tree, word))
# Output
# value: bar, count: 2
# value: barfoo, count: 1
# value: foo, count: 1
# value: foobar, count: 1
# search foo, result: (1, 1)
# search bar, result: (2, 2)
# search foobar, result: (2, 1)
# search bar, result: (2, 2)
# search barfoo, result: (3, 1)
To answer your direct question, the reason why you are placing all of the words into a single node is because of the following statement inside of main():
b.insert(words)
The insert function creates a Node and sets the value of the node to the item you pass in. Instead, you need to create a node for each item in the list which is what your createTree() function does. The preceeding b.insert is not necessary.
Removing that line makes your tree become correctly formed, but reveals a fundamental problem with the design of your data structure, namely the printTree() method. This method seems designed to traverse the tree and recursively call itself on any child. In your initial version this function worked, because there the tree was mal-formed with only a single node of the whole list (and the print function simply printed that value since right and left were empty).
However with a correctly formed tree the printTree() function now tries to invoke itself on the left and right descendants. The descendants however are of type _Node, not of type BinaryTree, and there is no methodprintTree() declared for _Node objects.
You can salvage your code and solve this new error in one of two ways. First you can implement your BinaryTree.printTree() function as _Node.printTree(). You can't do a straight copy and paste, but the logic of the function won't have to change much. Or you could leave the method where it is at, but wrap each _left or _right node inside of a new BinaryTree so that they would have the necessary printTree() method. Doing this would leave the method where it is at, but you will still have to implement some kind of helper traversal method inside of _Node.
Finally, you could change all of your _Node objects to be _BinaryTree objects instead.
The semantic difference between a node and a tree is one of scope. A node should only be aware of itself, its direct children (left and right), and possibly its parent. A tree on the other hand can be aware of any of its descendents, no matter how far removed. This is accomplished by treating any child node as its own tree. Even a leaf, without any children at all can be thought of as a tree with a depth of 0. This behavior is what lets a tree work recursively. Your code is mixing the two together.
I'm having some difficulties getting python to recursively print out the results from a search tree. I'm native to C++ and I'm completely familiar with using pointers to traverse such structures, but Python does more work than I'm used to. . .
In any case, I'm hoping someone will be able to help me. I'm working on implementing a heuristic to solve the Traveling Salesman Problem; however, I can't begin work on the actual heuristic until I can iterate through my tree. In any case, here's the code for the tree.
class Tree:
branches = dict()
def __init__(self, cities, n=0):
if len(cities) == 1:
nc = list(cities) # create a working list
# grab the nth element of the list, default to head
# Stash that as the node value
self.node = nc[n]
print "Complete!"
elif len(cities) == 0:
print "Doubly Complete!"
else:
nc = list(cities) # create a working list
# grab the nth element of the list, default to head
# Stash that as the node value
self.node = nc[n]
print self.node
del nc[n] # Pop off the nth value from the list
print "deleted city! See?"
print nc
c = 0 # create a counter
for a in nc: # loop through the remaining cities
self.branches[a] = Tree(nc, c) # generate a new tree
c += 1 # increase the counter
def __repr__(self, tier=1):
ret = ("\t" * tier)
ret += self.node
ret += "\n"
for a in self.branches:
ret += self.branches[a].__repr__(tier+1)
return ret
__str__ = __repr__
Here is where the tree is instantiated and printed:
l = ['A','B','C','D']
mine = Tree(l)
print mine
The result of printing the Tree is a RuntimeError: maximum recursion depth exceeded. I'm at my wits end when it comes to what to do next. I would certainly appreciate any help!
Oh! Believe me when I say, if I could use another method than recursion, I would. This particular heuristic requires it, though.
Thanks for any and all help!
This code seems to work. All I did was move the self.branches to inside the __init__. I did so following best practices while debugging. The problem was they were class members not instance members. Having a mutable datatype like dict be a class member just asks for problems.
class Tree:
def __init__(self, cities, n=0):
self.branches = dict()
if len(cities) == 1:
nc = list(cities) # create a working list
# grab the nth element of the list, default to head
# Stash that as the node value
self.node = nc[n]
print "Complete!"
elif len(cities) == 0:
print "Doubly Complete!"
else:
nc = list(cities) # create a working list
# grab the nth element of the list, default to head
# Stash that as the node value
self.node = nc[n]
print self.node
del nc[n] # Pop off the nth value from the list
print "deleted city! See?"
print nc
c = 0 # create a counter
for a in nc: # loop through the remaining cities
self.branches[a] = Tree(nc, c) # generate a new tree
c += 1 # increase the counter
def __repr__(self, tier=1):
ret = ("\t" * tier)
ret += self.node
ret += "\n"
for a in self.branches:
ret += self.branches[a].__repr__(tier+1)
return ret
__str__ = __repr__
t = Tree(["SLC", "Ogden"], 1)
print t
I have a recursive method problem with python, the code is this:
class NodeTree(object):
def __init__(self, name, children):
self.name = name
self.children = children
def count(self):
# 1 + i children's nodes
count = 1
for c in self.children:
count += c.count()
return count
def create_tree(d):
N = NodeTree(d['name'], d['children'])
print N.count()
d1 = {'name':'musica', 'children':[{'name':'rock', 'children':[{'name':'origini','children':[]},
{'name':'rock&roll','children':[]},
{'name':'hard rock', 'children':[]}]},
{'name':'jazz', 'children':[{'name':'origini', 'children':[{'name':'1900', 'children':[]}]},
{'name':'ragtime', 'children':[]}, {'name':'swing', 'children':[]}]}]}
tree = create_tree(d1)
The error is this:
count += c.count()
AttributeError: 'dict' object has no attribute 'count'
I tried anything but it doesn't work.
Anyway, any suggestions?
Thanks!
That's because Python dictionaries do not have a count method.
It'll help if we go over line by line what your code is actually doing.
def count(self):
# 1 + i children's nodes
count = 1
for c in self.children: ## self.children is a list of dictionaries, so each c is a dictionary
count += c.count() ## We are getting .count() of c--which is a dictionary
return count
This is because we passed d1['children'] as self.children, which is a list of dictionaries: [<dict>, <dict>, <dict>, ... ].
Rather than count(), what you should do is call len on the dictionary, to get the number of keys it has, thus becoming:
for c in self.children:
count += len(c)
d['children'] is a list of dict, as you can see in d1 dict.
Now, when you iterate over your children, in NodeTree, which is essentially d['children'] only, you will get dictionary as each element: -
for c in self.children: // c is a `dict` type here
count += c.count() // there is not attribute as `count` for a `dict`.
And hence you got that error.
Well, for once, the create_tree function does not build the tree recursively. So you just add a Node on zero level and the the children are just dictionaries.
The following (modified) code (although quickly typed and sloppy) should do a recursive
build of the tree. Didn't check your count code, but assuming it is correct, it should work.
class NodeTree(object):
def __init__(self, name, children):
self.name = name
self.children = children
def count(self):
# 1 + i children's nodes
count = 1
for c in self.children:
count += c.count()
return count
def deep_create_tree(d):
if len(d["children"]) > 0:
chlds = []
for i in d["children"]:
chlds.append(deep_create_tree(i))
else:
chlds = []
n = NodeTree(d["name"], chlds)
return n
d1 = {'name':'musica', 'children':[{'name':'rock', 'children':[{'name':'origini','children':[]},{'name':'rock&roll','children':[]},{'name':'hard rock', 'children':[]}]},{'name':'jazz', 'children':[{'name':'origini', 'children':[{'name':'1900', 'children':[]}]},{'name':'ragtime', 'children':[]}, {'name':'swing', 'children':[]}]}]}
def scan_tree(tr):
print tr.name, tr.count()
for i in tr.children:
scan_tree(i)
tr = deep_create_tree(d1)
scan_tree(tr)
The best (and the only desirable) way is to have a recursive creation of your node tree. This can be done in two different ways, either make your NodeTree.__init__() recursively init all of the children (which again recursively init all of their children, etc) or you can make your create_tree() function recursive.
I'd personally use recursive __init__(), but it's your call.
Recursive __init__() for creating tree structure:
def __init__(self, name, children=[]):
self.name = name
self.children = []
for c in children:
self.children.append(
self.__class__(c['name'], c['children']))
This way self.children will contain other NodeTrees instead of dicts. Also you no longer need to declare empty children list, instead of:
d2 = {'name':'sterile', 'children':[]}
do
d2 = {'name':'sterile'}
And the initializer will automatically set children to []
If you want to use a recursive create_tree() function, it's also possible, and not a bad idea either. However you will still have to edit the __init__() -method, it no longer takes children as parameter. Or as I did here, it does, but you hardly ever use it.
# NodeTree
def __init__(self, name, children=None):
self.name = name
if children:
self.children = children
def create_tree(d):
N = NodeTree(d['name'])
for c in d['children']:
N.children.append(create_tree(c))
return N
This will have basically the same results.