[Tutor] questions when define a class
Qianyun Guo
qianyunguo at gmail.com
Tue Apr 15 14:56:16 CEST 2014
Hi all, I am trying to get a suffix tree from a string. I use three
classes, Node, Edge, SuffixTree. I have two questions when implementing:
【1】
>>> a = Edge(1,2,3,4)
>>> a.length
1
if I remove '@property' in my code, it returns as below:
>>> a = Edge(1,2,3,4)
>>> a.length
<bound method Edge.length>
>>> a.length()
1
I don't really understand the differences w/ @property, and the differences
of a.length and a.length(), could you explain?
【2】
In SuffixTree, I define two functions, _get_str_from_edge,
_get_str_from_node, the latter depend on the first one (please see my
code). Then I have this problem:
>>> a = SuffixTree('abcd')
>>> a._get_str_from_edge(a.edges[(0,1)])
'abcd$'
>>> a._get_str_from_node(0,1)
TypeError: _get_str_from_edge() takes exactly 2 arguments (3 given)
Could you tell me what's wrong here?
below is my code, __repr__ are removed for convenience.
###################################
class Node:
def __init__(self, parent_node):
self.suffix_node = -1
self.parent = parent_node
self.children = []
def add_child(self, child_node_index):
self.children.append(child_node_index)
class Edge:
def __init__(self, first_char_index, last_char_index,\
source_node_index, dest_node_index):
self.first_char_index = first_char_index
self.last_char_index = last_char_index
self.source_node_index = source_node_index
self.dest_node_index = dest_node_index
@property
def length(self):
return self.last_char_index - self.first_char_index
class SuffixTree:
def __init__(self, string):
self.string = string+'$'
self.N = len(self.string)
self.nodes = []
self.num_nodes = 0
self.edges = {}
#initialize two node tree
root = Node(-1)
root.suffix_node = -1
self._add_node(root)
leaf = Node(0)
leaf.suffix_node = 0
self._add_node(leaf)
self.nodes[0].add_child(1)
edge = Edge(0, self.N, 0, 1)
self._add_edge(edge)
def _get_str_from_edge(self, edge):
return self.string[edge.first_char_index : edge.last_char_index]
def _get_str_from_node(self, source_node_index, dest_node_index):
return self._get_str_from_edge(self, self.edges[(source_node_index,
\
dest_node_index)])
def _add_node(self, node):
self.nodes.append(node)
self.num_nodes += 1
def _add_edge(self, edge):
self.edges[(edge.source_node_index, edge.dest_node_index)] = edge
self.nodes[edge.source_node_index].add_child(edge.dest_node_index)
self.nodes[edge.dest_node_index].parent = edge.source_node_index
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140415/b4156a99/attachment.html>
More information about the Tutor
mailing list