[FAQTS] Python Knowledge Base Update -- June 14th, 2000

Fiona Czuczman fiona at sitegnome.com
Wed Jun 14 08:08:54 EDT 2000


Hello All,

Here are the latest entries entered into http://python.faqts.com

Wishing you all a good day!

Regards, Fiona Czuczman


## Unanswered Questions ########################################


-------------------------------------------------------------
Can I combine a "select" call on some of my file objects with the Tkinter event loop?
http://www.faqts.com/knowledge-base/view.phtml/aid/3728
-------------------------------------------------------------
Rob Hooft



## New Entries #################################################


-------------------------------------------------------------
What type of sort is used for the internal sort function in Python (quick, merge, insertion, etc.)?
http://www.faqts.com/knowledge-base/view.phtml/aid/3720
-------------------------------------------------------------
Fiona Czuczman, Rob Hooft
Peter Schneider-Kamp, Tim Peters

The following assumes that we talk about lists in the standard (C) 
Python edition.

binary insertion sort is used for small lists (<100 elements) whereas
a quicksort derived sorting algorithm called "samplesort" is used for
larger lists. A description can be found in the list object 
implementation:

samplesort is basically quicksort on steroids:  a power of 2 close to 
n/ln(n) is computed, and that many elements (less 1) are picked at 
random from the array and sorted.  These 2**k - 1 elements are then used 
as preselected pivots for an equal number of quicksort partitioning 
steps, partitioning the slice into 2**k chunks each of size about ln(n). 
These small final chunks are then usually handled by binarysort.  Note 
that when k=1, this is roughly the same as an ordinary quicksort using a 
random pivot, and when k=2 this is roughly a median-of-3 quicksort.  
>From that view, using k ~= lg(n/ln(n)) makes this a "median of n/ln(n)" 
quicksort.  You can also view it as a kind of bucket sort, where 2**k-1 
bucket boundaries are picked dynamically.

The large number of samples makes a quadratic-time case almost 
impossible, and asymptotically drives the average-case number of 
compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-3 
variant) down to N lg N.

-----

The current binary_insertion/samplesort hybrid was introduced in Python
1.5.2.  In earlier releases a variety of plain quicksorts were used,
including-- in the very early days --libc's qsort.  The latter had to be
dropped because it wasn't reentrant on some platforms (== bad results 
and/or even segfaults), and ran horribly slowly on some platforms in 
some common degenerate cases.

