Re: [Tutor] Sort a list following the order of other list

2005-08-22 Thread jfouhy
Quoting Jonas Melian [EMAIL PROTECTED]:

 best = [ [1024, 768], [800, 600], [640, 480] ] (it's larger)
 
 modes = [
 (24, [1280, 1024]),
 (24, [1024, 768]),
 (24, [640, 480]),
 (16, [1600, 1200]),
 (16, [1280, 1024]),
 (15, [320, 200]),
 ]
 
 I want to create a list with ALL elements of 'modes', but following the
 order of list 'best' (if exist the number). At the end the rest of 
 numbers in modes, are added too. And all this for each modes[0] (24, 16,
 15, ...)

I well understand the desire to do everything in a single beautiful list
comprehension, but sometimes we have to go back to old-style programming and
actually write a function :-)

in 2.3, sort() takes an optional comparison function as a parameter. cmp(x,y)
should return 0 if xy, 0 if x==y, and 0 if xy.

 best = [ [1024, 768], [800, 600], [640, 480] ]
 modes = [ (24, [1280, 1024]), (24, [1024, 768]), (24, [640, 480]), (16,
[1600, 1200]), (16, [1280, 1024]), (15, [320, 200]) ]
 def modeCompare(m1, m2):
...  r1 = m1[1]; r2 = m2[1]
...  if r1 in best:
...   if r2 in best:
...return cmp(best.index(r1), best.index(r2))
...   else:
...return -1
...  else:
...   if r2 in best:
...return 1
...   else:
...return 0
...
 sorted(modes, cmp=modeCompare)
[(24, [1024, 768]), (24, [640, 480]), (24, [1280, 1024]), (16, [1600, 1200]),
(16, [1280, 1024]), (15, [320, 200])]

...mind you, having said that, here is a list comprehension solution anyway:

 [(b, r) for r in best for b, r2 in modes if r == r2] + [m for m in modes if
m[1] not in best]
[(24, [1024, 768]), (24, [640, 480]), (24, [1280, 1024]), (16, [1600, 1200]),
(16, [1280, 1024]), (15, [320, 200])]

HTH!

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sort a list following the order of other list

2005-08-22 Thread jfouhy
Quoting Jonas Melian [EMAIL PROTECTED]:

 Thank you very much!.
 
 I didn't want to make it using the old-style programming because it's 
 more large and I'm supposed that slower that using a list comprehension
 solution.

Well, we can investigate, to find out the truth :-)

Hopefully you can read the attached file.  Here are my results:
$ python sorttest.py
John 1:[5.324422796752101, 6.9189729420918029, 6.771758421810592]
John 2:[3.4790142322557749, 3.4373198269612502, 3.392254322825945]
Kent:[29.745739472474856, 42.376246143015386, 38.031272689685423]

(each time represents 100,000 reps)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is it possible to...

2005-08-15 Thread jfouhy
Quoting Nathan Pinno [EMAIL PROTECTED]:

 Is it possible to create a def that not only deals cards, but also
 assigns a value to each rank, except that the Jacks, Queens, and Kings
 all are the same value as the 10s?
 If this is possible, how should I go about doing this?

Nearly everything is possible; you just have to order your thoughts correctly 
:-)

In this case, you're looking for a way of mapping from cards to values.  Python
has  a mapping type built in, called a dictionary.  You can read about it here:
http://docs.python.org/tut/node7.html#SECTION00750 and here:
http://docs.python.org/lib/typesmapping.html

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting a list of lists aka nested lists

2005-08-14 Thread jfouhy
Quoting Alan G [EMAIL PROTECTED]:

  Quant.append( [ db_ticker, stock_close, MTD, 0, QTD, 0, YTD, 0, 
  0, 0 ] )
  After Quant is created, I want to sort it by MTD. If I use a simple 
  Quant.sort(), I assume its going to sort by 'db_ticker' which is not 
  what I want.
 you need to write your own comparison function.
 Basically it will take two of your lists and return -1,0 or 1.
 
 Or you can use Python's own logic to help
 
 def cmplists(lst1,lst2):
  return cmp(lst1[2],lst2[2])
 
 Now you can sort Quant by passing your function into sort...

Note that in Python2.4+, you can use key= instead:

def sortKey(lst):
 return lst[2]
Quant.sort(key=sortKey)

This is more effient than specifying a different comparison function, because
the key function is only called once for each element.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pls. help me in sorting and choosing

2005-08-10 Thread jfouhy
Quoting Srinivas Iyyer [EMAIL PROTECTED]:

 My question is how can I code to distinguish all high
 scoring group and all low scoring group. 

One thing you need to decide is what it means to be high scoring.  Is an element
high scoring if its score is above some threshhold, or it a percentage?  Or
something else?

(eg: an element is high scoring if its score is  1000 or an element is high
scoring if it is in the top 20% when ranked by score)

Do you know how to read your data in from your file?  If you have a file looking
like this:

NM_004619.2 4910.8
NM_004619.2 2716.3
NM_145759.1 4805.7
NM_14 5759.12716.3
XM_378692.1 56.00

then I would convert that into a list of tuples:

[(NM_004619.2, 4910.8), (NM_004619.2, 2716.3), (NM_145759.1, 4805.7),
(NM_14 5759.1, 2716.3), (XM_378692.1, 56.00)]

If you can do this, then it is easy to ask python to sort it for you.

 data = [(NM_004619.2, 4910.8), (NM_004619.2, 2716.3), (NM_145759.1,
4805.7), (NM_14 5759.1, 2716.3), (XM_378692.1, 56.00)]
 data.sort(key=lambda x: x[1], reverse=True)
 data
[('NM_004619.2', 4910.80002), ('NM_145759.1', 4805.69998),
('NM_004619.2', 2716.30002), ('NM_14 5759.1', 2716.30002),
('XM_378692.1', 56.0)]

Now, the first elements in the list have the highest score, and you can decide
how far down to go.

Alternatively, you could ask for all elements above a certain score:

 [x for x in data if x[1]  3000]
[('NM_004619.2', 4910.80002), ('NM_145759.1', 4805.69998)]

HTH!

(note: key= and reverse= arguments to sort() are a new feature in Python2.4.  If
you are using an earlier Python, you will have to do things slightly
differently.  Probably the easiest change to make would be to have the score be
the first element in the tuples)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pls. help me in sorting and choosing

2005-08-10 Thread jfouhy
Quoting Srinivas Iyyer [EMAIL PROTECTED]:

 2. I know how to read a tab delim txt file as list but
 not into the tupeles. Apologies for my inexperience. 

How are you currently reading the file? --- can you show us some code?

You can create tuples directly.  For example:

 x = 3
 y = 7
 t = (x, y)
 t
(3, 7)

or:

 squares = []
 for i in range(10):
...  squares.append((i, i**2))   # Note the double parentheses!
...
 squares
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64),
(9, 81)]

You can read more about tuples in the python tutorial; section 5.3.
(see http://www.python.org/)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help

2005-08-09 Thread jfouhy
Quoting Dan Deternova [EMAIL PROTECTED]:

 ok. i know python and want to turn all my programs i made when i was 
 learning python into Tkinter programs. i dont know how to make if
 satments and display the output like this in python: 
 if cmd == quit:
  print press exit to quit
  i have no idea how to do that in Tkinter please help.

Have a look at Thinking in Tkinter: http://www.ferg.org/thinking_in_tkinter/

If you work through it, it should hopefully give you a better idea of how
Tkinter programs work.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How do I fix this ValueError?

2005-08-09 Thread jfouhy
Quoting Nathan Pinno [EMAIL PROTECTED]:

 Here is the error:
 
 Traceback (most recent call last):
  File D:\Python24\password.py, line 91, in -toplevel-
  save_file(sitelist)
  File D:\Python24\password.py, line 22, in save_file
  for site,ID,passcard in sitelist.items():
 ValueError: need more than 2 values to unpack
 
 Here is the code:
 
 sitelist = {}

sitelist is a dictionary.  Let's see what the .items() method on dictionaries 
does:

 d = { 1:'foo', 2:'bar', 3:'baz' }
 d.items()
[(1, 'foo'), (2, 'bar'), (3, 'baz')]

So, if we iterate over d.items(), we are iterating over a list of tuples, each
two elements long.

 for item in d.items():
...  print item
...
(1, 'foo')
(2, 'bar')
(3, 'baz') 

Now, we can unpack tuples.  For example:

 t = (1, 2)
 x, y = t
 x
1
 y
2

This only works if both sides of the = have the same number of things.

 t = (1, 2, 3)
 x, y = t# Not enough variables on the left hand side.
Traceback (most recent call last):
  File stdin, line 1, in ?
ValueError: too many values to unpack
 x, y, z, w = t  # Too many variables on the left hand side.
Traceback (most recent call last):
  File stdin, line 1, in ?
ValueError: need more than 3 values to unpack

Now can you figure out what the ValueError you were getting means?

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to I make it save the data properly? (was Re: How do I fix this ValueError?)

2005-08-09 Thread jfouhy
Quoting Nathan Pinno [EMAIL PROTECTED]:

 I tried fixing it. Here is the new code:

There are two likely places where you could have a problem: In your save
function, or in your load function.  Have you tried looking at the file where it
saved the information?  If the file doesn't contain the data it should, then
your save function probably has an error.  Otherwise, your load function
probably has an error.

Once you've got an idea of where the problem is, you can try to isolate it, so
that you can fix the problem without having to plow through the rest of your
code all the time.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] use of webbrowser.open_new()

2005-08-07 Thread jfouhy
Quoting Tom Cloyd [EMAIL PROTECTED]:

Compare the filename here:

 webbrowser.open_new(C:\__Library\folders\05238 Design for Confusion\05238 
 Design for Confusion -05krugman.html)

With here:

 WindowsError: [Errno 2] The system cannot find the file specified: 
 'C:\\__Library\x0colders*38 Design for Confusion*38 Design for Confusion
 -05krugman.html'

Do you notice any differences?

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] terminology question

2005-08-01 Thread jfouhy
Quoting Dick Moores [EMAIL PROTECTED]:

 Why are list comprehensions called that?

Because that's what they're called in Haskell, I guess..

It's historical, based on the term set comprehension from mathematics, also
known as set builder notation: http://en.wikipedia.org/wiki/Set_comprehension

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How do I make Python draw?

2005-07-28 Thread jfouhy
Quoting Alan G [EMAIL PROTECTED]:

 I found my message to Nathan, looks like I pressed the wrong
 reply button in the Outlook Express newsreader. I thought I'd
 forward it to the list since:
 a) we don't often discuss the turtle module and

Wow, I never knew this existed...

  (The righward horizontal line seems to be a buglet in the module
  - does anyone know how to get rid of it?)

I don't get that --- when I run that code, I just get a triangle only...

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Select rows and columns in excel

2005-07-27 Thread jfouhy
Quoting David Holland [EMAIL PROTECTED]:

 Dear Tutors,
  
 I know how to open files in python, however what I want to do is select
 some information from an excel spreadsheet and save it as a .dat file. 
 The bit, I am stuck on is :- 
 How can I select all rows with a row number greater than x for a certain
 column ?

If you don't want to go with COM, there are a couple of packages that might be
useful: xlrd and pyExcelerator.

I've used pyExcelerator; it includes functions to parse a spreadsheet into a
dictionary.  You could do something like this (untested):

import pyExcelerator
workBook = pyExcelerator.parse_xls('myfile.xls')
sheet = workBook['Sheet1']   # Or whatever the worksheet is called

