473,320 Members | 1,794 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

view data in python class

I am following some code written for the binary tree.
The tree variable is the class object.
The program is running fine. however, I really confuse with the way that python storing the data in object. I can not view the data store in this tree the only thing that I can see when try to print is:

>> print tree
<treepredict.decisionnode instance at 0x03E0E6C0>

what is the way to view all the data store in this "tree" object???
Feb 8 '10 #1

✓ answered by bvdet

#1 Here's a simple example of recursion:
Expand|Select|Wrap|Line Numbers
  1. >>> def int_with_commas(s):
  2. ...     if len(s) <= 3:
  3. ...         return s
  4. ...     return '%s,%s' % (int_with_commas(s[:-3]), s[-3:])
  5. ... 
  6. >>> int_with_commas('1234567890')
  7. '1,234,567,890'
  8. >>> 
The same function without recursion:
Expand|Select|Wrap|Line Numbers
  1. >>> def int_with_commas1(s):
  2. ...     output = ""
  3. ...     while True:
  4. ...         s, sub = s[:-3], s[-3:]
  5. ...         if not sub:
  6. ...             return output
  7. ...         if output:
  8. ...             output = "%s,%s" % (sub, output)
  9. ...         else:
  10. ...             output = sub
  11. ...             
  12. >>> print int_with_commas1('1234567890')
  13. 1,234,567,890
  14. >>> print int_with_commas1('90')
  15. 90
  16. >>> 
Sometimes recursion makes a function easier to write, and sometimes not.


#2 Actually, it could be done like this:
Expand|Select|Wrap|Line Numbers
  1.     def __init__(self,col=-1,value=None,results=None,tb=None,fb=None):
  2.         self.col=col
  3.         self.value=value
  4.         self.results=results
  5.         self.tb=tb
  6.         self.fb=fb
  7.  
  8.     def __str__(self):
  9.         return "\n".join(self.print_tree(self))
  10.  
  11.     def print_tree(self, next, pad="", results=[]):
  12.         if next:
  13.             s = "%sValue:%s - Results:%s" % (pad, getattr(next, 'value', "NONE"), getattr(next, 'results', "NONE"))
  14.             results.append(s)
  15.             for branch in ('fb', 'tb'):
  16.                 obj = getattr(next, branch, None)
  17.                 if obj:
  18.                     for attr in ('value', 'results'):
  19.                         s = "%sBranch: %s - %s: %s" % (pad, branch, attr, getattr(obj, attr, 'NONE'))
  20.                         results.append(s)
  21.                     self.print_tree(obj, pad+"  ", results)
  22.                 else:
  23.                     results.append("%s  Object '%s' evaluates False" % (pad, branch))
  24.         return results
  25.  

7 1886
bvdet
2,851 Expert Mod 2GB
To view the data in a class instance using print, define a __str__() method. A simple example:
Expand|Select|Wrap|Line Numbers
  1. >>> class Point(object):
  2. ...     def __init__(self, x=0.0, y=0.0, z=0.0):
  3. ...         self.x = x
  4. ...         self.y = y
  5. ...         self.z = z
  6. ...     def __str__(self):
  7. ...         return "Point(%s, %s, %s)" % (self.x, self.y, self.z)
  8. ...     
  9. >>> Point(2,2,2)
  10. <__main__.Point object at 0x00F47050>
  11. >>> print Point(2,2,2)
  12. Point(2, 2, 2)
  13. >>> 
Feb 8 '10 #2
Thank you bvdet,

however the object "tree" that I got is kind da class for binary tree. It seem like there are a lot of objects (node data) in just one main object.
sorry for a little confuse question I post the code for you here