The point to the current hybrid is that it minimizes comparisons while
(believe it or not, and it's hard to believe if you study the code!) 
doing much less data movement than a mergesort.  Comparisons are 
especially expensive in Python, because lists are heterogenous and each 
time a pair of elements gets compared the correct type-varying function 
for doing the comparison needs to be figured out and then indirectly 
invoked.  So minimizing compares is crucial for a Python sort.  I wasn't 
able to write a mergesort (which also does few compares) as fast as the 
hybrid, because mergesort shuffles data around a lot more -- there are 
few enough compares now that data movement expense is no longer lost in 
the shuffle <ahem>.  The current hybrid is also an in-place sort.  Its 
only drawbacks are the complexity of the algorithm and that the 
resulting sort isn't stable.

-----

The "sort" function in the Numeric python code still uses the libc's
qsort() function at this moment.


-------------------------------------------------------------
Is there a general way to remove axes of length 1? eg. I have an array of shape (1,3,1,4) I want to change it to (3,4)?
http://www.faqts.com/knowledge-base/view.phtml/aid/3723
-------------------------------------------------------------
Fiona Czuczman
Konrad Hinsen

For a specific known shape, just assign a new one:

 array.shape = (3, 4)

For suppressing all axes of length one, no matter where, you can write

 array.shape = Numeric.repeat(array.shape, 
Numeric.not_equal(array.shape, 1))

Note that this changes the array, it does not create a new one.


## Edited Entries ##############################################


-------------------------------------------------------------
How do I check to see if a file exists?
http://www.faqts.com/knowledge-base/view.phtml/aid/2782
-------------------------------------------------------------
Fiona Czuczman
Fredrik Lundh,Peter Schneider-Kamp

To check if a file exists use:

>>> import os.path
>>> os.path.exists("python/")
1
>>> os.path.exists("spam/")
0
>>> os.path.exists("python/patches/submitted/array.pop-extend.patch")
1

If you only want a true for regular files have a look at isfile():

>>> os.path.isfile("python/")
0
>>> os.path.isfile("spam/")
0
>>> os.path.isfile("python/patches/submitted/array.pop-extend.patch")

for more info or other function look at:
http://python.org/doc/current/lib/module-os.path.html


-------------------------------------------------------------
Where can I get good Tutorials about JPython?
Where can I get good Tutorials about JPython?
http://www.faqts.com/knowledge-base/view.phtml/aid/3668
-------------------------------------------------------------
Fiona Czuczman
Moshe Zadka,bo Vandenberg

JPython is another implementation of the Python language: everything you
learn in the Python tutorial (http://www.python.org/doc/tut/tut.html),
will be true for JPython. You can review the CPython/JPython differences
somewhere in the JPython site (http://www.jpython.org).

Some links to start with are:

The first stop for Python (IMHO)
http://www.pythonlabs.com/

JPython
http://sourceforge.net/project/?group_id=5473

General Python Portal -- with easy links to important pages
phttp://www.oreillynet.com/pub/a/python/2000/04/14/python-intro.html


SOURCE MODULES ETC...
http://www.vex.net/parnassus/apyllo.py?a=l
http://tor.dhs.org/~zephyrfalcon/snippets/index.html


-------------------------------------------------------------
Is there a progress bar given by Tkinter?
http://www.faqts.com/knowledge-base/view.phtml/aid/2718
-------------------------------------------------------------
Fiona Czuczman, Rob Hooft
Robert Hicks, John Grayson

This comes from John Grayson's book "Python and Tkinter
programming".

"""
A  basic widget for showing the progress
being made in a task.

"""

from Tkinter import *

class ProgressBar:
    def __init__(self, master=None, orientation="horizontal",
                 min=0, max=100, width=100, height=18,
                 doLabel=1, appearance="sunken",
                 fillColor="blue", background="gray",
                 labelColor="yellow", labelFont="Verdana",
                 labelText="", labelFormat="%d%%",
                 value=50, bd=2):
        # preserve various values
        self.master=master
        self.orientation=orientation
        self.min=min
        self.max=max
        self.width=width
        self.height=height
        self.doLabel=doLabel
        self.fillColor=fillColor
        self.labelFont= labelFont
        self.labelColor=labelColor
        self.background=background
        self.labelText=labelText
        self.labelFormat=labelFormat
        self.value=value
        self.frame=Frame(master, relief=appearance, bd=bd)
        self.canvas=Canvas(self.frame, height=height, width=width, bd=0,
                           highlightthickness=0, background=background)
        self.scale=self.canvas.create_rectangle(0, 0, width, height,
                                                fill=fillColor)
        self.label=self.canvas.create_text(self.canvas.winfo_reqwidth()
/ 2,
                                           height / 2, text=labelText,
                                           anchor="c", fill=labelColor,
                                           font=self.labelFont)
        self.update()
        self.canvas.pack(side='top', fill='x', expand='no')

    def updateProgress(self, newValue, newMax=None):
        if newMax:
            self.max = newMax
        self.value = newValue
        self.update()

    def update(self):
        # Trim the values to be between min and max
        value=self.value
        if value > self.max:
            value = self.max
        if value < self.min:
            value = self.min
        # Adjust the rectangle
        if self.orientation == "horizontal":
            self.canvas.coords(self.scale, 0, 0,
              float(value) / self.max * self.width, self.height)
        else:
            self.canvas.coords(self.scale, 0,
                               self.height - (float(value) / 
                                              self.max*self.height),
                               self.width, self.height)
        # Now update the colors
        self.canvas.itemconfig(self.scale, fill=self.fillColor)
        self.canvas.itemconfig(self.label, fill=self.labelColor)
        # And update the label
        if self.doLabel:
            if value:
                if value >= 0:
                    pvalue = int((float(value) / float(self.max)) * 
                                   100.0)
                else:
                    pvalue = 0
                self.canvas.itemconfig(self.label, text=self.labelFormat
                                         % pvalue)
            else:
                self.canvas.itemconfig(self.label, text='')
        else:
            self.canvas.itemconfig(self.label, text=self.labelFormat %
                                   self.labelText)
        self.canvas.update_idletasks()







More information about the Python-list mailing list