print sheet.items()[:5]
# prints something like: ((3, 2), 'foo'), ((1, 0), 'bar'), etc

rowsAbove3 = dict([(x, sheet[x]) for x in sheet if x[0]  3])

# etc

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT: we won't eat VB programmers for lunch [Was: How do I make Python draw?]

2005-07-27 Thread jfouhy
On Wed, 27 Jul 2005, luke wrote:
 
 VB is not a good language to learn because it is the complete opposite
 of every other programming language.

If you think that's true, google some time for esoteric programming languages 
:-)

Some examples:

http://www.muppetlabs.com/~breadbox/bf/ --- an 8 instruction programming
language designed with the goal of making the smallest compiler possible. (the
AmigaOS compiler was 240 bytes long)

http://www.madore.org/~david/programs/unlambda/ --- unLambda: _everything_ is a
function. (Your Functional Programming Language Nightmares Come True)

http://en.wikipedia.org/wiki/Malbolge_programming_language --- Malbolge:
Designed to be the most horrible programming language conceivable.  Malbolge
was so difficult to understand when it arrived that it took two years for the
first Malbolge program to appear.

http://shakespearelang.sourceforge.net/ --- Programs are in the form of
Shakespearean plays.

http://compsoc.dur.ac.uk/whitespace/ --- Whitespace: The only legal syntax
characters are spaces, tabs and newlines.  All other characters are considered
comments.

There's also one I've seen where your program was an ASCII-art line, and the
instructions were given by the angle when your line turned a corner.  180deg was
a no-op, so you could make your program as big as you wanted.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pager in Python?

2005-07-25 Thread jfouhy
   Is there a command like more(1) or less(1) in python to display
   the output of a command (e.g. dir()) one page at a time?

You could always write your own ...

eg:

def page(it, numLines=20):
   if isinstance(it, dict):
  it = it.iteritems()
   for i, x in enumerate(it):
  print x
  if (i+1) % numLines == 0:
 raw_input('Press enter to continue...')

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Efficient word count

2005-07-21 Thread jfouhy
Quoting Jorge Louis De Castro [EMAIL PROTECTED]:

 I was wondering, and maybe this is because I come from a different
 programming language background, but is a word count using len(list)
 after a string.split, efficient if there are many words? Or should I
 write my own word count for large(ish) blocks of text (500-1000)?

Well, here's a few attempts at finding other ways of doing that:

E:\Python24\Libpython timeit.py -s foo = 'word wrd wordwordword '*1000
len(foo.split())
1000 loops, best of 3: 1.44 msec per loop

E:\Python24\Libpython timeit.py -s foo = 'word wrd wordwordword '*1000
len([c for c in foo if c.isspace()])
100 loops, best of 3: 9.18 msec per loop

E:\Python24\Libpython timeit.py -s foo = 'word wrd wordwordword '*1000
len([c for c in foo if c == ' '])
100 loops, best of 3: 4.33 msec per loop

At a guess, you might be able to do it faster if you wrote a word counter in C,
because you could avoid building the list.  But len(s.split()) is probably the
quickest otherwise.

See also http://www.python.org/doc/essays/list2str.html :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter event for changing OptionMenu items

2005-07-21 Thread jfouhy
Quoting Bernard Lebel [EMAIL PROTECTED]:

 I'm trying to bind an event to the changes made to an OptionMenu. Ie
 the user chooses a different item, the rest of the Tk window gets
 updated. To repopulate the window, a function would be called by the
 binding.
 
 Any suggestion?

The easiest way is to use a Pmw.OptionMenu, which has this functionality
built-in :-)

Alternatively, you can trace the StringVar you connect to the OptionMenu.  I
have never done anything with traces, but there are some instructions here:
http://www.astro.washington.edu/owen/ROTKFolklore.html

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically populate Tkinter OptionMenu with list

2005-07-20 Thread jfouhy
Quoting Bernard Lebel [EMAIL PROTECTED]:

 I have this problem. I build a list of elements, and I never know in
 advance how many or what will be the elements.
 
 I then wish to populate an OptionMenu with this list of elements.

Do you know the list of elements before you create the option menu?

If so, you can do something like this:

# suppose aElements is the list of elements, and var1 is a StringVar.
oOption = OptionMenu(oRoot, var1, aElements[0], *aElements[1:])

If you want to create the OptionMenu first, and then later set the list of
elements ... then it is a bit more difficult.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with ebay profit/loss program error

2005-07-19 Thread jfouhy
Quoting Sam Klinger [EMAIL PROTECTED]:

 Hi my name is Sam Klinger and I made a smal program to help find out
 the cost of listing and selling an item on ebay. However I see nothing
 wrong with the code but I get these error messages:

Hi Sam,

The problem is here:

 def listing_price():
  price=input('What is the starting price?')

This gets input from the user and stores it in a _local_ variable 'price'.  When
the function terminates, the variable goes out of existence.

This means that, later on:

 #Computes the price of insertion
 def compute_insertion_fee():
  if price = .99:
  price= price+.25

'price' does not exist, so you get the error you are seeing.

I recommend making use of the fact that functions can take parameters and can
return values.  For example:

def listing_price():
 price = float(raw_input('What is the starting price?'))
 return price

def compute_insertion_fee(price):
 if price = 0.99:
# etc

#Gets a menu choice from user
menu_choice = 0
print_menu()
while menu_choice !=7:
 menu_choice = int(raw_input(type in a number (1-7): ))
 if menu_choice == 1:
  price = listing_price()
  compute_insertion_fee(price)
# etc

Incidentally: It is better to use raw_input, rather than input, for reasons that
have been discussed several times on this list recently :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter: justify label

2005-07-19 Thread jfouhy
Quoting Bernard Lebel [EMAIL PROTECTED]:

 Can you specify a justification for a label widget? I'm reading there
 is a justify option available on this page:
 http://www.pythonware.com/library/tkinter/introduction/x611-text-formatting.htm
 Although I don't know if this option works for label.

It does; it just doesn't do what you think it does :-)

justify is for multi-line labels.  If you are looking to position the text
within the label, you need to use anchor.

eg:

 from Tkinter import *
 tk = Tk()
 l1 = Label(tk, text='this is left\njustified', justify=LEFT)
 l1.pack()
 l2 = Label(tk, text='this, otoh, is right\njustified', justify=RIGHT)
 l2.pack()
 l3 = Label(tk, text='left aligned', anchor=W)
 l3.pack(fill=X)
 l4 = Label(tk, text='right aligned', anchor=E)
 l4.pack(fill=X)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Minesweeper the return

2005-07-19 Thread jfouhy
Quoting Alberto Troiano [EMAIL PROTECTED]:

 Please let's talk about this more! *grin*
 I'm not sure if I'm following you, what I see here is a function inside
 other function and the first function returns its inside function, but
 how does it work?

In Python, as in other modern languages, functions are first-class objects. 
In particular, you can pass functions as arguments to other functions, or return
functions from other functions.

I like examples:

 def add(x, y):
...  return x + y
...
 f = add  # Notice the lack of brackets after 'add'
 f(3, 5)
8
 f(9, 12)
21

In this case, all I've done is assigned to f the function 'add'.  This means
that f is now a function, and I can call it, even though I never did 'def f(x,
y)' anywhere.

 def square(x):
...  return x*x
...
 range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 map(square, range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The 'map' builtin function takes two arguments: a function and a list.  It makes
a new list by applying the function to each element of the old list.
ie: This is an example of passing a functino as an argument.

Finally:

 def makeAdder(x):
...  def add(y):
...   return x + y
...  return add
...
 f = makeAdder(5)
 f(3)
8
 f(8)
13

'def add(y)' defines a function of one argument, which adds that argument to x,
and returns the result.  What is x? Well, x is a variable in the scope of
makeAdder(); it gets bound to the argument you pass.  In my example, x was bound
to 5.  So, effectively, we have created a new function by: 'def add(y): return 5
+ y', and then returned that function to f.  We can now call f and see the 
result.

HTH!

-- 
John.

[ps: sorry for the troll.. I couldn't resist :-) ]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Scrolling multilistbox help

2005-07-18 Thread jfouhy
Quoting Alberto Troiano [EMAIL PROTECTED]:

 I'm using the Multilistbox class and I noticed that it only handles the
 mouse scroll and the scrollbar to go down or up.I succesfully
 implemented the sort function that came with the class
 I also added code to handle the up and down arrow keys and it goes down
 all right but only select the item and it doesn't scroll down or up
 How can make it go up or down?

I haven't actually tried your code, but this might be the problem here:

  def _select1(self):
  if self.fila==self.size()-1:
  pass
  else:
  self.selection_clear(0, END)
self.selection_set(self.fila+1)
  self.fila+=1
  self._scroll()
   return 'break'

  def _scroll(self, *args):
   for l in self.lists:
apply(l.yview, args)

You call self._scroll with no arguments to make the selected index visible (I
guess).  But self._scroll just calls yview on each list..and yview with no
arguments returns a tuple, but otherwise does nothing.

Try replacing self._scroll with self.see --- possibly: self.see(self.fila).

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Performance difference, ``in'' vs ``has_key()''

2005-07-17 Thread jfouhy
Quoting Bill Campbell [EMAIL PROTECTED]:

 I'm going to be doing some work where I'll be doing existence
 testings on keys on about a million records where it may require
 multiple passes so I'm a bit concerned about the timing of these
 tests.

If you're just doing existence testing, is it an option to use a set? (builtin
to Python 2.4)

I admit, I don't know how it performs.  But it would seem the most appropriate
of the builtin data structures.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tk -- which label clicked

2005-07-15 Thread jfouhy
Quoting Michael Lange [EMAIL PROTECTED]:

 I don't think it will work this way, because you don't catch the event
 bind() passes to the callback
 (you also use a variable e in makeCallback() that isn't defined
 anywhere).

That's what the variable 'e' is doing!

Here is some code I just wrote and tested:

 def clicked(w):
...  print 'Widget %s clicked! Text: %s' % (str(w), w.cget('text'))
...
 def makeCallback(w):
...  def callback(e):
...   clicked(w)
...  return callback
...
 from Tkinter import *
 tk = Tk()
 for text in ['foo', 'bar', 'baz']:
...  lb = Label(tk, text=text)
...  lb.pack()
...  lb.bind('Button-1', makeCallback(lb))
...
'11427352callback'
'12096856callback'
'12097016callback'
 # Now to click on the labels.
Widget .11444992 clicked! Text: foo
Widget .12097096 clicked! Text: bar
Widget .12097336 clicked! Text: baz
Widget .12097096 clicked! Text: bar
Widget .11444992 clicked! Text: foo

-

Lambdas are (probably) going away in Py3000, so I am trying to get away from
using them (it's hard, though :-) ).  Anyway, makeCallback() defines a function
which takes one argument (that's the event), and then calls clicked() on the
widget argument to makeCallback().  That function is returned and bound to
Button-1.

Here's a simpler example of the same thing:

 def add(x):
...  def addx(y):
...   return x + y
...  return addx
...
 f = add(5)
 f(3), f(5), f(9)
(8, 10, 14)

(of course, I could have done the same thing by writing: f = (5).__add__ ...)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] populating a listbox from a list

2005-07-15 Thread jfouhy
Quoting Max Russell [EMAIL PROTECTED]:

 I have a list in this format:
 
 puckman puckmana puckmanf puckmanh pacman 
 pacmanf puckmod pacmod 
 newpuc2 newpuc2b newpuckx pacheart hangly 

Hi,

You can use .split() to turn a string like that into a list of the individual
elements.
(when called with no arguments, .split() splits on all whitespace)

 s = foo bar baz
... zif zaf zof
... yip yap
 s
'foo bar baz\nzif zaf zof\nyip yap'
 s.split()
['foo', 'bar', 'baz', 'zif', 'zaf', 'zof', 'yip', 'yap']

 I'm really not sure how to populate the list though- I
 can work with lists just as text, but what do I need
 to do to read a list into a listbox.

To insert into a listbox, you use self.lstbx.insert(position, *entries)

For example:

for elem in s.split():
 self.lstbx.insert(END, elem)

You can also do this:

self.lstbx.insert(END, *s.split())

(if x is a list and foo() a function, then foo(*x) is equivalent to foo(x[0],
x[1], x[2], ..., x[len(x)-1]))

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Virtual keyboard

2005-07-14 Thread jfouhy
Quoting Mark Kels [EMAIL PROTECTED]:

 I do want it to type in any entry (websites, notepad and other
 programs), and thats what makes it harder. I dont think that shouldnt
 be too hard as well, but I have no idea how to do it.

You would need some way of getting a handle for the widget you want to type
into.. I don't know how to do this (or even if you can), but I wonder if you
might have more luck if you used PythonWin and the Microsoft factory classes to
build your GUI?

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regular expressions

2005-07-14 Thread jfouhy
Quoting Servando Garcia [EMAIL PROTECTED]:

 Hello List
   I am working on creating a Domain Specific Language that will solve 
 partial differential equations. The user will enter a equation in 
 pseudo code format. I will need to parse the equation. Here is the BNF 
 for the equation
...

There are a few parser generators out there in Python.  One, which I have used
successfully before, is SimpleParse (google for it).  These will allow you to
build a parser directly from the grammar with little effort :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter query?

2005-07-14 Thread jfouhy
Quoting Ron Weidner [EMAIL PROTECTED]:

   tk = Tk()
   tk.config(background='pink')
   tk.geometry('400x400')
  
 
 tk.geometry( 320x150+200+200)

Hmm.  In my experience, a call like tk.geometry('400x400') will resize tk
without moving it...

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tk -- which label clicked

2005-07-14 Thread jfouhy
Quoting Ron Weidner [EMAIL PROTECTED]:

 Or, more to the point... I need to dynamicaly create
 clickable labels, each using the same callback. When
 clicked, I need to know which one was clicked. I was
 hoping to use the text of the label as the argument
 to another function.

You've got one suggestion ... But, FWIW, here is how I would probably do it:

def clicked(w):
print 'Widget %s clicked! Text:' % (str(w), w.cget('text'))

def makeCallback(w):
def callback(e):
clicked(w)
return callback

# create labels
for text in ['foo', 'bar', 'baz']:
lb = Label(master, text=text)
lb.bind('Button-1', makeCallback(lb))

--

(this involves a separate callback function for each label, so it could possibly
be slower)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter query?

2005-07-14 Thread jfouhy
Quoting Dave S [EMAIL PROTECTED]:

 Thank you, that has clarified a few points but raised a query.
 tk.geometry('400x400') does not appear to have any effect on its size
 when the window is drawn, the window is always the same size and short
 of maximizing it to full screen it is not adjustable.
 
 Just a minor query but interesting

Hmm, that is strange.  You can use tk.resizable(width, height) to set whether
the window can be resized.  But, when I do this (Debian linux, WindowMaker), I
can't maximise the window either.  Also, it should default to being resizable in
both directions.

What platform are you running on?

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] HTML links from Tkinter

2005-07-14 Thread jfouhy
Quoting Alberto Troiano [EMAIL PROTECTED]:

 Is there any way that I can link a button to go to certain web page?
 and how can I do that?

If you want to open a web page in the user's default browser, check out the
webbrowser module in the standard library.

If you want to go to a website and suck down some data, you'll probably need
urllib (and it will be a bit more work).

 Another thing, I'll make a query by name and I want to show every
 results matching the query in a table using Tkinter.

There's no table widget in standard Tkinter.  Search in the Python Cookbook (on
ActiveState) for a MultiListbox; it might do what you need.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter Q's