Expand|Select|Wrap|Line Numbers
  1. mydata = [['slashdot', 'USA', 'yes', '18', 'None'],
  2.           ['google', 'France', 'yes', '23', 'Premium'],
  3.           ['digg', 'USA', 'yes', '24', 'Basic'],
  4.           ['kiwitobes', 'France', 'yes', '23', 'Basic'],
  5.           ['google', 'UK', 'no', '21', 'Premium'],
  6.           ['(direct)', 'New Zealand', 'no', '12', 'None'],
  7.           ['(direct)', 'UK', 'no', '21', 'Basic'],
  8.           ['google', 'USA', 'no', '24', 'Premium'],
  9.           ['slashdot', 'France', 'yes', '19', 'None'],
  10.           ['digg', 'USA', 'no', '18', 'None'],
  11.           ['google', 'UK', 'no', '18', 'None'],
  12.           ['kiwitobes', 'UK', 'no', '19', 'None'],
  13.           ['digg', 'New Zealand', 'yes', '12', 'Basic'],
  14.           ['slashdot', 'UK', 'no', '21', 'None'],
  15.           ['google', 'UK', 'yes', '18', 'Basic'],
  16.           ['kiwitobes', 'France', 'yes', '19', 'Basic']]
  17. class decisionnode:
  18.     def __init__(self,col=-1,value=None,results=None,tb=None,fb=None):
  19.         self.col=col
  20.         self.value=value
  21.         self.results=results
  22.         self.tb=tb
  23.         self.fb=fb
  24. def divideset(rows,column,value):
  25.     # make a function that tells us if a row is in the first group (true)
  26.     # or the second group (false)
  27.     if isinstance(value,int) or isinstance(value,float):
  28.         split_function=lambda row:row[column]>=value
  29.     else:
  30.         split_function=lambda row:row[column]==value
  31.     # divide the rows into two sets and return them
  32.     set1=[row for row in rows if split_function(row)]
  33.     set2=[row for row in rows if not split_function(row)]
  34.     return(set1,set2)
  35. def uniquecounts(rows):
  36.     results ={}
  37.     for row in rows:
  38.         # the result is the last column
  39.         r=row[len(row)-1]
  40.         if r not in results: results[r]=0
  41.         results[r]+=1
  42.     return results
  43. def entropy(rows):
  44.     from math import log
  45.     log2 = lambda x:log(x)/log(2)
  46.     results=uniquecounts(rows)
  47.     # now calculate the entropy
  48.     ent=0.0
  49.     for r in results.keys():
  50.         p=float(results[r])/len(rows)
  51.         ent=ent-p*log2(p)
  52.     return ent
  53. def buildtree(rows,scoref=entropy):
  54.     if len(rows)==0: return decisionnode()
  55.     current_score=scoref(rows)
  56.  
  57.     # Set up some variables to track the best criteria
  58.     best_gain=0.0
  59.     best_criteria=None
  60.     best_sets=None
  61.  
  62.     column_count=len(rows[0])-1
  63.     for col in range(0,column_count):
  64.         # Generate the list of different value in
  65.         # this column
  66.         column_values={}
  67.         for row in rows:
  68.             column_values[row[col]]=1
  69.         # now try dividing the rows up for each value
  70.         # in this column
  71.         for value in column_values.keys():
  72.             (set1,set2)=divideset(rows,col,value)
  73.  
  74.             # information gain
  75.             p=float(len(set1))/len(rows)
  76.             gain=current_score-p*scoref(set1)-(1-p)*scoref(set2)
  77.             if gain>best_gain and len(set1)>0 and len(set2)>0:
  78.                 best_gain=gain
  79.                 best_criteria=(col,value)
  80.                 best_sets=(set1,set2)
  81.     # Create the subbranches
  82.     if best_gain>0:
  83.         trueBranch=buildtree(best_sets[0])
  84.         falseBranch=buildtree(best_sets[1])
  85.         return decisionnode(col=best_criteria[0],value=best_criteria[1],tb=trueBranch,fb=falseBranch)
  86.     else:
  87.         return decisionnode(results=uniquecounts(rows))
I save this code in treecart.py and call it in pythonshell. Then creating the binary tree as follows:

>> tree = treecart.buildtree(treecart.mydata)

Now, I have a problem of how i can preview this kind of variable because it seem that tree variable has several object data (node data) in it.

thank you in advance, this board have been a very great helper to me.
Feb 8 '10 #3
bvdet
2,851 Expert Mod 2GB
You will need a recursive function to evaluate all the branches. I wrote one to recursively evaluate the value and results attributes for the object, fb branch and tb branch.
Expand|Select|Wrap|Line Numbers
  1. x = buildtree(mydata)
  2.  
  3. def print_tree(x, pad="", results=[]):
  4.     if x:
  5.         s = "%sValue:%s - Results:%s" % (pad, getattr(x, 'value', "NONE"), getattr(x, 'results', "NONE"))
  6.         results.append(s)
  7.         for branch in ('fb', 'tb'):
  8.             obj = getattr(x, branch, None)
  9.             if obj:
  10.                 for attr in ('value', 'results'):
  11.                     s = "%sBranch: %s - %s: %s" % (pad, branch, attr, getattr(obj, attr, 'NONE'))
  12.                     results.append(s)
  13.                 print_tree(obj, pad+"  ", results)
  14.             else:
  15.                 results.append("%s  Object '%s' evaluates False" % (pad, branch))
  16.     return results
  17.  
  18. print
  19. sList = print_tree(x)
  20. print "\n".join(sList)
