"Python Programming in the JVM"
Volume: 5 Issue: 3, p.68

Listing 1: Python Employee Class

class Employee: def __init__(self, fname="John", lname="Doe", id=1, manager=None, dept=1): self.__firstName = fname self.__lastName = lname self.__id = id self.__manager = manager self.__dept = dept def getManager(self): return self.__manager def __str__(self): values = self.__lastName, self.__firstName, self.__id return join(values,',')

Listing 2: Java Employee Class

public class Employee{ private String firstName, lastName; private int id, dept; private Employee manager; public Employee(){ firstName = "John"; lastName = "Doe"; id = 1; manager=null; dept=1; } public Employee(String fname, String lname, int id, Employee manager, int dept){ firstName = fname; lastName = lname; this.id = id; this.manager = manager; this.dept = dept; } public Employee getManager(){ return manager; } public String toString(){ StringBuffer buf = new StringBuffer(); buf.append(lastName+','); buf.append(firstName+','); buf.append(""+id); return buf.toString(); } Š Š }

Listing 3: Jpython Employee Form

from javax.swing import JFrame, JButton, JTextField, JLabel, JPanel from string import split from pawt import GridBag from Employee import Employee class EmployeeForm(JFrame): def __init__(self): JFrame.__init__(self, "Employee Form") pane = JPanel() self.contentPane.add(pane) bag = GridBag(pane) #Create a name, and id text field. self.__name = JTextField(25) self.__id = JTextField(10) #Create and add a "Name" and "ID" label. name = JLabel("Name", labelFor=self.__name, displayedMnemonic=ord('N')) bag.add(name) id = JLabel("ID", labelFor=self.__id, displayedMnemonic=ord('I')) bag.add(id, gridy=1) # Add the name and ID text field to the form. bag.add(self.__name, gridx=1, weightx=80.00, anchor='WEST') bag.add(self.__id, gridx=1, gridy=1, anchor='WEST') #Create an okay button, add it, and set up its event handler. okay = JButton("Okay", mnemonic=ord('O')) bag.add(okay, gridx=1, gridy=2, anchor='EAST') okay.actionPerformed=self.handleOkay self.visible=1 self.pack() def handleOkay(self, event): fname, lname = split(self.__name.text, " ") id = int(self.__id.text) employee = Employee(fname, lname, id) print employee if __name__=="__main__":EmployeeForm()

Listing 4 :Java EmployeeForm