2005-07-13 Thread jfouhy
Quoting Joseph Quigley [EMAIL PROTECTED]:

 Hi, 
   what's the **kw stand for, used for? What does it mean?

Sorry about that.  A couple of people have already answered; I'll just give you
a couple of examples which might help you understand:

 def showArgs(**kw):
...  print kw
...
 showArgs(foo=1, bar=2, string='My string')
{'foo': 1, 'bar': 2, 'string': 'My string'}

Basically, **kw means Take any keyword arguments that were unused, and put them
in a dictionary called 'kw'.

Here's another example:

 def myFunction(x=1, y=2, **kw):
...  print x == %s, y == %s % (x, y)
...  print Unused arguments:, kw
...
 myFunction(a='foo', b='bar', y=8, c='baz', x=13)
x == 13, y == 8
Unused arguments: {'a': 'foo', 'c': 'baz', 'b': 'bar'}

Some of the keyword arguments are given explicit names, to make them easy to
access.  The remainder are available still in kw.

You can also do the reverse:

 def doSomeMaths(x=3, y=2, z=8):
...  return (x+y)*z
...
 kwargs = { 'x':4, 'y':3, 'z':2 }
 doSomeMaths(**kwargs)
14

In this case, the dictionary 'args' is expanded into three keyword parameters:
x=4, y=3, z=2

You can also do the same thing with positional parameters; in this case you just
use one *.

Does that help?

 Uh, not really, no. I'm very new to GUI. So you're saying that If I make
 the class actually do something (I edited and example in:
 An into to Tkinter, Fredrik Lundh).

Tkinter programming involves making Frames, Buttons, Labels, etc. and putting
them all together.  What I like to do is subclass Frame (or other things) to
make new GUI components, which I can then pack() into Frames as normal.

Here's a really basic example:

from Tkinter import *

class BlueLabel(Label):
  A Label with a blue background. 

 def __init__(self, *args, **kw):
kw['background'] = 'blue'
Label.__init__(self, *args, **kw)

if __name__ == '__main__':
tk = Tk()
l1 = Label(tk, text='This is a normal label.')
l1.pack()
l2 = BlueLabel(tk, text='This is a blue label.')
l2.pack()
tk.mainloop()

(and, this time, I have tested this code :-) Although you may need to fix up the
indentation a bit)

  currQuote = showquote.cget('config') # Get the current quote

As Michael pointed out, this was a bug.  Sorry.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter query?

2005-07-13 Thread jfouhy
Quoting Dave S [EMAIL PROTECTED]:

 But I do not understand where Frame fits in to this ... ie
 
 from Tkinter import *
 class Hello(Frame):
  
  def __init__(self, parent=None):
  Frame.__init__(self, parent)
  self.pack()
 
 
 Why not just use 'class Hello(root)' ? Or have I missed the point :-[
 
 OK am I right in thinging a 'Frame' always has a parent of a Tk() or
 possibly Toplevel() and its used to help in positioning a widget window
 with .pack() ?
 
 Dave

There's two separate issues here ...

class Hello(Frame):
 ...

This means that Hello is a subclass of the Frame class.  If you haven't already,
you might want to read the Python tutorial; particularly the section on classes
and inheritance: http://docs.python.org/tut/node11.html
(this is an example of inheritance)

Your second question:

 OK am I right in thinging a 'Frame' always has a parent of a Tk() or
 possibly Toplevel() and its used to help in positioning a widget window
 with .pack() ?

Frames are used to help with positioning other widgets, yes.  They are also used
to affect how the application looks: you can change the background colour of
Frames, and also the border (to make them look like they are sticking out, for
example).  But you can (and frequently will) put Frames inside other Frames.

Example:

from Tkinter import *

tk = Tk()
tk.config(background='pink')
tk.geometry('400x400')

frame1 = Frame(tk, background='blue')
frame1.pack(side=LEFT, padx=15, pady=15, expand=True, fill=BOTH)

frame2 = Frame(tk, background='green', borderwidth=3, relief=RAISED)
frame2.pack(side=LEFT, padx=15, pady=15, expand=True, fill=BOTH)

frame3 = Frame(frame1, background='red', borderwidth=3, relief=SUNKEN)
frame3.pack(side=TOP, padx=15, pady=15, expand=True, fill=BOTH)

frame4 = Frame(frame1, background='white', borderwidth=3, relief=GROOVE)
frame4.pack(side=TOP, padx=15, pady=15, expand=True, fill=BOTH)

label1 = Label(frame4, text='Hello world!')
label1.pack(expand=True)

tk.mainloop()

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tk entry focus

2005-07-13 Thread jfouhy
Quoting Ron Weidner [EMAIL PROTECTED]:

 What's wrong with this code? Or more to the point,
 how do you set the focus to an Entry widget?

Look at what the error message is saying:
 
  self.cmd.focus()
 AttributeError: 'NoneType' object has no attribute
 'focus'

Translation: self.cmd is a 'NoneType' object.  There is only one NoneType
object: None.  So, somehow, you have (effectively) done:
 self.cmd = None

Let's see ...

   self.cmd = Entry( self.frame,
 textvariable=self.cmd_text ).grid( row = 1, column = 2 )

Aha.  Here, you are creating an Entry widget, calling the grid() method on the
entry widget, and then assigning to self.cmd the return value _of the grid()
call_.  This is extremely different from assigning to self.cmd the Entry widget
just created.
(can you guess what .grid() returns?)

You need to break your code up into two lines:
 self.cmd = Entry(...)
 self.cmd.grid(...)

Then give it a try :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter Q's

2005-07-12 Thread jfouhy
Quoting Joseph Quigley [EMAIL PROTECTED]:

 Hi first off, here's my code:
 
 # -*- coding: utf-8 -*-
 from Tkinter import *
 import random
 import time
 import about
 import quotes
 
 
 def closeprog():
  raise SystemExit
 
 class main:
  root = Tk()
  frame = Frame()
  root.title(Quoter %s % (about.ver))
  root.minsize(300, 50)
 
  showquote = Label(root, text=random.choice(quotes.quote))
  showquote.pack()
 
  exit = Button(root, text=Exit, command=closeprog)
  exit.pack(side=LEFT)
 
  aboutprg = Button(root, text=About, command=about.main)
  aboutprg.pack(side=LEFT)
 
 
  totalq = Label(root, text=quotes.qts)
  totalq.pack(side=BOTTOM)
  
  root.mainloop()
 
 (I'd appreciate some suggestions, or notifications on how bad something
 is)

Some comments ---

You create a Frame, but you never use it.

You've put a whole lot of code in a class, but it's not in a class method.  This
is kinda missing the point of using classes in the first place (and it just
flat-out wouldn't work in the majority of OO languages).

Here's what I would do:

class Main(Frame):
def __init__(self, master=None, **kw):
Frame.__init__(self, master, **kw)

showquote = Label(self, text=random.choice(quotes.quote))
showquote.pack()

# etc

if __name__ == '__main__':
root = Tk()
main = Main(root)
main.pack(fill=BOTH, expand=True)
root.mainloop()
###

Do you see what I am doing there, and why it is different from your approach?

 I have a small problem: I don't know how to make a button that would 
 redisplay another quote in the same window, ie I need a button that 
 says: Show Another Quote. (Actually I don't know how to make it show 
 another quote even in a new window!!). I got the interface from Catfood

Once you've got a label, you can change its text attribute by using its
.config() method.

So, you could do something like this:

# ...
showquote = Label(self, text=random.choice(quotes.quote))
showquote.pack()

def changeQuote():
currQuote = showquote.cget('config')  # Get the current quote
newQuote = random.choice(quotes.quote)
while newQuote == currQuote:  # Make sure the new quote differs
newQuote = random.choice(quotes.quote)
showquote.config(text=newQuote)
Button(self, text='Show another quote', command=changeQuote).pack()

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python newbie..system call help

2005-07-12 Thread jfouhy
Quoting Mike Pindzola [EMAIL PROTECTED]:

 Should I be even trying to make a system call? Is there a better way to
 talk to the shell? Either way, please enlighten me. Thanks.

There may be a better way to achieve what you want to do, without using the
shell at all.  For example, the os and os.path modules include a range of
functions for manipulating files and directories (listing, walking, moving,
renaming, et cetera).  Perhaps, if you say what you are trying to achieve, we
can give some pointers.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding quotation marks around variables

2005-07-10 Thread jfouhy
Quoting Robert [EMAIL PROTECTED]:

 I have figured out how to do the math but I need to display these two
 variables with quotation marks around them. 
 
 Also I need to add these two variables together and display the
 hexadecimal of these two variables???
 
 Also how do you display wheather one variable is greater than or less
 than or equal to the other variable?

Hi Robert,

I recommend you have a look through the online Python tutorial
(http://python.org/doc); in particular, section 3:
http://docs.python.org/tut/node5.html

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Single Underscore

2005-07-10 Thread jfouhy
Quoting Kevin Reeder [EMAIL PROTECTED]:

 What's the significance of naming a variable with a single
 underscore as its first character? For example, I'm looking at
 find.py in the standard library and it has variables named _debug
 and _prune.

Basically, it means These variables are internal and not part of the API;
please do not use them in your code because they may change without warning.

The reference here is PEP-8, the Python style guide:
http://www.python.org/peps/pep-0008.html

Excerpt:


In addition, the following special forms using leading or trailing
underscores are recognized (these can generally be combined with any
case convention):

- _single_leading_underscore: weak internal use indicator
  (e.g. from M import * does not import objects whose name
  starts with an underscore).

- single_trailing_underscore_: used by convention to avoid
  conflicts with Python keyword, e.g.
  Tkinter.Toplevel(master, class_='ClassName').

- __double_leading_underscore: class-private names as of Python 1.4.

- __double_leading_and_trailing_underscore__: magic objects or
  attributes that live in user-controlled namespaces,
  e.g. __init__, __import__ or __file__.  Sometimes these are
  defined by the user to trigger certain magic behavior
  (e.g. operator overloading); sometimes these are inserted by the
  infrastructure for its own use or for debugging purposes.  Since
  the infrastructure (loosely defined as the Python interpreter
  and the standard library) may decide to grow its list of magic
  attributes in future versions, user code should generally
  refrain from using this convention for its own use.  User code
  that aspires to become part of the infrastructure could combine
  this with a short prefix inside the underscores,
  e.g. __bobo_magic_attr__.


class-private (double leading underscore) basically means extra effort is
expended in making the variable hard to see.  It's still not enforced, though. 
This is easiest to explain with an example:

 class Foo(object):
...  __x = 3
...  def p(self):
...   print self.__x
...
 f = Foo()
 f.__x
Traceback (most recent call last):
  File stdin, line 1, in ?
AttributeError: 'Foo' object has no attribute '__x'
 f.p()
3
 f._Foo__x
3

Google for python name-mangling if you want to know more about this :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] py2exe

2005-07-09 Thread jfouhy
Quoting D. Hartley [EMAIL PROTECTED]:

 I modified the setup.py file to match the details of my game (as best
 I can imagine: I don't know what optimize = 2 #0,
 1, or 2; like -O and -OO means, so I just left it as his sample had
 it, 

From python -h:

-O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)
-OO: remove doc-strings in addition to the -O optimizations

optimize=2 means py2exe will optimize the bytecode and remove doc strings; this
is probably OK since you're not going to be running the debugger on your
finished executable.

 and I'm not sure if I put in all of the module names it will need
 specified, but it looks as if its supposed to give me an error if it
 can't find them). 

py2exe will search for all the modules it thinks it needs, but sometimes it will
miss some.  Generally, the best way to find out if it missed anything is to run
your executable and see if it crashes :-)

 But then the tutorial says simply run this script
 and it will do all the work. 

You need to run it from the command line: python setup.py py2exe

HTH.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding attributes to imported class

2005-07-06 Thread jfouhy
Quoting Michael Lange [EMAIL PROTECTED]:

 I'm trying to write a python wrapper for the tkDnD Tk extension to add
 drag and drop support

Hi Michael,

Just a side issue --- tkDnD seems to be broken in python 2.4: see bug 1164742,
http://sourceforge.net/tracker/index.php?func=detailaid=1164742group_id=5470atid=105470

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] super() and inherited attributes?