The output:
Expand|Select|Wrap|Line Numbers
  1. >>> 
  2. Value:google - Results:None
  3. Branch: fb - value: slashdot
  4. Branch: fb - results: None
  5.   Value:slashdot - Results:None
  6.   Branch: fb - value: yes
  7.   Branch: fb - results: None
  8.     Value:yes - Results:None
  9.     Branch: fb - value: 21
  10.     Branch: fb - results: None
  11.       Value:21 - Results:None
  12.       Branch: fb - value: None
  13.       Branch: fb - results: {'None': 3}
  14.         Value:None - Results:{'None': 3}
  15.           Object 'fb' evaluates False
  16.           Object 'tb' evaluates False
  17.       Branch: tb - value: None
  18.       Branch: tb - results: {'Basic': 1}
  19.         Value:None - Results:{'Basic': 1}
  20.           Object 'fb' evaluates False
  21.           Object 'tb' evaluates False
  22.     Branch: tb - value: None
  23.     Branch: tb - results: {'Basic': 4}
  24.       Value:None - Results:{'Basic': 4}
  25.         Object 'fb' evaluates False
  26.         Object 'tb' evaluates False
  27.   Branch: tb - value: None
  28.   Branch: tb - results: {'None': 3}
  29.     Value:None - Results:{'None': 3}
  30.       Object 'fb' evaluates False
  31.       Object 'tb' evaluates False
  32. Branch: tb - value: 18
  33. Branch: tb - results: None
  34.   Value:18 - Results:None
  35.   Branch: fb - value: None
  36.   Branch: fb - results: {'Premium': 3}
  37.     Value:None - Results:{'Premium': 3}
  38.       Object 'fb' evaluates False
  39.       Object 'tb' evaluates False
  40.   Branch: tb - value: yes
  41.   Branch: tb - results: None
  42.     Value:yes - Results:None
  43.     Branch: fb - value: None
  44.     Branch: fb - results: {'None': 1}
  45.       Value:None - Results:{'None': 1}
  46.         Object 'fb' evaluates False
  47.         Object 'tb' evaluates False
  48.     Branch: tb - value: None
  49.     Branch: tb - results: {'Basic': 1}
  50.       Value:None - Results:{'Basic': 1}
  51.         Object 'fb' evaluates False
  52.         Object 'tb' evaluates False
  53. >>> 
The output does not make much sense to me.
Feb 8 '10 #4
Glenton
391 Expert 256MB
The point is that if you want to preview it, you have to tell the class how! If you don't know what the preview is meant to look like, how will the class know?!

When you define the __str__ function you can put anything in there. You can do whatever calculations you need to do etc to show the value you'd like to see!

If you want help with that you need to tell us what kind of thing you want to see, or at least what the code is doing...
Feb 9 '10 #5
Thank you for all of your answer, I have couple more questions though.

1. could you point me to the source of references related to this kind of variable? (is that call recursion or generator)
2. to view structure of "tree" variable, the only way is to write the code like the one that you provided in the previous post right?

Thank you in advance and thank you for patient with the newbie
Feb 9 '10 #6
bvdet
2,851 Expert Mod 2GB
#1 Here's a simple example of recursion:
Expand|Select|Wrap|Line Numbers
  1. >>> def int_with_commas(s):
  2. ...     if len(s) <= 3:
  3. ...         return s
  4. ...     return '%s,%s' % (int_with_commas(s[:-3]), s[-3:])
  5. ... 
  6. >>> int_with_commas('1234567890')
  7. '1,234,567,890'
  8. >>> 