import javax.swing.*; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import employee.Employee; public class EmployeeForm extends JFrame{ private JTextField name; private JTextField id; public EmployeeForm(){ super("Employee Form"); JPanel pane = new JPanel(); getContentPane().add(pane); pane.setLayout(new GridBagLayout()); // Create a name, and id text field. name = new JTextField(25); id = new JTextField(10); // Create and add a "Name" and "ID" label. JLabel nameLabel = new JLabel("Name"); nameLabel.setLabelFor(name); nameLabel.setDisplayedMnemonic('N'); GridBagConstraints constraint = new GridBagConstraints(); pane.add(nameLabel, constraint); JLabel idLabel = new JLabel("ID"); idLabel.setLabelFor(id); idLabel.setDisplayedMnemonic('I'); constraint.gridy=1; pane.add(idLabel, constraint); // Add the name and ID text field to the form. constraint.gridy=0; constraint.gridx=1; constraint.weightx=80.00; constraint.anchor=GridBagConstraints.WEST; pane.add(name, constraint); constraint.gridy=1; pane.add(id, constraint); // Create an okay button, add it, and set up its event handler. JButton okay = new JButton("Okay"); okay.setMnemonic('O'); constraint.gridx=1; constraint.gridy=2; constraint.anchor=GridBagConstraints.EAST; pane.add(okay, constraint); okay.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ handleOkay(); } }); this.setVisible(true); this.pack(); } public void handleOkay(){ String name, fname, lname; int index=0; int id =0; name = this.name.getText(); index = name.indexOf(" "); fname = name.substring(0, index); lname = name.substring(index+1, name.length()); id = Integer.parseInt(this.id.getText()); Employee employee = new Employee(fname, lname, id, null, 100); System.out.println(""+employee); } public static void main(String [] args){ new EmployeeForm(); } }

Listing 5: getRange

def getRange (nums): min = 300000000 max = -300000000 for item in nums: if (item > max): max = item if (item < min): min = item return (min, max, max-min)

Listing 6: getRange

def getRange (nums): return (min(nums), max(nums), max(nums)-min(nums))

Listing 7: getMean

def getMean (nums, sample): sum = 0.0 # holds the value of sum # iterate through the sequence of numbers and sum them for x in nums: sum = sum + x # Check to see if this is a sample mean if(sample): average = sum / (len(nums)-1) # Else it is a population mean else: average = sum / len(nums) return average

Listing 8: getMode

def getMode (nums): # # make a duplicate copy of the nums argument duplicate = nums[:] highest_count = -100 mode = None # # calculate the highest_count and the mode for item in nums: count = duplicate.count(item) if (count == 0): continue if (count > highest_count): highest_count = count mode = item while(duplicate.count(item) > 0): duplicate.remove(item) return mode

Listing 9: getMedian

def getMedian (nums): "Find the Median number" #create a duplicate since we are going to modify t seq = nums[:] #sort the list of numbers seq.sort() median = None # to hold the median value length = len(seq) # to hold the length of the seq # Check to see if the length is an even number if ( ( length % 2) == 0): # since it is an even number # add the two middle number together index = length / 2 median = (seq[index-1] + seq[index]) /2.0 else: # since it is an odd number # just grab the middle number index = (length / 2) median = seq[index] return median

Listing 10 getMedian

def reportStatistics (nums): # get central tendencies averages = { "mean":getMean(nums,0), "median":getMedian(nums), "mode":getMode(nums) } # get range range = getRange(nums) # put ranges in a dictionary ranges = { "min":range[0], "max":range[1], "range":range[2] } report = { "averages": averages, "ranges": ranges } return report

Listing 11: runReport.py

from stat import reportStatistics house_in_awahtukee = [100000, 120000, 150000, 200000, 65000, 100000] report = reportStatistics(house_in_awahtukee) range_format = """ Range: The least expensive house is %(min)20.2f The most expensive house is %(max)20.2f The range of house price is %(range)20.2f """ average_format = """ Averages: The mean house price is %(mean)20.2f The mode for house price is %(mode)20.2f The median house price is %(median)20.2f """ print range_format % report["ranges"] print average_format % report["averages"]

Listing 12: runReport.py Output

Range: The least expensive house is 65000.00 The most expensive house is 200000.00 The range of house price is 135000.00 Averages: The mean house price is 122500.00 The mode for house price is 100000.00 The median house price is 110000.00

Listing 13: Complete Java Version

---- Stats.java --- package stat; import java.util.ArrayList; import java.util.Iterator; import java.util.Collections; import java.util.HashMap; public class Stats { public static double getMean (ArrayList nums, boolean sample){ // Define mean that finds two types of mean, namely: // population mean and sample mean double sum=0.0; double average=0.0; Iterator iterator = nums.iterator(); while(iterator.hasNext()) sum = sum + ((Double)iterator.next()).doubleValue(); // Check to see if this is a sample mean if(sample) average = sum / nums.size()-1; else average = sum / nums.size(); return average; } public static ArrayList getRange (ArrayList nums){ // Find the range. Returns a tuple with the minimum, // maximum, and range value double min, max; ArrayList ranges; min = ((Double)Collections.min(nums)).doubleValue(); max = ((Double)Collections.max(nums)).doubleValue(); ranges = new ArrayList(); ranges.add(new Double (min)); ranges.add(new Double (max)); ranges.add(new Double (max-min)); return ranges; } public static double getMedian (ArrayList nums){ // Find the Median number // create a duplicate since we are going to modify the sequence ArrayList seq = new ArrayList(nums); // sort the list of numbers Collections.sort(seq); double median = 0.0; // to hold the median value int length = seq.size(); // to hold the length of the sequence int index=0; // Check to see if the length is an even number if ( ( length % 2) == 0){ // since it is an even number // add the two middle number together index = length / 2; double m1 = ((Double)seq.get(index-1)).doubleValue(); double m2 = ((Double)seq.get(index)).doubleValue(); median = (m1 + m2) /2.0; } else{ // since it is an odd number // just grab the middle number index = (length / 2); median = ((Double)seq.get(index)).doubleValue(); } return median; } private static int countMode(Object object, ArrayList list){ int index = 0; int count = 0; do { index = Collections.binarySearch(list, object); if(index >=0)list.remove(index); count++; } while (index >=0); return count; } public static double getMode (ArrayList nums){ // Find the number that repeats the most. // make a duplicate copy of the nums argument ArrayList duplicate = new ArrayList(nums); Collections.sort(duplicate); double highest_count = -100; double mode = -100; Iterator iterator = nums.iterator(); // iterate through nums removing each item out of the duplicate // calculate the highest_count and the mode while(iterator.hasNext()){ double count = 0; Object item = iterator.next(); // Count the number of times the item occurs in the list // If Count is 0 go to the next iteration count = countMode(item, duplicate); if (count == 0) continue; // determine the highest count. The highest counted item is the mode. if (count > highest_count){ highest_count = count; mode = ((Double)item).doubleValue(); } } return mode; } public static HashMap reportStatistics (ArrayList nums){ // get central tendencies HashMap averages = new HashMap(); averages.put("mean",new Double(getMean(nums,false))); averages.put("median",new Double(getMedian(nums))); averages.put("mode",new Double(getMode(nums))); // get range ArrayList range = getRange(nums); HashMap ranges = new HashMap(); // put ranges in a dictionary ranges.put("min", range.get(0)); ranges.put("max", range.get(1)); ranges.put("range",range.get(2)); HashMap report = new HashMap(); report = new HashMap(); report.put("averages", averages); report.put("ranges", ranges); return report; } } --- RunReport.java --- package stat; import java.util.ArrayList; import java.text.MessageFormat; import java.util.HashMap; public class RunReport{ public static String range_format = "" + "Range: \n"+ "The least expensive house is {0,number,currency}\n" + "The most expensive house is {1,number,currency} \n" + "The range of house price is {2,number,currency} \n"; public static String average_format = "" + "Averages: \n" + "The mean house price is {0,number,currency}\n" + "The mode for house price is {1,number,currency}\n" + "The median house price is {2,number,currency}\n"; public static void main(String [] args){ ArrayList houses_in_awahtukee = new ArrayList(); houses_in_awahtukee.add(new Double(110000)); houses_in_awahtukee.add(new Double(190000)); houses_in_awahtukee.add(new Double(140000)); houses_in_awahtukee.add(new Double(120000)); houses_in_awahtukee.add(new Double(190000)); houses_in_awahtukee.add(new Double(180000)); houses_in_awahtukee.add(new Double(170000)); houses_in_awahtukee.add(new Double(180000)); houses_in_awahtukee.add(new Double(180000)); houses_in_awahtukee.add(new Double(190000)); houses_in_awahtukee.add(new Double(190000)); houses_in_awahtukee.add(new Double(250000)); HashMap report = Stats.reportStatistics(houses_in_awahtukee); HashMap ranges = (HashMap)report.get("ranges"); HashMap averages = (HashMap)report.get("averages"); Object [] m_args = new Object[]{ averages.get("mean"), averages.get("mode"), averages.get("median")}; Object [] r_args = new Object []{ ranges.get("min"), ranges.get("max"), ranges.get("range")}; System.out.println(MessageFormat.format(range_format,r_args)); System.out.println(MessageFormat.format(average_format,m_args)); } }

Listing 14 for runReport2

from stat import reportStatistics from string import split file = open("data.txt") data = file.read() housePrices = split(data, ",") housePrices = map(float, housePrices) report = reportStatistics(housePrices) range_format = """ Range: The least expensive house is %(min)20.2f The most expensive house is %(max)20.2f The range of house price is %(range)20.2f """ average_format = """ Averages: The mean house price is %(mean)20.2f The mode for house price is %(mode)20.2f The median house price is %(median)20.2f """print range_format % report["ranges"] print average_format % report["averages"]

Listing 15: RunReport2

package stat; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import java.text.MessageFormat; import java.io.FileReader; import java.io.BufferedReader; public class RunReport2{ public static String range_format = "" + "Range: \n"+ "The least expensive house is {0,number,currency}\n" + "The most expensive house is {1,number,currency} \n" + "The range of house price is {2,number,currency} \n"; public static String average_format = "" + "Averages: \n" + "The mean house price is {0,number,currency}\n" + "The mode for house price is {1,number,currency}\n" + "The median house price is {2,number,currency}\n"; public static void main(String [] args){ ArrayList houses_in_awahtukee = new ArrayList(); try { BufferedReader reader = new BufferedReader(new FileReader("data.txt")); String data = reader.readLine(); StringTokenizer tokens = new StringTokenizer(data, ",\t\n\r "); while (tokens.hasMoreTokens()){ houses_in_awahtukee.add(Double.valueOf(tokens.nextToken())); } } catch(Exception e){ e.printStackTrace(); } HashMap report = Stats.reportStatistics(houses_in_awahtukee); HashMap ranges = (HashMap)report.get("ranges"); HashMap averages = (HashMap)report.get("averages"); Object [] m_args = new Object[]{ averages.get("mean"), averages.get("mode"), averages.get("median")}; Object [] r_args = new Object []{ ranges.get("min"), ranges.get("max"), ranges.get("range")}; System.out.println(MessageFormat.format(range_format,r_args)); System.out.println(MessageFormat.format(average_format,m_args)); } }

Listing 16: Embedding JPython in Java

import org.python.util.PythonInterpreter; import org.python.core.*; public class SimpleEmbedded { public static void main(String []args) throws PyException { // Create a Python interpreter. PythonInterpreter interp = new PythonInterpreter(); System.out.println("Hello, brave new world"); // Execute an import statement and a print statement. interp.exec("import sys"); interp.exec("print sys"); // Create a variable by assuaging it the value 42. // PyInterger is a Python integer. interp.set("a", new PyInteger(42)); // Execute the print statement to print out the value of a. interp.exec("print a"); // Assign x to equal the expression 2 + 2. interp.exec("x = 2+2"); // Get the value associated with x. PyObject x = interp.get("x"); // Print the value of x. System.out.println("x: "+x); } }