2005-06-28 Thread jfouhy
Quoting Alan G [EMAIL PROTECTED]:

 I don't know the direct answer but the more common way 
 of doing that in Python is not to use super() but just 
 call the inherited constructor directly:
 
 Parent.__init__(self,'I am a child')
 
 
 SO if you just want to fix the itch use that, if you want 
 to understand super() then that won't help and its over to 
 someone else! :-)

OTOH, there are reasons for prefering super over a direct call.

This explains it better than I could:
http://www.python.org/2.2.3/descrintro.html#cooperation

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] max(len(item)) for cols

2005-06-20 Thread jfouhy
Quoting János Juhász [EMAIL PROTECTED]:

 That I don't know is the asterisk in zip(*[labels] + rows)
 I wasn't able to find in the python reference what it means.
 May you help me in that ?

You can find it in the language reference: http://docs.python.org/ref/calls.html

Basically, suppose you have a list:

 myList = ['foo', 42, None]

and a function:

 def doSomething(s, n, t):
... print 'The meaning of %s is %d' % (s, n)
... if t:
... return True
... return False
...

Then you can call like this:

 doSomething(*myList)
The meaning of foo is 42
False

The *myList means expand myList into a bunch of positional parameters.  So,
doSomething got the first element of myList as s, the second element as n, and
the third element as t.

You can do the same thing in reverse, in the function definition.  eg:

 def myFunction(*args):
... for x in args:
... print x,
... print
...
 myFunction(1, 2, 'foo', 'bar', 37)
1 2 foo bar 37

In this case, all the positional arguments got combined into a tuple, and given
the name 'args'.

Finally, this works with keyword arguments as well, but you have to use
dictionaries, and you use two asterisks instead of one.

 myDict = { 'x':3, 'y':7, 'z':19 }
 def doSomeArithmetic(y=0, z=0, x=0):
... return y*z+x
...
 doSomeArithmetic(**myDict)
136

HTH!

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Layering Canvas widgets with Tkinter

2005-06-19 Thread jfouhy
Quoting Phillip Hart [EMAIL PROTECTED]:

 So far, I've tried using a single Tk window, creating a series of canvas
 widgets, each containing a series of buttons. When pressed, each button
 calls a function which uses .grid_remove() on the current canvas and
 creates a new canvas with new buttons in its place (a new menu).

Your logic is a bit confused, I think.

What you are aiming for, I think, is something like this:

  Display Main Menu
 menu 1 pushed -- hide main menu, display menu1
 back pushed -- hide menu1, display main menu
 menu 2 pushed -- hide main menu, display menu2
 back pushed -- hide menu2, display main menu
 menu 3 pushed -- hide main menu, display menu3.

One way you could do this is to create all four menus, and then use callbacks
that simply show/hide as appropriate.

For example:

 Note that I have replaced leading spaces with underscores #
 You will need to undo this to run the program #

from Tkinter import *

def switch(hide, show):
hide.grid_forget()
show.grid(sticky=N+S+E+W)

tk = Tk()

# This is necessary, otherwise the canvas shrinks to the size of the button(s)
it contains.
# You could also use width= and height= to give the canvases a specific size.
tk.grid_rowconfigure(0, weight=1)
tk.grid_columnconfigure(0, weight=1)

main = Canvas(tk)
menu1 = Canvas(tk, background='green')
menu2 = Canvas(tk, background='pink')
menu3 = Canvas(tk, background='yellow')

for i, m in enumerate((menu1, menu2, menu3)):
Button(main, text='Menu %d' % i, command=lambda m=m: switch(main, m)).grid()
Button(m, text='Back', command=lambda m=m: switch(m, main)).grid()

main.grid()
tk.mainloop()

##

I am only creating the canvases once, and then just using grid() and
grid_forget() to hide/show them as appropriate.  In your code, you created a new
canvas with every call to menu1/menu2/menu3.  Also, you never called grid_forget
on any of those canvases (so they never disappeared).

Finally, I made all the canvases children of tk, rather than making
menu1/menu2/menu3 children of main.  If menu1 were a child of main, then to
display menu1, you would have to hide the buttons (because menu1 would display
inside main).



Additional comments:
 - grid_forget is, I think, exactly the same as grid_remove.
 - Are you sure you want to be using canvases at all?  Geometry managers like
grid are normally used with Frames.  If you want to display widgets on a canvas,
the normal way to do it is to use canvas.create_window.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Every Other

2005-06-19 Thread jfouhy
Quoting Chuck Allison [EMAIL PROTECTED]:

 Hello Tutors,
 
 What would be the most Pythonic way of printing (or extracting) every 
 other element of a list? Thanks in advance.

This is probably it:

 arr = range(20)
 arr[::2]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
 arr[1::2]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] max(len(item)) for cols

2005-06-17 Thread jfouhy
Quoting Jnos Juhsz [EMAIL PROTECTED]:

 
 Dear Guys,
 
 I have a 2D array:
 [['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']]
 
 
 How can I get what is the max(len(item)) for the columns ?
 I would like to get a list with the max_col_width values.
 
 I hope that, it can wrote with some nice list comprehension, but I can't
 do that :(

There is a magic trick: You can use zip(* ) to transpose a two-dimensional 
array.

eg:

 arr = [[1,2,3], [4,5,6]]
 zip(*arr)
[(1, 4), (2, 5), (3, 6)]
 zip(*zip(*arr))
[(1, 2, 3), (4, 5, 6)]

(if this is not obvious to you, I recommend spending the time to figure out how
this works)

You can use this to easily get at the columns of your array.  And once you have
the columns, you can use a list comprehension to get the lengths of the elements
and find the max.

eg:

 arr = [['a'*random.randint(1, 10) for i in range(5)] for j in range(10)]
 pprint.pprint(arr)
[['aa', 'a', 'aa', '', ''],
 ['aaa', 'aa', 'aa', 'aaa', 'aaa'],
 ['aa', 'aaa', '', 'aa', 'aaa'],
 ['', 'aa', 'aa', 'aa', 'aa'],
 ['aa', 'a', 'aa', 'a', ''],
 ['aaa', 'a', 'aa', 'a', 'aa'],
 ['', 'a', 'a', '', 'aa'],
 ['a', 'aaa', 'a', 'aa', 'aaa'],
 ['', 'aa', 'aa', 'a', 'a'],
 ['a', 'aa', 'aa', 'aaa', 'aa']]
 [max([len(s) for s in l]) for l in zip(*arr)]
[10, 9, 10, 6, 10]

HTH!

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling a function

2005-06-09 Thread jfouhy
Quoting Kevin Reeder [EMAIL PROTECTED]:

 The second module is timings.py.
 
 import time, makezeros
 
 def do_timing(num_times, *funcs):
  totals = {}
  for func in funcs: totals[func] = 0.0
   for x in range(num_times):
   for func in funcs:
starttime = time.time()
apply(func)
stoptime = time.time()
elapsed = stoptime-starttime
totals[func] = totals[func] + elapsed
for func in funcs:
print Running %s %d times took %.3f seconds %
 (func.__name__, num_times, totals[func]) 
 
 do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply))

