Search Results

Search found 19539 results on 782 pages for 'pretty print'.

Page 69/782 | < Previous Page | 65 66 67 68 69 70 71 72 73 74 75 76  | Next Page >

  • Python singleton pattern

    - by Javier Garcia
    Hi, someone can tell me why this is incorrect as a singleton pattern: class preSingleton(object): def __call__(self): return self singleton = preSingleton() a = singleton() b = singleton() print a==b a.var_in_a = 100 b.var_in_b = 'hello' print a.var_in_b print b.var_in_a Edit: The above code prints: True hello 100 thank you very much

    Read the article

  • Using Javascript in Adobe Reader

    - by godleuf
    Hi, I am currently using the following script for a few documents: var pp = this.getPrintParams(); pp.interactive = pp.constants.interactionLevel.automatic; this.print(pp); How do I add another command, say document.close() so that it reads the print function and then follows the close document last? Do I simply add the close command right after the print command so it would read var pp = this.getPrintParams(); pp.interactive = pp.constants.interactionLevel.automatic; this.print(pp); document.close(); Thanks.

    Read the article

  • JAVA-how to manually compose a MIME multipart message

    - by Augusto Picciani
    I need to compose manually a MIME multipart message. I don't need to use any library to doing it. I'm trying this without success: out.println("From:myemail@mydomain"); out.flush(); out.println("To:myemail@mydomain"); out.flush(); out.println("Date:Thu, 25 Nov 2011 01:00:50 +0100"); out.flush(); out.println("Subject:manual test 269"); out.flush(); out.println("MIME-version:1.0"); out.flush(); out.print("Content-Type: multipart/mixed; boundary=\"1234567\"\n\n"); out.println("--1234567"); out.flush(); out.println("Content-Type: text/plain; charset:utf-8"); out.flush(); out.print("Content-Transfer-Encoding: 7bit\n\n"); out.flush(); out.print("test message\n\n"); out.flush(); out.println("--1234567"); out.flush(); out.println("Content-Type: text/html; charset:utf-8"); out.flush(); out.print("Content-Transfer-Encoding: 7bit\n\n"); out.flush(); out.print("<p><strong>test message in html</strong></p>\n\n"); out.flush(); out.println("--1234567--"); out.flush(); out.print("\r\n.\r\n"); out.flush(); Problem is that my mail client see the headers (from,subject,date,ecc.) but it doesn't see the message body. If i try without multipart it works fine. Maybe problem is in whitespaces character.

    Read the article

  • Condition checking vs. Exception handling

    - by Aidas Bendoraitis
    When is exception handling more preferable than condition checking? There are many situations where I can choose using one or the other. For example, this is a summing function which uses a custom exception: # module mylibrary class WrongSummand(Exception): pass def sum_(a, b): """ returns the sum of two summands of the same type """ if type(a) != type(b): raise WrongSummand("given arguments are not of the same type") return a + b # module application using mylibrary from mylibrary import sum_, WrongSummand try: print sum_("A", 5) except WrongSummand: print "wrong arguments" And this is the same function, which avoids using exceptions # module mylibrary def sum_(a, b): """ returns the sum of two summands if they are both of the same type """ if type(a) == type(b): return a + b # module application using mylibrary from mylibrary import sum_ c = sum_("A", 5) if c is not None: print c else: print "wrong arguments" I think that using conditions is always more readable and manageable. Or am I wrong? What are the proper cases for defining APIs which raise exceptions and why?

    Read the article

  • wxpython - Nested Notebooks

    - by madtowneast
    I have been trying to make my nested notebooks a little bit more appealing code wise. At the moment, I got this #!/usr/bin/env python import os import sys import datetime import numpy as np from readmonifile import MonitorFile from sortmonifile import sort import wx class NestedPanelOne(wx.Panel): #---------------------------------------------------------------------- # First notebook that creates the tab to select the component number #---------------------------------------------------------------------- def __init__(self, parent, label, data): wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY) sizer = wx.BoxSizer(wx.VERTICAL) #Loop creating the tabs according to the component name nestedNotebook = wx.Notebook(self, wx.ID_ANY) for slabel in sorted(data[label].keys()): tab = NestedPanelTwo(nestedNotebook, label, slabel, data) nestedNotebook.AddPage(tab,slabel) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(nestedNotebook, 1, wx.ALL|wx.EXPAND, 5) self.SetSizer(sizer) class NestedPanelTwo(wx.Panel): #------------------------------------------------------------------------------ # Second notebook that creates the tab to select the main monitoring variables #------------------------------------------------------------------------------ def __init__(self, parent, label, slabel, data): wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY) sizer = wx.BoxSizer(wx.VERTICAL) nestedNotebook = wx.Notebook(self, wx.ID_ANY) for sslabel in sorted(data[label][slabel][data[label][slabel].keys()[0]].keys()): tab = NestedPanelThree(nestedNotebook, label, slabel, sslabel, data) nestedNotebook.AddPage(tab, sslabel) sizer.Add(nestedNotebook, 1, wx.ALL|wx.EXPAND, 5) self.SetSizer(sizer) class NestedPanelThree(wx.Panel): #------------------------------------------------------------------------------- # Third notebook that creates checkboxes to select the monitoring sub-variables #------------------------------------------------------------------------------- def __init__(self, parent, label, slabel, sslabel, data): wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY) labels=[] chbox =[] chboxdict={} for ssslabel in sorted(data[label][slabel][data[label][slabel].keys()[0]][sslabel].keys()): labels.append(ssslabel) for item in list(set(labels)): cb = wx.CheckBox(self, -1, item) chbox.append(cb) chboxdict[item]=cb gridSizer = wx.GridSizer(np.shape(list(set(labels)))[0],3, 5, 5) gridSizer.AddMany(chbox) self.SetSizer(gridSizer) ######################################################################## class NestedNotebookDemo(wx.Notebook): #--------------------------------------------------------------------------------- # Main notebook creating tabs for the monitored components #--------------------------------------------------------------------------------- def __init__(self, parent, data): wx.Notebook.__init__(self, parent, id=wx.ID_ANY, style= wx.BK_DEFAULT ) for label in sorted(data.keys()): print label tab = NestedPanelOne(self,label, data) self.AddPage(tab, label) ######################################################################## class DemoFrame(wx.Frame): #---------------------------------------------------------------------- # Putting it all together #---------------------------------------------------------------------- def __init__(self,data): wx.Frame.__init__(self, None, wx.ID_ANY, "pDAQ monitoring plotting tool", size=(800,400) ) panel = wx.Panel(self) notebook = NestedNotebookDemo(panel, data) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(notebook, 1, wx.ALL|wx.EXPAND, 5) panel.SetSizer(sizer) self.Layout() #Menu Bar to be added later ''' menubar = wx.MenuBar() file = wx.Menu() file.Append(1, '&Quit', 'Exit Tool') menubar.Append(file, '&File') self.SetMenuBar(menubar) self.Bind(wx.EVT_MENU, self.OnClose, id=1) ''' self.Show() #---------------------------------------------------------------------- if __name__ == "__main__": if len(sys.argv) == 1: raise SystemExit("Please specify a file to process") for f in sys.argv[1:]: data=sort.sorting(f) print data['stringHub'].keys() print data.keys() print data[data.keys()[0]].keys() print 'test' app = wx.PySimpleApp() frame = DemoFrame(data) app.MainLoop() print 'testend' and I would like to reduce this whole mess into something that only has three nested for loops, so something like for label in sorted(data.keys()): self.SubNoteBooks[label] = wx.Notebook(self.Notebook, wx.ID_ANY) self.Notebook.AddPage(self.SubNoteBooks[label], label) for slabel in sorted(data[label].keys()): self.SubNoteBooks[label][slabel] = wx.Notebook(self, wx.ID_ANY) self.SubNoteBooks[label].AddPage(self.SubNoteBooks[label][slabel], slabel) for sslabel in sorted(data[label][slabel][data[label][slabel].keys()[0]].keys()): self.SubNoteBooks[label][slabel][sslabel] = wx.Notebook(self.Notebook, wx.ID_ANY) self.Notebook.AddPage(self.SubNoteBooks[label][slabel][sslabel], sslabel) I have been trying to fiddle this around but the problem seems to be the line self.SubNoteBooks[label][slabel] = wx.Notebook(self, wx.ID_ANY) I get the error: Traceback (most recent call last): File "./reducelinenumbers.py", line 162, in <module> frame = DemoFrame(data) File "./reducelinenumbers.py", line 126, in __init__ self.SubNoteBooks[label][slabel] = wx.Notebook(self, wx.ID_ANY) TypeError: 'Notebook' object does not support item assignment I understand why notebook is being type raises a TypeError here. Is there a way around this? Thanks a bunch in advance.

    Read the article

  • PHP Strange error "0:". Possible Object syntax problem?

    - by Michael Stone
    I'm trying to transfer a site from one hosting company to another. I was using 000webhost until the client had hosting and a domain. Now that the client has their domain and hosting, using FatCow.com, I can not for the life of me, debug my PHP code. I'm not getting any errors. I have a successful DB connection. If you procedurally display data, it works, but when I try to use my original objects, something is breaking and just returns "0:". I have all errors on. On old server where the site worked: PHP Version 5.2.11 MySQL Version: 5.0.81 On new server where I get the "0:": PHP Version 5.2.12 MySQL Version 5.0.32 I've setup a test page to test just the output of the variables with the DB connection. Below is my code: <?php error_reporting(E_ALL); ini_set('display_errors', '1'); try { $link = mysql_connect('connectionstring', 'username', 'password'); if (!$link) { die('Could not connect: ' . mysql_error()); } else{ $db = mysql_select_db('a8210422_lit'); } if($db){ include_once('admin/classes/clsPOW.php'); include_once('admin/classes/clsProviders.php'); $pow = new POW(); $prov = new Providers(); $new = $pow->getNew(); $newAr = $new->val(); $get = $prov->getAll($newAr['providerId']); $getAr = $get->val(); $img = $getAr['image']; $name = $getAr['provider']; $desc = $getAr['description']; $zip = $getAr['zip']; $web = $getAr['link']; if($zip==0){ $zip = "Unavailable"; } print $img; print $name; print $desc; print $zip; print $web; } else{ print 'fail!'; } } //catch exception catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?>

    Read the article

  • Calculating the pixel size of a string with Python

    - by Aristide
    I have a Python script which needs to calculate the exact size of arbitrary strings displayed in arbitrary fonts in order to generate simple diagrams. I can easily do it with Tkinter. The problem is the results seem to depend on the version of Python and/or the system. import Tkinter as tk import tkFont root = tk.Tk() times12 = tkFont.Font(family="times",size=12) print times12.metrics("linespace"), print times12.measure("Hello world") times24 = tkFont.Font(family="times",size=24) print times24.metrics("linespace"), print times24.measure("Hello world") Python 2.5 on Mac OS X gives the actual pixel measurements: 12 57 24 116 Python 2.6.1 on Mac OS X gives: 14 58 27 115 Python 2.6.3 on Windows XP gives: 19 71 36 154 Such a need being quite common, I suspect I did something wrong. Any idea?

    Read the article

  • How to start a Python script several functions in

    - by chrissygormley
    Hello, I have a Python script and I want to call it several functions down the script. Example code below: class Name(): def __init__(self): self.name = 'John' self.address = 'Place' self.age = '100' def printName(self): print self.name def printAddress(self): print self.address def printAge(self): print self.age if __name__ == '__main__': Person = Name() Person.printName() Person.printAddress() Person.printage() I execute this code by entering ./name.py. How could I exectute this code from the function printAddress() down the the end of the script? Thanks

    Read the article

  • super function doesn't work inside a maya python module

    - by sfjedi
    Somehow, this works fine in the Maya/Python script editor, but fails when it's inside of my module code. Anyone have any ideas? class ControlShape(object): def __init__(self, *args, **kwargs): print 'Inside ControlShape...' class Cross(ControlShape): def __init__(self, *args, **kwargs): print 'Entering Cross...' super(Cross, self).__init__(*args, **kwargs) print 'Leaving Cross...' x = Cross() This gives me a TypeError: super(type, obj): obj must be an instance or subtype of type.

    Read the article

  • Condensing multiple else if statements, referencing them from a table?

    - by Haskella
    Hi I'm about to type some 500 else if statements into my code (PHP) which have the exact same coding each: if (color=White); rgb = 255-255-255; print rgb; else if (color=Black); rgb = 0-0-0; print rgb; else if (color=Red); rgb = 255-0-0; print rgb; else if (color=Blue); rgb = 0-0-255; print rgb; [the list keeps going] I also (luckily) have a table that displays the color in the first column and rgb value in the next column for 500 of them... how do I use this to save time typing all those else if statements? Some how I have to reference the table file (made in excel, I'm guessing I'll have to save it as .csv?)

    Read the article

  • Mongodb using db.help() on a particular db command

    - by user1325696
    When I type db.help() It returns DB methods: db.addUser(username, password[, readOnly=false]) db.auth(username, password) ... ... db.printShardingStatus() ... ... db.fsyncLock() flush data to disk and lock server for backups db.fsyncUnock() unlocks server following a db.fsyncLock() I'd like to find out how to get more detailed help for the particular command. The problem was with the printShardingStatus as it returned "too many chunks to print, use verbose if you want to print" mongos> db.printShardingStatus() --- Sharding Status --- sharding version: { "_id" : 1, "version" : 3 } shards: { "_id" : "shard0000", "host" : "localhost:10001" } { "_id" : "shard0001", "host" : "localhost:10002" } databases: { "_id" : "admin", "partitioned" : false, "primary" : "config" } { "_id" : "dbTest", "partitioned" : true, "primary" : "shard0000" } dbTest.things chunks: shard0001 12 shard0000 19 too many chunks to print, use verbose if you want to for ce print I found that for that particular command I can specify boolean parameter db.printShardingStatus(true) which wasn't shown using db.help().

    Read the article

  • Why is this logical expression in python False?

    - by W3ctor
    My question is, why are these expressions False? Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> num = raw_input("Choose a number: ") Choose a number: 5 >>> print num 5 >>> print ( num < 18 ) False >>> print ( num == 5 ) False Because if i try this: >>> print ( num > 0 ) True The expression works fine. Thank you for the help!

    Read the article

  • Python's asyncore to periodically send data using a variable timeout. Is there a better way?

    - by Nick Sonneveld
    I wanted to write a server that a client could connect to and receive periodic updates without having to poll. The problem I have experienced with asyncore is that if you do not return true when dispatcher.writable() is called, you have to wait until after the asyncore.loop has timed out (default is 30s). The two ways I have tried to work around this is 1) reduce timeout to a low value or 2) query connections for when they will next update and generate an adequate timeout value. However if you refer to 'Select Law' in 'man 2 select_tut', it states, "You should always try to use select() without a timeout." Is there a better way to do this? Twisted maybe? I wanted to try and avoid extra threads. I'll include the variable timeout example here: #!/usr/bin/python import time import socket import asyncore # in seconds UPDATE_PERIOD = 4.0 class Channel(asyncore.dispatcher): def __init__(self, sock, sck_map): asyncore.dispatcher.__init__(self, sock=sock, map=sck_map) self.last_update = 0.0 # should update immediately self.send_buf = '' self.recv_buf = '' def writable(self): return len(self.send_buf) > 0 def handle_write(self): nbytes = self.send(self.send_buf) self.send_buf = self.send_buf[nbytes:] def handle_read(self): print 'read' print 'recv:', self.recv(4096) def handle_close(self): print 'close' self.close() # added for variable timeout def update(self): if time.time() >= self.next_update(): self.send_buf += 'hello %f\n'%(time.time()) self.last_update = time.time() def next_update(self): return self.last_update + UPDATE_PERIOD class Server(asyncore.dispatcher): def __init__(self, port, sck_map): asyncore.dispatcher.__init__(self, map=sck_map) self.port = port self.sck_map = sck_map self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.bind( ("", port)) self.listen(16) print "listening on port", self.port def handle_accept(self): (conn, addr) = self.accept() Channel(sock=conn, sck_map=self.sck_map) # added for variable timeout def update(self): pass def next_update(self): return None sck_map = {} server = Server(9090, sck_map) while True: next_update = time.time() + 30.0 for c in sck_map.values(): c.update() # <-- fill write buffers n = c.next_update() #print 'n:',n if n is not None: next_update = min(next_update, n) _timeout = max(0.1, next_update - time.time()) asyncore.loop(timeout=_timeout, count=1, map=sck_map)

    Read the article

  • How do I include a frameset under CGI.pm?

    - by neversaint
    I want to have a cgi-script that does two things. Take the input from a form. Generate results base on the input values on a frame. I also want the frame to exist only after the result is generated/printed. Below is the simplified code of what I want to do. But somehow it doesn't work. What's the right way to do it? #!/usr/local/bin/perl use CGI ':standard'; print header; print start_html('A Simple Example'), h1('A Simple Example'), start_form, "What's your name? ",textfield('name'), p, "What's the combination?", p, checkbox_group(-name=>'words', -values=>['eenie','meenie','minie','moe'], -defaults=>['eenie','minie']), p, "What's your favorite color? ", popup_menu(-name=>'color', -values=>['red','green','blue','chartreuse']), p, submit, end_form, hr; if (param()) { # begin create the frame print <<EOF; <html><head><title>$TITLE</title></head> <frameset rows="10,90"> <frame src="$script_name/query" name="query"> <frame src="$script_name/response" name="response"> </frameset> EOF # Finish creating frame print "Your name is: ",em(param('name')), p, "The keywords are: ",em(join(", ",param('words'))), p, "Your favorite color is: ",em(param('color')), hr; } print end_html;

    Read the article

  • Parse and charset: why my script doesn't work

    - by Rebol Tutorial
    I want to extract attribute1 and attribute3 values only. I don't understand why charset doesn't seem to work in my case to "skip" any other attributes (attribute3 is not extracted as I would like): content: {<tag attribute1="valueattribute1" attribute2="valueattribute2" attribute3="valueattribute3"> </tag> <tag attribute2="valueattribute21" attribute1="valueattribute11" > </tag> } attribute1: [{attribute1="} copy valueattribute1 to {"} thru {"}] attribute3: [{attribute3="} copy valueattribute3 to {"} thru {"}] spacer: charset reduce [tab newline #" "] letter: complement spacer to-space: [some letter | end] attributes-rule: [(valueattribute1: none valueattribute3: none) [attribute1 | none] to-space [attribute3 | none] (print valueattribute1 print valueattribute3) | [attribute3 | none] to-space [attribute1 | none] (print valueattribute3 print valueattribute1 valueattribute1: none valueattribute3: none ) | none ] rule: [any [to {<tag } thru {<tag } attributes-rule {>} to {</tag>} thru {</tag>}] to end] parse content rule output is >> parse content rule valueattribute1 none == true >>

    Read the article

  • Display numbers from 1 to 100 without loops or conditions

    - by Harsha
    Is there a way to print numbers from 1 to 100 without using any loops or conditions like "if"? We can easily do using recursion but that again has an if condition. Is there a way to do without using "if" as well? Also no repetitive print statements,or a single print statement containing all the numbers from 1 to 100. A solution in Java is preferable.

    Read the article

  • How to replace the nth column/field in a comma-separated string using sed/awk?

    - by Peter Meier
    assume I have a string "1,2,3,4" Now I want to replace, e.g. the 3rd field of the string by some different value. "1,2,NEW,4" I managed to do this with the following command: echo "1,2,3,4" | awk -F, -v OFS=, '{$3="NEW"; print }' Now the index for the column to be replaced should be passed as a variable. So in this case index=3 How can I pass this to awk? Because this won't work: echo "1,2,3,4" | awk -F, -v OFS=, '{$index="NEW"; print }' echo "1,2,3,4" | awk -F, -v OFS=, '{$($index)="NEW"; print }' echo "1,2,3,4" | awk -F, -v OFS=, '{\$$index="NEW"; print }' Thanks for your help!

    Read the article

  • little java help....

    - by jona
    Hi I am doing some practice problems and trying to print a diagonal line like the example below. I have writen the program you see below and I honestly dont understand what I am doing wrong. I m a java beginner and I cant see how to find the error. Example ( If you only see a straight line of stars...then imagine it diagonally....from top left to bottom right) * * * * * code: class Diagonal{ public static void main(String args[]) { int row, col; for(row = 1; row < 6; row++) { for(col = 1; col <= row; col++) { if(col==row){ System.out.print("*"); } else{ System.out.print(""); } System.out.println(); } } } } I am trying to learn for loops because they really confuse me. Another practice is to print a similar diagonal line but this time from right to left. I cant do that without getting this right however :( I believe they will be pretty similar? Above my reasining is this: As long as the column # is the same as the row number the print the line or otherwise leave a blank....what's wrong with how i did it? THANK YOU!

    Read the article

  • Printing a string and variable in MIPS

    - by Matt
    Here's the C representation of what I'm trying to do in MIPS assembly: printf ("x=%d\n", x); I know that I can do a syscall to easily print x= and I can also do a syscall to print the int x (which is stored in a register). However, that prints them like this (let's say x is 5): x= 5 How can I make them print on the same line?

    Read the article

  • python multiprocess update dictionary synchronously

    - by user1050325
    I am trying to update one common dictionary through multiple processes. Could you please help me find out what is the problem with this code? I get the following output: inside function {1: 1, 2: -1} comes here inside function {1: 0, 2: 2} comes here {1: 0, 2: -1} Thanks. from multiprocessing import Lock, Process, Manager l= Lock() def computeCopyNum(test,val): l.acquire() test[val]=val print "inside function" print test l.release() return a=dict({1: 0, 2: -1}) procs=list() for i in range(1,3): p = Process(target=computeCopyNum, args=(a,i)) procs.append(p) p.start() for p in procs: p.join() print "comes here" print a

    Read the article

  • Why does Printing from Javascript in Air happen out of order?

    - by Bob Bob
    I am trying to print from an Adobe Air App that embeds an AJAX app. The print function looks like this: function printPage() { asyncSetupForPrint(printCallback); } function asyncSetupForPrint(printCallback) { synchronousMethods(); if (printCallback) printCallback(); } function printCallback() { var pjob = new window.runtime.flash.printing.PrintJob; var psprite = window.htmlLoader; pjob.start(); // etc... } However the print dialog is coming up before the synchronous methods have been executed. Is the AIR JS runtime optimizing something? And if so, is there any way to stop it doing that? (The setup function is doing things like changing the resolution to huge*huge so that the print out looks ok.)

    Read the article

  • Type problem with Observable.Create from Boo

    - by Tristan
    I'm trying to use Reactive Extensions from Boo and am running into type problems. Here's the basic example: def OnSubscribe(observer as IObservable[of string]) as callable: print "subscribing" def Dispose(): print "disposing" return Dispose observable = System.Linq.Observable.Create[of string](OnSubscribe) observer = System.Linq.Observer.Create[of string]({x as string | print x}) observable.Subscribe(observer) The Subscribe here gives a System.InvalidCastException: Cannot cast from source type to destination type. The issue appears to be with how I'm creating the observable, but I've struggled to see where the type problem arises from. Ideas?

    Read the article

  • How do implement a breadth first traversal?

    - by not looking for answer
    //This is what I have. I thought pre-order was the same and mixed it up with depth first! import java.util.LinkedList; import java.util.Queue; public class Exercise25_1 { public static void main(String[] args) { BinaryTree tree = new BinaryTree(new Integer[] {10, 5, 15, 12, 4, 8 }); System.out.print("\nInorder: "); tree.inorder(); System.out.print("\nPreorder: "); tree.preorder(); System.out.print("\nPostorder: "); tree.postorder(); //call the breadth method to test it System.out.print("\nBreadthFirst:"); tree.breadth(); } } class BinaryTree { private TreeNode root; /** Create a default binary tree */ public BinaryTree() { } /** Create a binary tree from an array of objects */ public BinaryTree(Object[] objects) { for (int i = 0; i < objects.length; i++) { insert(objects[i]); } } /** Search element o in this binary tree */ public boolean search(Object o) { return search(o, root); } public boolean search(Object o, TreeNode root) { if (root == null) { return false; } if (root.element.equals(o)) { return true; } else { return search(o, root.left) || search(o, root.right); } } /** Return the number of nodes in this binary tree */ public int size() { return size(root); } public int size(TreeNode root) { if (root == null) { return 0; } else { return 1 + size(root.left) + size(root.right); } } /** Return the depth of this binary tree. Depth is the * number of the nodes in the longest path of the tree */ public int depth() { return depth(root); } public int depth(TreeNode root) { if (root == null) { return 0; } else { return 1 + Math.max(depth(root.left), depth(root.right)); } } /** Insert element o into the binary tree * Return true if the element is inserted successfully */ public boolean insert(Object o) { if (root == null) { root = new TreeNode(o); // Create a new root } else { // Locate the parent node TreeNode parent = null; TreeNode current = root; while (current != null) { if (((Comparable)o).compareTo(current.element) < 0) { parent = current; current = current.left; } else if (((Comparable)o).compareTo(current.element) > 0) { parent = current; current = current.right; } else { return false; // Duplicate node not inserted } } // Create the new node and attach it to the parent node if (((Comparable)o).compareTo(parent.element) < 0) { parent.left = new TreeNode(o); } else { parent.right = new TreeNode(o); } } return true; // Element inserted } public void breadth() { breadth(root); } // Implement this method to produce a breadth first // search traversal public void breadth(TreeNode root){ if (root == null) return; System.out.print(root.element + " "); breadth(root.left); breadth(root.right); } /** Inorder traversal */ public void inorder() { inorder(root); } /** Inorder traversal from a subtree */ private void inorder(TreeNode root) { if (root == null) { return; } inorder(root.left); System.out.print(root.element + " "); inorder(root.right); } /** Postorder traversal */ public void postorder() { postorder(root); } /** Postorder traversal from a subtree */ private void postorder(TreeNode root) { if (root == null) { return; } postorder(root.left); postorder(root.right); System.out.print(root.element + " "); } /** Preorder traversal */ public void preorder() { preorder(root); } /** Preorder traversal from a subtree */ private void preorder(TreeNode root) { if (root == null) { return; } System.out.print(root.element + " "); preorder(root.left); preorder(root.right); } /** Inner class tree node */ private class TreeNode { Object element; TreeNode left; TreeNode right; public TreeNode(Object o) { element = o; } } }

    Read the article

< Previous Page | 65 66 67 68 69 70 71 72 73 74 75 76  | Next Page >