The same function without recursion:
Expand|Select|Wrap|Line Numbers
  1. >>> def int_with_commas1(s):
  2. ...     output = ""
  3. ...     while True:
  4. ...         s, sub = s[:-3], s[-3:]
  5. ...         if not sub:
  6. ...             return output
  7. ...         if output:
  8. ...             output = "%s,%s" % (sub, output)
  9. ...         else:
  10. ...             output = sub
  11. ...             
  12. >>> print int_with_commas1('1234567890')
  13. 1,234,567,890
  14. >>> print int_with_commas1('90')
  15. 90
  16. >>> 
Sometimes recursion makes a function easier to write, and sometimes not.


#2 Actually, it could be done like this:
Expand|Select|Wrap|Line Numbers
  1.     def __init__(self,col=-1,value=None,results=None,tb=None,fb=None):
  2.         self.col=col
  3.         self.value=value
  4.         self.results=results
  5.         self.tb=tb
  6.         self.fb=fb
  7.  
  8.     def __str__(self):
  9.         return "\n".join(self.print_tree(self))
  10.  
  11.     def print_tree(self, next, pad="", results=[]):
  12.         if next:
  13.             s = "%sValue:%s - Results:%s" % (pad, getattr(next, 'value', "NONE"), getattr(next, 'results', "NONE"))
  14.             results.append(s)
  15.             for branch in ('fb', 'tb'):
  16.                 obj = getattr(next, branch, None)
  17.                 if obj:
  18.                     for attr in ('value', 'results'):
  19.                         s = "%sBranch: %s - %s: %s" % (pad, branch, attr, getattr(obj, attr, 'NONE'))
  20.                         results.append(s)
  21.                     self.print_tree(obj, pad+"  ", results)
  22.                 else:
  23.                     results.append("%s  Object '%s' evaluates False" % (pad, branch))
  24.         return results
  25.  
Feb 9 '10 #7
Glenton
391 Expert 256MB
By the way, recursion, though sometimes easier to write, is often more expensive in process time. So if your real data set is much bigger that what you've suggested then you need to rethink. Sometimes the best is to use what's known as memoization (?). But basically you save the answers as you generate them, and reuse them rather than regenerate them. The easy way to do this is to pass the saved data in and out of the function.

Also, "to understand recursion you first have to understand recursion" is a terribly old coders joke, but it's almost obligatory to include it in any discussion so there it is.

To answer your second question: the only way to view the tree variable is to write code that returns the data you want to view.
It could be as simple as:
Expand|Select|Wrap|Line Numbers
  1. def __str__(self):
  2.     return self.value, self.results
However, it's fundamentally up to you to decide what the "tree" variable should look like. If you help us with what it should look like, then we can help you with how to code it!
Feb 10 '10 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Tony Marston | last post by:
For those who you thought my method of implementing OO principles in PHP was totally wrong - see http://www.tonymarston.co.uk/php-mysql/good-bad-oop.html for details, you can now read...
4
by: Neil Zanella | last post by:
Hello, I would like to know whether it is possible to define static class methods and data members in Python (similar to the way it can be done in C++ or Java). These do not seem to be mentioned...
4
by: spar | last post by:
I'm converting a Perl script to Python and have run into something I'm not sure how to do in Python. In Perl, I am running through a couple loops and inserting values directly into a complex...
8
by: Jef Driesen | last post by:
I'm implementing some image processing algorithms in C++. I created a class called 'image' (see declaration below), that will take care of the memory allocations and some basic (mathematical)...
0
by: Brian Henry | last post by:
Here is another virtual mode example for the .NET 2.0 framework while working with the list view. Since you can not access the items collection of the list view you need to do sorting another...
4
by: Griff | last post by:
Two questions really, the first one "conceptual" and the other more involved with design: 1 - There are two schools of thought where I work on the role of the "controller" task. The first is...
13
by: DH | last post by:
Hi, I'm trying to strip the html and other useless junk from a html page.. Id like to create something like an automated text editor, where it takes the keywords from a txt file and removes them...
6
by: Bill44077 | last post by:
Hi, I am new to the MVP pattern and one of the main reasons that we are going this route is because we are doing Scrum with 30 day sprints - so we have a continually morphing design. We are...
0
by: Jacob Donajkowski | last post by:
Once the user logs in I want to have the users switch from the Roster View to the Profile View and enter their profile infomation and save it. Then the next time they login and go to the Profile...
162
by: Sh4wn | last post by:
Hi, first, python is one of my fav languages, and i'll definitely keep developing with it. But, there's 1 one thing what I -really- miss: data hiding. I know member vars are private when you...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.