Hi Kevin,

I have two comments.  First, a simple one:

Using apply is no longer necessary in python.  It is better to just call the
function directly.  (ie: replace 'apply(func)' with 'func()')

Now, to your problem:

You have (possibly) slightly misunderstood the star notation.

Consider:

 def printArgs(*args):
... print args
...
 printArgs(1, 2, 'foo', 'bar')
(1, 2, 'foo', 'bar')

Basically, all the arguments to printArgs get collected into a tuple, which gets
the name 'args' in this example.

Here's another example:

 def printArgs2(x, y, *args):
... print 'x:', x
... print 'y:', y
... print 'remaining:', args
...
 printArgs2(1, 'foo', 3, 'hello world', 99)
x: 1
y: foo
remaining: (3, 'hello world', 99)

In this case, x and y consumed the first two arguments to printArgs2, and the
remainder went into the catch-all args.

Now, lets look at the relevant bits of your code:


def do_timing(num_times, *funcs):
...


This says: Call the first argument 'num_times', and put any other arguments
into a tuple called 'funcs'.

You then do this:


do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply))


Here, you are calling do_timing with _two_ arguments.

First argument:   100
Second argument:  (makezeros.lots_of_appends, makezeros.one_multiply)

Your second argument is a tuple with two elements.  funcs in your function will
be set to a tuple containing all remaining arguments --- ie:
((makezeros.lots_of_appends, makezeros.one_multiply),)  (which is a tuple with
one element, whose element is a tuple with two elements).

You can correct this in two ways:
 - Change the function definition to:
  def do_timing(num_times, funcs):
   Now, funcs is just an ordinary positional argument, and it will take whatever
you give it.  If you give it a tuple of functions, then you can iterate over it
the way you expect.

or:
 - Change the function call to:
  do_timing(100, makezeros.lots_of_appends, makezeros.one_multiply)
   *funcs will consume the two function arguments, giving you the same result as
in the first option.

My personal preference would be for the first option, which I think is clearer..

(it better expresses the idea that you have written a function which will take 
a 
list of functions and time them)

HTH!

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically calling a class

2005-06-09 Thread jfouhy
Quoting Ryan Parrish [EMAIL PROTECTED]:

 example -
 
 list_of_classes = ['A', 'B', B', 'A']
 
 class A:
   doingsomething
 class B:
   doing something
 
 for x in list_of_classes:
   x()
 
 my problem is that i get 'TypeError: 'str' object is not callable', of 
 which i understand what the error is saying, i just want to know how to
 dynamically call the class.

Just put the class object in the list!

 class A:
...  pass
...
 class B:
...  pass
...
 class C:
...  pass
...
 classes = [A, B, C]
 for cls in classes:
...  x = cls()
...  print x.__class__
...
__main__.A
__main__.B
__main__.C

You can do some black magic to go from the string 'A' to the class A (eg, use
eval()), but it's generally better to avoid that if you can.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] repr()

2005-06-07 Thread jfouhy
Quoting Alan G [EMAIL PROTECTED]:

 The other waybthat you can use repr() is by using the backtick
 notation
 
  print `s`
 'hello'
 

It's worth noting that backticks are going out of fashion --- I think they are
queued for deletion in Py3000.  Better to get in the habit of just calling
repr() directly.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Py2exe Problem

2005-06-02 Thread jfouhy
Quoting Alberto Troiano [EMAIL PROTECTED]:

 I'm having a problem with Py2exe.
 I created the executable but when I try to execute it it gives the
 following 
 error:
 
 Traceback (most recent call last):
  File NovusExtension.pyw, line 8, in ?
  File Pmw\__init__.pyc, line 28, in ?
 WindowsError: [Errno 3] El sistema no puede hallar la ruta especificada:
 
 'C:\\Documents and 
 Settings\\percy.IMPOR-FERNANDO\\Escritorio\\NovExt\\dist\\library.zip\
 \Pmw/*.*'

It might help if you translated that error message :-)

But, I will make one guess, since I see the problem is to do with Pmw: 

From this page: http://pmw.sourceforge.net/doc/dynamicloader.html


 When Pmw is first imported, an instance of PmwLoader is created and placed into
sys.modules['Pmw']. From that point on, any reference to attributes of the Pmw
'module' is handled by the loader. The real Pmw package is stored in
sys.modules['_Pmw'].

...

 Freezing Pmw

Since the dynamic loader requires that Pmw be installed at run time, it can not
be used when freezing Pmw. In this case, a single module containing all Pmw code
is required, which can then be frozen with the rest of the application's
modules. The bundlepmw.py script in the Pmw bin directory can be used to create
such a file. This script concatenates (almost) all Pmw megawidget files into a
single file, Pmw.py, which it writes to the current directory. The script is
called like this:

 bundlepmw.py [-noblt] [-nocolor] /path/to/Pmw/Pmw_X_X_X/lib

The last argument should be the path to the lib directory of the required
version of Pmw. By default, the Pmw.py file imports the PmwBlt and PmwColor
modules and so, to freeze an application using Pmw, you will need to copy the
files PmwBlt.py and PmwColor.py to the application directory before freezing.

If you are sure that your application does not use any of the Pmw.Blt or
Pmw.Color functions, you can use the -noblt or -nocolor options. In this case
Pmw.py will be modified so that it does not import these module(s) and so will
not need to be included when freezing the application.

If your application only uses a few Pmw megawidgets, you can remove the
references to the usused ones in the files list in the bundlepmw.py code. To
make the change, take a copy of the script and modify it. This will make the
Pmw.py file smaller. However, be sure that you do not delete megawidgets that
are components or base classes of megawidgets that you use.


If you haven't done this, you will need to, otherwise Pmw won't work with 
py2exe.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Program to lock folders under win32

2005-05-26 Thread jfouhy
Quoting Mark Kels [EMAIL PROTECTED]:

 I want to make a program to lock folders (so the user can only access
 them if he knows the password) under win32, the only problem is that I
 have no idea how to start or what to do. Do you guys have any ideas of
 how to do it?

Is your program going to be running all the time?

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 is a recipe
showing how to lock files on POSIX and Win32.  So possibly you could do
something like that, where your program acquires locks on all the files and then
releases the lock when given the password...

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exceptions and its error messages

2005-05-25 Thread jfouhy
Quoting Jonas Melian [EMAIL PROTECTED]:

 How to know all the exceptions that there are? (i.e. OSError,
 ImportError)

Check the Python library reference (on python.org); section 2.4: Built-in
exceptions.

Of course, you can subclass Exception to build your own!

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2005-05-25 Thread jfouhy
Quoting John Carmona [EMAIL PROTECTED]:

 The next step is to use the built-in functin ord() in order to convert
 each character to an ASCII integer. I have had a look at the ord() function
 but it says that it only take one argument i.e. ord('a'). How could I
 execute to convert each character into an ASCII integer?

The chr() function only takes one argument (eg: chr(97)).  How did you use it to
convert each integer into an ASCII character?

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] xml

2005-05-24 Thread jfouhy
Quoting D. Hartley [EMAIL PROTECTED]:

 anyone have a pointer to a *SIMPLE* intro to xml as used in python? I
 looked in the library and there are about 11 xml-related modules.
 
 Perhaps something 'remote'. ;)

Use ElementTree!

(google for it)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] better resolution on time.sleep()?

2005-05-23 Thread jfouhy
Quoting Roger Merchberger [EMAIL PROTECTED]:

 I really only need between 500 and 1000 samples per second, but as the 
 smallest sleep available normally is time.sleep(.01) -- which brings my
 samples/sec to a nice 100; but I need it a little faster.

Where did you find that out?
 
 2) will upgrading to a newer version of Python get me what I need?
 [[ I looked thru the New in 2.4 dox and nothing I needed was
 listed...]]

I just did some experimenting ... I am running ActiveState Python 2.4.1 under
Windows XP / cygwin.

 def check():
...  now = time.clock()
...  for i in xrange(1):
...   time.sleep(0.001)
...  print time.clock() - now
...
 check()
11.2695306247
 def check():
...  now = time.clock()
...  for i in xrange(10):
...   time.sleep(0.0001)
...  print time.clock() - now
...
 check()
2.77601985727
 check()
8.70900742972

The first test is fairly consistent with time.sleep(0.001) doing what you
expect.  The second is a bit puzzling to me, though...

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [HELP]win32 shutdown, restart, logoff

2005-05-22 Thread jfouhy
Quoting Shidai Liu [EMAIL PROTECTED]:

 Any one know how to make a shutdown, restart, logoff call in windows os
 like 98, 2000 and xp?

Try this: win32api.InitiateSystemShutdown(None, 'Kaboom!', 2000, False, False)

Parameters:
 1. Computer to shutdown (None for lcoalhost)
 2. Message to display.
 3. Time in ms to display message (0 for no message).
 4. Kill programs (False to allow user a chance to save their work).
 5. Reboot or shutdown.

If you are doing win32 programming, I strongly recommend Mark Hammond's book!
(since that's where I got this information)

Note that I have not tested this (in particular, it is possible I have the
orientation of the two boolean parameters wrong).

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Comparing a string

2005-05-20 Thread jfouhy
Quoting Jonas Melian [EMAIL PROTECTED]:

 I'm tryin compare a string with a value with style of pattern-matching.
 
 string = 'i686'
 
 if string == glob.glob(i?86):

This is a task for regular expressions!

Have a look at the re module.

(and feel free to ask for more help if you're having trouble with it)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Disable menubar

2005-05-19 Thread jfouhy
Quoting Alberto Troiano [EMAIL PROTECTED]:

 About disabling the button it would be nice to know if that can be done
 , although I made some work around and I managed to restrict the
 Toplevels.

You can disable buttons and menu items with the state option.  Setting
state=DISABLED will grey-out a Button or menu item. (you need to use the
entryconfig method of the menu)

You can reenable the object by setting state=NORMAL.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python debugger under Tiger?

2005-05-18 Thread jfouhy
Quoting Mike Hall [EMAIL PROTECTED]:

 Does anyone know of a Python debugger that will run under OSX 10.4? 
 The Eric debugger was looked at, but it's highly unstable under 
 Tiger. Thanks.

pdb should work :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] buttons, scrollbar, tkinter

2005-05-18 Thread jfouhy
Quoting Ron Alvarado [EMAIL PROTECTED]:

 Is there any way to change this to put in a column of buttons and it
 will scroll like it does now. I've tried but when I put in the buttons the
 scrollbar just grows with all the buttons and won't do anything.

I'm not exactly sure what you're after here ...

You can't put buttons into a Listbox.  A Listbox will only take strings.

You can attach a scrollbar to a Frame and pack a bunch of buttons into that.

But I find the easiest solution to making scrolling things is to get Pmw:
http://pmw.sourceforge.net/ .  A Pmw.ScrolledFrame will probably do what you
want with very little effort on your part.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] using -i flag with '''if __name__ == __main__:'''

2005-05-17 Thread jfouhy
Quoting Terry Carroll [EMAIL PROTECTED]:

 I've recently started using the construct 
 
  if __name__ == __main__:
  main()
 
 And found I can't do the -i thing effectively any more. What's a good 
 equivalent approach?

If main is a class, you could change to 'm = main()'; that would at least give
you access to the class attributes.

Another possibility is to look at this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 15, Issue 40

2005-05-17 Thread jfouhy
Quoting Kent Johnson [EMAIL PROTECTED]:

 J. Gabriel Schenz wrote:
  Now, I am new to Python as well, but it seems like apply might not be
  completely superfluous. I was thinking that if one were using a functional
  programming style, and had to apply a function determined at runtime to an
  argument, then one could use this apply to do so. 
 apply() is superfluous. apply(function, args[, keywords]) is exactly
 equivalent to function(*args, [**keywords]). 

Ooh.  Functional programming is fun!

 multers = [i.__mul__ for i in range(10)]
 mulTable = [[f(i) for i in range(10)] for f in multers]
 import pprint
 pprint.pprint(mulTable)
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
 [0, 3, 6, 9, 12, 15, 18, 21, 24, 27],
 [0, 4, 8, 12, 16, 20, 24, 28, 32, 36],
 [0, 5, 10, 15, 20, 25, 30, 35, 40, 45],
 [0, 6, 12, 18, 24, 30, 36, 42, 48, 54],
 [0, 7, 14, 21, 28, 35, 42, 49, 56, 63],
 [0, 8, 16, 24, 32, 40, 48, 56, 64, 72],
 [0, 9, 18, 27, 36, 45, 54, 63, 72, 81]]

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] hettingertools?

2005-05-17 Thread jfouhy
Quoting Terry Carroll [EMAIL PROTECTED]:

 On Tue, 17 May 2005, D. Hartley wrote:
  This was a hint from a python challenge, but I can't find anything
  about it online: Anyone know?
 Raymond Hettinger is a frequent contributor to Python. I don't know if 
 that is part of it.

If I had to guess, I would guess: itertools.
(http://python.org/doc/2.3.5/whatsnew/node18.html)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter questions

2005-05-16 Thread jfouhy
Quoting Alberto Troiano [EMAIL PROTECTED]:

 How can I change the background color of a label??
 How can I change the font-size and make it BOLD??

Check out Fredrik Lundh's _Introduction to Tkinter_:
http://www.pythonware.com/library/tkinter/introduction/

In particular, the section on widget customization/styling:
http://www.pythonware.com/library/tkinter/introduction/widget-styling.htm

If you are using Pmw, you can also use Pmw.logicalfont() to change the font.

(eg: 

tk = Tk()
fixed = Pmw.logicalfont(name='Fixed', weight='bold')
Label(tk, background='blue', font=fixed, text='Hello world!').pack()

)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to verify all things are equal to one another

2005-05-15 Thread jfouhy
Quoting Terry Carroll [EMAIL PROTECTED]:

 Suppose I have several variables, e.g.: a, b, c, d, e, f, g.
 
 I would like to be able to see if they're all the same, I don't care
 what the value is, as long as they're equal. If they're all equal to 0, or
 to spam, or to [cleese, idle, gilliam], as long as they're the
 same.

Two suggestions ---

First, you can actually do multiple equality testing the way your mathematics
teacher would:

if a == b == c == d == e == f == g:
  # do stuff

(this grates against my instincts in some ways, since it breaks associativity
(because it means 'a == b == c' is different from '(a == b) == c'), but it's in
the language, so I guess it's the Right Way).

You could also do this:

# python2.3: use Set module
if set([a,b,c,d,e,f,g]) == set([a]):
  # do stuff

HTH.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] py2exe

2005-05-13 Thread jfouhy
Quoting [EMAIL PROTECTED] [EMAIL PROTECTED]:

 Thanks for this. But do you know how I can achieve a single exe file
 with the dist and build folders. Is it possible to run a single exe file
 without the other dependencies? 

There is another freezer here: 
http://starship.python.net/crew/atuining/cx_Freeze/

I don't have any experience with it, though, so I don't know if it will do what
you want.

Just as a note --- you only need to distribute the contents of the dist
directory.  Don't worry about the build directory or your source code.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] character format

2005-05-11 Thread jfouhy
Quoting D. Hartley [EMAIL PROTECTED]:

 Does anyone have a hint as to what things like this:
 \xaf\x82\r\x00\x00\x01\
 
 refer to? 

Basically, they are unprintable characters.

 ord('\x82')
130
 chr(130)
'\x82'

If you look at http://asciitable.com/, you will see that ascii chracter 130 is
an e with a tick on its head.  This is not something you can find on your
keyboard, so python can't/won't display it.

Also, if you do some maths, you will see that 82 in hexadecimal is 130 in 
decimal:

 8*16 + 2
130

So that explains why it is x82 :-) (with the backslash to indicate an escape
sequence, and an x to indicate hexadecimal)

'\r' is the carriage return character [1].  Looking at asciitable.com, I can see
that it is hex d / ascii 13.

 '\x0d' == '\r'
True

Hope this helps!

-- 
John.

[1] Historical note: In the days of typewriters [2], a carriage return would
send the carriage (with the ink in it) back to the left, so you could start
typing a new line.  A line feed would advance the paper by one line.  These were
separate operations 'cause sometimes you wouldn't want to do both.

The characters entered ASCII (because of early printers?) and different
operating systems used them to end lines in different ways: in UNIX, the
end-of-line character is a newline character ('\n'); in MSDOS/Windows it is both
('\r\n'); and I think Macintoshes just use a '\r'.

Fortunately, python has so-called universal newline support, so you don't need
to worry about all that :-)

[2] Before my time, so there could be errors of fact...
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] character format

2005-05-11 Thread jfouhy
Quoting Max Noel [EMAIL PROTECTED]:

  You mean é? Oh, it is perfectly printable. It's even on my 
 keyboard (as unshifted 2), along with è, ç, à and ù. Ah, American 
 cultural assumption... ^^

I was waiting for someone to call me on that ...

As was pointed out, I'm not American.  I guess the problem stems from an
American cultural assumption, though, in that Americans (I think) developed the
ASCII character set without any thought for other languages.

Will a standard xterm display chr(130) as é in linux for you, Max?  Or under Mac
OS X?

Anyway, in Python3000 all strings will be unicode, so it won't matter then :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] following the chain

2005-05-10 Thread jfouhy
Quoting Liam Clarke [EMAIL PROTECTED]:

 While we're on challenge 4, I assume a linked list is important. Can
 anyone point me at a good introduction to linked lists? 

A linked list, at a high level, is a data structure made of nodes, where each
node contains some data and a pointer to the next node.

Here is a really simple python example:

 class Node:
...  pass
...
 root = Node()
 root.value = Start
 n = root
 for i in range(10):
...  n.next = Node()
...  n.next.value = str(i)
...  n = n.next
... else:
...  n.next = None
...
 # We now have a linked list starting at root.
...
 n = root
 while n != None:
...  print n.value
...  n = n.next
...
Start
0
1
2
3
4
5
6
7
8
9


Of course, the pointer to the next node could be anything; as long as your
program logic knows how to use it to get to the next node.

One of the advantages linked lists have over arrays in languages like C++ is
that they can be as big as you like, whereas arrays are created with a fixed
side.  But python lists don't have that problem, so they're a lot less useful
here...

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python riddles - zip question

2005-05-09 Thread jfouhy
Quoting D. Hartley [EMAIL PROTECTED]:

 How do I open a zipfile? I see commands for closing it, but i only see
 class zipfile - no command like urlopen() (!!!)

Look at the constructor :-)

 import zipfile
 z = zipfile.ZipFile('myzip.zip')
 z.printdir()
 ...

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Any easy way to invoke the default browser on a specified URL?

2005-05-09 Thread jfouhy
Quoting Terry Carroll [EMAIL PROTECTED]:

 Is there any way, from within Python, to cause the default browser 
 (Firefox, in my case) to be invoked with a specific URL?

If you're on Win32, try:

 import win32api
 win32api.ShellExecute(0, 'open', 'http://www.google.com/', None, '', 1)

Parameters in order: 
 - Handle to the parent window (0 for no parent)
 - Operation to perform (you can also use 'print', and maybe others?)
 - Name of the file/shortcut to execute
 - Optional parameters for the new process
 - Initial directory for the new process
 - Flag indicating if the new window should be shown or not.

[information from Mark Hammond's book]

Basically, this does the same thing as double-clicking on the file/shortcut in
Windows Explorer.

If you're on Linux, I'm not sure.  I think different distros / window managers
may have different ways of defining things like a default browser, or different
ways of getting at them.

And I don't know anything about Mac OS X :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] zip question

2005-05-09 Thread jfouhy
Quoting D. Hartley [EMAIL PROTECTED]:

 Instances have the following attributes: 
 
 filename, comment, etc.
 
 
 I've tried about ten things to get filename to work:
 
 myzip.filename(99905.txt) (str not callable)

Check out the error message: str not callable.  You are trying to call
something whose type is str --- ie: a string.  In python, there is no
distinction between callable and noncallable attributes.  

try:
 print myzip.filename
It should print the filename that this ZipInfo object refers to.

Likewise, myzip.comment is a string which is the comment attached to the file in
the zip.

If you have any background in other languges, it might help you to think of
these as member variables (or whatever they call them).  And a ZipInfo object
appears to be similar to a struct in C/C++.

I hope this helps.
(and if it doesn't, the fault is probably in the explanation, so keep asking,
and I (or someone else) will try again :-) )

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python riddles

2005-05-08 Thread jfouhy
Quoting Jacob S. [EMAIL PROTECTED]:

 Unfortunately, after about 50 pages or so, it stops, apparently using
 too much memory, or something causing the computer to lock badly enough I
 have to wait for 5 minutes for the keyboard interupt to work. I believe it
 also hints in the source that I should do this about 300 times? I just want
 to know if I'm on the right track, and maybe a slight push in a better,
 less memory consuming direction...

When I did riddle 4, my loop was for i in range(320), and I had a break
condition as well (if I didn't find a number of the right form).  The break
condition triggered before the for loop exhausted its range.

If you saw the line with two numbers, and you modified your code so that it only
picks up the right one, then you should be able to solve the riddle, I think..

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] elegant way to turn list into string?

2005-05-07 Thread jfouhy
Quoting Max Russell [EMAIL PROTECTED]:

 anyway- I don't like the output which come in the
 form:
 ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
 'w', 'x', 'y', 'z', 'a']
 
 
 What I'd like to do is take my list and turn it into a
 string, which looks neater when printed.
 
 I've tried using join() but that didn't work, can
 anyone give me a pointer here?

As Tanja points out, you can use ''.join().

You may also be interested in the chr() and ord() built-in functions.

eg:

 alphabet = [chr(i) for i in range(ord('a'), ord('z')+1)]
 alphabet
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

See also this.py in your lib directory :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generator function question?

2005-05-07 Thread jfouhy
Quoting John Clark [EMAIL PROTECTED]:

 import sys
 
  def neverEndingStatus(currentChar_ = '|'):
  while 1:
   if currentChar_ == '|':
currentChar_ = '\\'
   elif currentChar_ == '\\':
currentChar_ = '-'
   elif currentChar_ == '-':
currentChar_ = '/'
   elif currentChar_ == '/':
currentChar_ = '|'
   yield currentChar_
  
 
 x = neverEndingStatus()
 
 def Test1():
  for w in range(1, 100):
  sys.stderr.write('\b'+x.next())
  for z in range(1, 1):
  z = z + 1

One of the big uses for generators is in loops.  eg:

 import time
 def nes():
...  chars = ('|', '\\', '-', '/')
...  i = 0
...  while True:
...   yield chars[i]
...   i = (i + 1) % len(chars)
...
 for c in nes():
...  print c,
...  time.sleep(0.5)
...
| \ - / | \ - / | \ - / | \ - / | \ - / | \ ...

Of course, you'll need _some_ way of breaking out of the loop eventually (either
a 'break' statement in the for loop, or something in nes() to raise
StopIteration, which will cause the for loop to exit naturally).

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Else in list comprehension

2005-05-07 Thread jfouhy
Quoting Max Noel [EMAIL PROTECTED]:

  Apparently, no. I just tried:
 
   b = [i for i in range(10) if (i % 2) == 0 else 0]

You can sometimes do a bit of trickery with and/or.  eg:

 odds = [(i % 2 == 1 and i or -1) for i in range(10)]
 odds
[-1, 1, -1, 3, -1, 5, -1, 7, -1, 9]

The big gotcha here is if any of the data you are interested in could be 0.  You
can progress to further trickery, but the payoff isn't always worth it.

Sometimes you just have to write a loop :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python challenges

2005-05-05 Thread jfouhy
Quoting Max Noel [EMAIL PROTECTED]:

 (Also, note that however simple they may seem, one can never 
 completely master regular expressions. There are entire books 
 dedicated to the things, and when properly used, they're the most 
 powerful text processing tool available for any language. In other 
 words, try to remember what you'll learn about them: they're very 
 useful.)

At the risk of being pedantic ---

This is not actually true.  There are things you can't do with regular
expressions.  The normal example is bracket counting: If I give you a string
like '(1+(2-4/(3+8)*(5+9)))-(8+1)', can you write me a regex which will produce
matches for only the chucks defined by the brackets?  

(in this case, the answer is this list of substrings: ['(1+(2-4/(3+8)*(5+9)))',
'(2-4/(3+8)*(5+9))', '(3+8)', '(5+9)', '(8+1)'] )

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python riddles

2005-05-04 Thread jfouhy
As seen on python-announce (via Dr Dobbs): 

http://www.pythonchallenge.com/

Good fun!

-- 
John.
[currently on riddle 6]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re Help with this script

2005-04-27 Thread jfouhy
Quoting John Carmona [EMAIL PROTECTED]:

 Is it that if you use while 1: you create a recursive function? Hope I
 am right.

No ...

Remember how functions can call other functions?

def add(x, y):
 Add two integers together. 
return x+y

def mul(x, y):
 Multiply two integers together. 
if x == 0:
return 0
if x  0:
x = -x
product = y
while x  1:
product = add(product, y)
x = add(x, -1)

The mul function calls add to do some of its work for it.

A recursive functio nis just a function that calls itself.  For example, we
could rewrite add as:

def increment(x):
 Increment an integer. 
return x + 1

def decrement(x):
 Decrement an integer. 
return x - 1

def add(x, y):
 Add two integers together. 
if x == 0:
return y
if x == 1:
return increment(y)
if x == -1:
return decrement(y)
if x  0:
return add(-1, add(add(1, x), y))
else:
return add(1, add(add(-1, x), y))

In this case, add is a recursive function, because it makes calls to itself. 
There's nothing magical about recursive functions or recursion; you just have to
be a bit careful to make sure that your program will end.  

Example:

def poem():
print 'A mad metaprogrammer wrote a mad metaprogram,\n which started: ',
poem()
print 'sort of close, were the words that the programmer finally chose\nTo
bring his mad program to some sort of close.'

The poem() function will call the poem() function which will call the poem()
function which will call the poem() function, with no end in sight...

Another example:

def qsort(lst):
 Quicksort a list. 
if len(lst) = 1:
return lst
pivot = lst[0]
return qsort([x for x in lst if x  pivot]) + [pivot] + qsort([x for x in
lst if x  pivot])

This will stop because the argument in each recursive call to qsort is smaller
than the original, and because there is a smallest value ([]).

Does this help?

[Bonus questions:

1. Can you rewrite the recursive add() so that you only need one of (increment,
decrement)?

2. Do you recognise the inspiration for poem()?
]

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Re: Re: Tkinter and Animation

2005-04-27 Thread jfouhy
Quoting Jeremiah Rushton [EMAIL PROTECTED]:

 from Tkinter import *
 from time import sleep
 
 class Main:
 
  def __init__(self,master):
   button = Button(master,text='button')
   button.place(x=1,y=1)
   y=3
   for x in range(1,25):
sleep(.3)
button.place_forget()
button.place(x=1,y=y)
y +=2
 
 
 root = Tk()
 Main(root)
 root.title('test')
 root.mainloop()

Try adding a call to master.update_idletasks() in your for loop.  Still not
ideal, though, but maybe it would work better if you were doing the animation
after the Tk mainloop had started. (I'm just guessing there, though)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] using TK to view an image and then close the window

2005-04-25 Thread jfouhy
Quoting Ertl, John [EMAIL PROTECTED]:

  top = Tkinter.Toplevel(app,visual=truecolor,colormap=new)
  top.title(mainTitle)
  top.protocol(WM_DELETE_WINDOW, quit)
  top.bind(q,quit)
  top.bind(Q,quit)

In addition to Michael's comments, to bind to a keypress, you just do (eg)
widget.bind(q, f).

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] crash - switching between text window and graphics/gamewindow (high score)

2005-04-20 Thread jfouhy
Quoting D. Hartley [EMAIL PROTECTED]:

 The play file does end in .py. I am running it on Windows. You can
 double-click the play file, and run it straight that way, which is
 when the crash occurs. If you right click the file, go to edit in
 IDLE, and hit F5 to run it, the crash does NOT happen. I'm not sure
 why (but this is also why my debugging program won't tell me what's
 wrong).

I haven't been following this thread, so apologies in advance if this is
something you've already done ---

Have you tried running the program from a command prompt?  To do this, go to
Start--Run and type 'cmd'.  Then change to the directory with your script in it
('cd ' followed by the full directory path), and run the script by typing
'python ' followed by the script name.
(you may need to type something like 'c:\python24\python ' instead, if python is
not in your path)

The effect of this is that, when the program crashes, you will be left with a
window showing you (hopefully) some useful error messages.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Recursion....what are the best situations to use it?

2005-04-14 Thread jfouhy
Quoting [EMAIL PROTECTED] [EMAIL PROTECTED]:

 If this is too general a question, perhaps you can tell me when NOT to
 use recursion(where it would be inappropriate or inefficient).

In my opinion ---

Some problems are naturally recursive.  A good example is traversing data
structures (particularly trees), but there are other problems where there is an
obvious solution in terms of solving the same problem on smaller subinstances,
which obviously lends itself well to a recursive function.

In terms of efficiency: You should write your program first in the most obvious,
easy-to-understand way.  This may involve recursion if you are dealing with
naturally recursive data structures.  Then run your program and see if it's
slow.  If it is, try to figure out where the slowness is, either with profiling
or with theory.  If you conclude that your recursive function is slowing the
program down, then you can look to replace it with something else.

(I guess the traditional example of when it would be inappropriate is Pascall's
triangle --- ie: computing (n, r) == n!/(n-r)!r!.  The recursive algorithm looks
like this;

def C(n, r):
 Compute N choose R.

Require:
assert((type(n), type(r)) == (int, int))
assert(n = r)
assert(r = 0)


if r in (0, n):
return 1
else:
return C(n-1, r-1) + C(n-1, r)

But if you do this, you end up computing a lot of values multiple times.  It
works better if you use an array to build up the answers from the bottom --- a
technique called dynamic programming. )

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


RE: [Tutor] _winreg problems enumerating

2005-04-14 Thread jfouhy
Quoting Gooch, John [EMAIL PROTECTED]:

 I am writing a function whose job is it delete all of the selected items
 in a Listbox.

I think this problem is the same as the general problem of deleting a selection
of items from a python list.  The general solution is to iterate through the
list of selected indices backwards.

eg:

 from Tkinter import *
 tk = Tk()
 lb = Listbox(tk, selectmode=EXTENDED)
 lb.pack()
 for i in range(10):  # Inserting integers, so initially the item in each
...  lb.insert(END, i)   # position will be the same as its index.
... 
 lb.curselection()
('2', '4', '5', '7')
 for i in lb.curselection()[-1::-1]:
...  lb.delete(i)
... 
 lb.get(0, END)
(0, 1, 3, 6, 8, 9)
 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] high score lists

2005-04-14 Thread jfouhy
Quoting Max Noel [EMAIL PROTECTED]:

 On Apr 15, 2005, at 01:33, D. Hartley wrote:
  (I also
  just ended up writing the list like [score,user] because I couldnt
  figure out how to get it to sort by the second half of the tuple. I
  need a better tutorial book, I think!)
   I'm still using Python 2.3, so someone else will have to tell you what
 the key argument is.

Interestingly, the key argument is the solution to this problem:

 arr = zip(range(10), range(10,0,-1))
 arr
[(0, 10), (1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 
1)]
 arr.sort(key=lambda x: x[1])
 arr
[(9, 1), (8, 2), (7, 3), (6, 4), (5, 5), (4, 6), (3, 7), (2, 8), (1, 9), (0, 
10)]

Basically, key takes a function which, given a list element, returns the value
you actually want to sort by.
 
 - Your 2 best friends are the interactive Python shell, and the help() 
 function.

True, although help(sort) could be more helpful...

 help([].sort)

Help on built-in function sort:

sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) - -1, 0, 1



-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New to programming question (Ben M.) (Joseph Q.)

2005-04-13 Thread jfouhy
Quoting Joseph Quigley [EMAIL PROTECTED]:

 prefixes = 'JKLMNOPQ'
 suffix = 'ack'
 
 for letter in prefixes:
  if letter == ('O') or ('Q'):
   print letter + 'u' + suffix
  else:
   print letter + suffix

Hi Joseph,

This still won't work.  The reason is that your if statement is interpreted like
this:

if letter == 'O':
print letter + 'u' + suffix
elif 'Q':
print letter + 'u' + suffic
else:
print letter + suffix

Do you see?  The == binds more tightly than the or.  And, in python, 'Q' is
considered True for the purposes of tests.

So this is what happens:

 prefixes = 'JKLMNOPQ'
 suffix = 'ack'
 
 for letter in prefixes:
...   if letter == ('O') or ('Q'):
... print letter + 'u' + suffix
...   else:
... print letter + suffix
... 
Juack
Kuack
Luack
Muack
Nuack
Ouack
Puack
Quack
 

What you can do instead is this:

for letter in prefixes:
if letter in ['O', 'Q']:
print letter + 'u' + suffix
else:
print letter + suffix

HTH.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dispatching functions with args

2005-04-13 Thread jfouhy
Quoting Luke Jordan [EMAIL PROTECTED]:

 But this does not:
 
  def aFunc(configArg):
  print aFunc with argument
  print configArg
 
  def anotherFunc(configArg):
  print anotherFunc with argument
  print configArg 
  return aFunc,1
   ^^

  def dispatch(func,configArg):
  while func is not None and configArg is not None:
  func = func(configArg)
 
  dispatch(anotherFunc,1)
 

The line I have underlined is returning a tuple.  So, when you do 

func = func(configArg)

It has the effect of setting 

func = (aFunc, 1)

which you then try to call.

Instead, you could try:

func, configArg = func(configArg)

Of course, you would then need to ensure that any function you could call (such
as aFunc) also returns an appropriate tuple, otherwise the unpacking will fail.
(or wrap it in an if statement or a try:except block or something)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about Frames and Scrollbars

2005-04-12 Thread jfouhy
A couple of options...

You can pack a scrollbar on the right hand side of the containing frame and use
the yscrollcommand option to associate it with the frame --- see Fredrik Lundh's
Tkinter pages for an example.

Or you could grab Python MegaWidgets from http://pmw.sourceforge.com/ and use a
Pmw.ScrolledFrame instead, which will do the scrollbars for you automatically.
(this is my recommended option)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting of files based on filesize

2005-04-11 Thread jfouhy
Quoting Kent Johnson [EMAIL PROTECTED]:

 This is a hard problem. It is a version of the 0-1 knapsack problem -
 googling for that might give 
 you some ideas.
  Hi
  Some of my harddrives are getting full and i would like to burn the files 
  to 
  some cheep DVD's. Filesizes range from lets say 1Mb to 1Gb. 
  Ofcourse i would like to optimize the size of each DVD to be as close to 
  4.7Gb 
  as possible (to save this cheep media :) ).

Hmm, I would have called it an example of bin packing...

http://en.wikipedia.org/wiki/Bin_packing_problem

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for a number adding script

2005-04-10 Thread jfouhy
Quoting Kenny Li [EMAIL PROTECTED]:

 A little while ago, when I tried to pick up Python, I ran into an
 article that has a script to add up all numbers in a text file (email
 message, for example). I want to use that script now, but I could not
 find (recalled) the URL to the article. If you have a point, please
 let me know. Appreciate it.

I don't have the original one you saw ...

But this is a problem very well suited to regular expressions.  Python's re
module has good documentation on regular expression syntax.

example:

- sumFile.py ---
import sys, re

if len(sys.argv)  2:
print 'Syntax: python sumFile.py filename'
sys.exit(1)
filename = sys.argv[1]

numexp = re.compile(r'\d+(?:\.\d+)?')  # Match one or more digits, optionaly
followed
   # by (a ., followed by one or more 
digits).
   # Note that .18 will be treated as
18, not
   # 0.18 (unless it really is 0.18 in
the text).

print 'Sum: ', sum(map(float, numexp.findall(file(filename).read(

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Major Newbie Here

2005-04-05 Thread jfouhy
Quoting Danny Yoo [EMAIL PROTECTED]:

 Try:
 
 ##
 class Spam:
  A meat for combining with other foods
  It can be used with other foods to make interesting meals.
  It comes with lots of nutrients and can be cooked using many
  different techniques
 
  def__init__(self):
  ## ... rest of code follows
 ##
 
 
 Tell us if this works out better for you.

Actually, that still won't work.

Firstly, because, as others have pointed out, there is a missing space between
the 'f' and the '_'.

But even then, if you do that at the interpreter, it won't work.

 class Spam:
...  A meat for combining with other foods
...  It can be used with other foods to make interesting meals.
...  It comes with lots of nutrients and can be cooked using many
...  different techniques
...
  def __init__(self):
  File stdin, line 1
def __init__(self):
^
SyntaxError: invalid syntax


The problem is that the interpreter will treat a blank line as the end of an
indented block.  If you want to define classes, functions, etc. in the
interactive interpreter, you have to do so without leaving any blank lines.

...which is another good reason to write things in scripts instead :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: building strings of specific length

2005-04-04 Thread jfouhy
Quoting Andrei [EMAIL PROTECTED]:

 You could do (I'll use 20 instead of 72 to keep it readable):
 
  s = %20s % xyz
  len(s), s
 (20, ' xyz')
 
 or:
 
  s = xyz
  s = s + (20 - len(s)) * ' '
  s, len(s)
 ('xyz ', 20)

Just a comment ---

You can do the second example using string formatting as well:

 s = '%-20s' % 'xyz'
 s, len(s)
('xyz ', 20)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Operator Overloading

2005-04-04 Thread jfouhy
Quoting Kevin Reeder [EMAIL PROTECTED]:

 On Mon, 04 Apr 2005 21:14:21 +1200
 John Fouhy [EMAIL PROTECTED] wrote:
  Are you sure you've giving us all the code?
 No, I was trying to keep it simple. Anyway, here it is,

Fine, but always test the simplified version, unless you're absolutely certain
what you're throwing out!

This is the key to your problem:
 
  def __getattr__(self, name):
  MyListSub.calls = MyListSub.calls + 1
  self.adds = self.adds + 1 
  return MyList.__getattr__(self, name)

When you do 'A + [4, 5, 6]', python first calls A.__getattr__('__coerce__').

__coerce__ appears to be used to implement mixed-mode arithmetic (eg, adding an
int to a float).  Presumably, you could define your own numeric types; if you
then defined __coerce__, you could add, mulitply, etc. your type with the
builtin types.

I guess the reasoning looks something like this:
  If both operands are the same, then call the appropriate __add__ method.
   Otherwise, look to see if either has a __coerce__ method.
  If so, try to use coerce to make them the same.
   Call the appropriate __add__ method.

I found this out by putting all your code into a file, and then using pdb.

ie: The file 'mylist.py' contains all your code, and ends with:


A = MyListSub([1,2,3])
print A.stats()
print len(A)
print A.stats()
print A + [4, 5, 6]
print A.stats()


I then run:  $ python /usr/lib/python2.4/pdb.py mylist.py

I put a break point on the line with 'A + [4, 5, 6]', and use the step command
to see what happens.  This immediately showed the call to __getattr__.

pdb is useful :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A Newbie Printing Question

2005-03-31 Thread jfouhy
Quoting Jacob S. [EMAIL PROTECTED]:

 Cool! Does anybody know of... I guess a rather *thorough* tutorial of
 win32? for the very reason that I don't know that this existed, and there may
 be other things I can use that I'm missing...

I don't know of anything online ... It seems a very poorly-documented corner of
Python.

Oreilly have a book which may be of help to you if you do a lot of programming
on Windows: http://www.oreilly.com/catalog/pythonwin32/

The only other thing I can suggest is try running pydoc on the win32 modules and
looking at the docstrings.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I am puzzled - help needed

2005-03-30 Thread jfouhy
Quoting John Carmona [EMAIL PROTECTED]:

 Hi John, thanks for the reply.

Hey John,

Please reply to the list, rather than to people directly.  Clicking reply to
all is probably what you want.
 
 Ok No. 1, I have read about ctime which convert a time expressed in 
 seconds since the epoch to a string representing local time

Nah, it's much, much simpler than that.

time.time just returns a floating point number.  How do you convert a number
into a string?
 
 No. 3 why do I need to convert them into an integer, if I manage to get
 the last 2 character this will be a whole number, no?

Programming languages differentiate between numbers and strings.  32 is a
number; you can do computations with it (add, multply, etc).  32 is a string;
this means it is the character 3 followed by the character 2.  Python (and
most other programming languages) treats them very differently.

example:

 x = 32
 x + 1
33
 x * 3 / 4
24
 s = 32
 s + 1
'321'
 s + foo
'32foo'

You have to decide what you need.  Your program compars numbers with the answer
(your random number).  In order to do this comparison, you need to have your
answer as a number, not as a string.

Hope this helps.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: hash issues [WAS] Re: [Tutor] hash()ing a list

2005-03-29 Thread jfouhy
Quoting Brian van den Broek [EMAIL PROTECTED]:

 I had thought lookup was by hash value, and thus expected the access 
 to some_dict to cause troubles. Yet it worked. Is it that lookup is by 
 hash value, and then equality if need be so as to settle ambiguity, or 
 have I completely misunderstood the mechanism of dictionary lookup?

Hash functions are rarely perfect (in terms of mapping every input to a
different output) [1], so they have to deal with collisions.

AFAIK, the hash table lookup algorithm basically works like this:

def lookup(self, key):
hits = self.internalDataStructure[key]
for key_, value in hits:
if key_ == key:
return value
raise KeyError, 'Key not found'.

(except that it will be written in C and there may be advanced trickery involved
to improve efficiency in other ways)

HTH!

[1] The pigeonhole principle [2] tells us that it is rarely possible to make
perfect hash functions.  For example, there are more possible strings than there
are integers [3,4], so, in principle, you could find arbitrarily many strings
all with the same hash value.  In that case, a dictionary with them as keys
would be O(n), not O(1).  But a good hash function will make that very unlikely.
[2] http://en.wikipedia.org/wiki/Pigeonhole_principle
[3] Because every integer n has a corresponding string n, but there are
strings which do not (directly) correspond to an integer (eg, foo).
[4] Unless we allow integers to go to infinity... But computers generally do not
have infinite memory :-)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Launching a file browser

2005-03-28 Thread jfouhy
Quoting Mike Hall [EMAIL PROTECTED]:

 I get the impression some of these Mac modules are more relevant to 
 os 9 than 10(which is Unix), so maybe EasyDialogs is not the right 
 choice here. Any suggestions are appreciated.

So, you are writing a GUI app and you want some kind of open file dialog?  Won't
this depend on what toolkit you are using for your GUI?

If you are using Tkinter (which should work on OS X, I think), try:

 import tkFileDialog
 f = tkFileDialog.askopenfilename()

Check dir(tkFileDialog) for other functions.

But other GUI toolkits will have their own functions.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] commands with multiple things to do?

2005-03-28 Thread jfouhy
Quoting Diana Hawksworth [EMAIL PROTECTED]:

 Is it possible for me to make a command do multiple things instead of
 1?

Not directly ... But you can always write a function that does both things.

  self.submit_bttn = Button(self, text = Tries: 0, command =
 self.reveal, self.update_count)

eg:

def callback():
self.reveal()
self.update_count()
self.submit_bttn = Button(self, text='Tries: 0', command=callback)

In python, function definitions can be placed anywhere (including inside other
functions).

HTH.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Passing data from html to py

2005-03-23 Thread jfouhy
Quoting Vicki Stanfield [EMAIL PROTECTED]:

 I need something more like this:
 
 First Name: Vicki
 Last Name: Stanfield
 etc.

Instead of just printing form, try this:

for key in form:
print '%s: %s' % (key, form[key].value)

Basically, a FieldStorage object is organised as a dictionary, where the keys
are the names of the HTML form elements, and the values are MiniFieldStorage
objects.  To get the actual form data, you look at the .value attribute.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Passing data from html to py

2005-03-23 Thread jfouhy
Quoting Vicki Stanfield [EMAIL PROTECTED]:

  for key in form:
  print '%s: %s' % (key, form[key].value)
 Thanks John,
 That is exactly what I was looking for. I would like to add a newline
 after each line. I tried adding a \n after the second %s, but that
 doesn't seem to work. But wait, it works interactively. Any idea why it might
 not work in this script.
 
 for key in form:
  print '%s: %s/n/n' % (key, form[key].value)

Hi Vicki ---

Two things:

Firstly, a there is a difference between /n and \n :-)

Secondly, remember that all whitespace (including newlines) in HTML is collapsed
down to a single space.

The newlines will be there, but your web browser is just ignoring them.  A quick
fix is something like '%s: %sbr' % (key, form[key].value).

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I need some guidance

2005-03-23 Thread jfouhy
Quoting John Carmona [EMAIL PROTECTED]:

 Second question: As i am not, unfortunately, involved professionaly in
 the field of programming is there a specific technique to learn other than
 just read everything I put my hand on?

Reading is fine, but you really need to be writing code to cement your
knowledge.  I find it very helpful if I have a projcet of some kind to work on
if I'm learning something new.  Which leads on to ---

 Third question: Does anybody know if it is possible to get involved in
 this field in a non-lucrative kind of way in order to learn faster and of
 course to apply this science in a real world.

Well, look around yourself.  Is there anything that you do which might benefit
from some basic programming?

For example, I play ultimate frisbee.  So my learn python project was to
create a CGI system for handling the ultimate leagues here in Wellington
(displaying this week's games, recording scores, calculating leaderboards, etc).

The code I produced is not a model for anyone on this list to look at, but it
did get me into the language :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   >