Re: [Tutor] Code Readability (was: Recursion and List Comprehensions)

2005-10-29 Thread Andrew P
Since when is elegance a dirty word?

Elegance is the soul of good programming.   A simple and graceful
solution to the widest number of cases, efficient and easy to
understand in application.  Sometimes subtle, but always beautiful.

In language design, software architecture, algorithms, it is the
rushing light of clarity that banishes dark and smelly corners.  It's
side effects are many--reusable code, effortless speed, painless
maintenance, reduced complexity.

The dreams shared by physicists, mathematicians, and engineers, are
dreams of elegance.

It is heartbreaking to see a concise and useful term maligned by dense
one-liners, which are seldom anything except hard to read.  Simple and
short ain't the same thing.

And having indulged in possibly very off-topic interlude, let me point
out that recognizing a donut when you see it, doesn't make you a
baker.  Trust me,  I'm not baking donuts.

And judging by the amount of Escher-like pretzels that continute to be
baked in the world,  we have a long ways to go before we get more than
the occasional sighting or passing whiff of something sweet and round
with a hole in the middle. .

Take care,

Andrew

On 10/28/05, Carroll, Barry <[EMAIL PROTECTED]> wrote:
> Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> <>
>
> >>PS Don't get too crazy about eliminating intermediate variables, they can
> >>make the code more readable.
> >>
> >>Kent
>
> I agree.  When writing for keeps (i.e. production code) I prefer clarity and
> ease of maintenance over 'elegance' or 'trickiness'.  This exercise is
> intended, in part, to sharpen my understanding of Python idioms.  If I can
> write highly idiomatic code that works,  chances are better that I will be
> able to decipher it when I come across it elsewhere.
>
> Barry
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Tkinter

2005-10-29 Thread Shi Mu
When I run the following code,
script kept running and I have to force it to stop.
Could you check the code to give suggestions how to improve it?
Thanks a lot!

from Tkinter import *
from Tkinter import _cnfmerge

class Dialog(Widget):
  def __init__(self, master=None, cnf={}, **kw):
  cnf = _cnfmerge((cnf, kw))
  self.widgetName = '__dialog__'
  Widget._setup(self, master, cnf)
  self.num = self.tk.getint(
  apply(self.tk.call,
('tk_dialog', self._w,
 cnf['title'], cnf['text'],
 cnf['bitmap'], cnf['default'])
+ cnf['strings']))
  try: Widget.destroy(self)
  except TclError: pass
  def destroy(self): pass

if __name__ == '__main__':

  q = Button(None, {'text': 'How are you',
Pack: {}})
  b1 = Listbox()
  b1.pack()

  c1 = Checkbutton(text="Check")
  c1.pack()

  q.mainloop()

from Tkinter import *
root =Tk()
menu=Menu(root)
root.config(menu=menu)
filemenu=Menu(menu)
menu.add_cascade(label="Test", menu=filemenu)
filemenu.add_command(label="Just Try")
filemenu.add_separator()
mainloop()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter

2005-10-29 Thread Liam Clarke
What kind of improvement you looking for?

On 10/29/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> When I run the following code,
> script kept running and I have to force it to stop.
> Could you check the code to give suggestions how to improve it?
> Thanks a lot!
>
> from Tkinter import *
> from Tkinter import _cnfmerge
>
> class Dialog(Widget):
>   def __init__(self, master=None, cnf={}, **kw):
>   cnf = _cnfmerge((cnf, kw))
>   self.widgetName = '__dialog__'
>   Widget._setup(self, master, cnf)
>   self.num = self.tk.getint(
>   apply(self.tk.call,
> ('tk_dialog', self._w,
>  cnf['title'], cnf['text'],
>  cnf['bitmap'], cnf['default'])
> + cnf['strings']))
>   try: Widget.destroy(self)
>   except TclError: pass
>   def destroy(self): pass
>
> if __name__ == '__main__':
>
>   q = Button(None, {'text': 'How are you',
> Pack: {}})
>   b1 = Listbox()
>   b1.pack()
>
>   c1 = Checkbutton(text="Check")
>   c1.pack()
>
>   q.mainloop()
>
> from Tkinter import *
> root =Tk()
> menu=Menu(root)
> root.config(menu=menu)
> filemenu=Menu(menu)
> menu.add_cascade(label="Test", menu=filemenu)
> filemenu.add_command(label="Just Try")
> filemenu.add_separator()
> mainloop()
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter

2005-10-29 Thread Shi Mu
move the bottom codes to the top and try to make
the codes following if __name__ == '__main__':
as few as possible.
also,
i want the main menu come first, and after clicking test/just try, i
can go to the "how are you" interface.

On 10/29/05, Liam Clarke <[EMAIL PROTECTED]> wrote:
> What kind of improvement you looking for?
>
> On 10/29/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> > When I run the following code,
> > script kept running and I have to force it to stop.
> > Could you check the code to give suggestions how to improve it?
> > Thanks a lot!
> >
> > from Tkinter import *
> > from Tkinter import _cnfmerge
> >
> > class Dialog(Widget):
> >   def __init__(self, master=None, cnf={}, **kw):
> >   cnf = _cnfmerge((cnf, kw))
> >   self.widgetName = '__dialog__'
> >   Widget._setup(self, master, cnf)
> >   self.num = self.tk.getint(
> >   apply(self.tk.call,
> > ('tk_dialog', self._w,
> >  cnf['title'], cnf['text'],
> >  cnf['bitmap'], cnf['default'])
> > + cnf['strings']))
> >   try: Widget.destroy(self)
> >   except TclError: pass
> >   def destroy(self): pass
> >
> > if __name__ == '__main__':
> >
> >   q = Button(None, {'text': 'How are you',
> > Pack: {}})
> >   b1 = Listbox()
> >   b1.pack()
> >
> >   c1 = Checkbutton(text="Check")
> >   c1.pack()
> >
> >   q.mainloop()
> >
> > from Tkinter import *
> > root =Tk()
> > menu=Menu(root)
> > root.config(menu=menu)
> > filemenu=Menu(menu)
> > menu.add_cascade(label="Test", menu=filemenu)
> > filemenu.add_command(label="Just Try")
> > filemenu.add_separator()
> > mainloop()
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] threaded chat server, is this the way?

2005-10-29 Thread Christian Eskebjerg
Hi,

Im trying to write a threaded chat server, building on examples given in 
  the book "Python Network Programming", chapter 21.

I have managed to come up with af working (so it seems) solution, see 
code below.

My question is: What is wrong with this aproach?
I put each new connection in a common dict, and when i recieve a message 
i loop the dict and send the message to each connection (except the sender).

In the book I'm told I have to a semaphore and a queue for each 
connection. What would I achieve by doing this, and how would i go about it?

Thanks
Christian



My code looks like this:
--

# -*- coding: latin_1 -*-

# original: Echo Server with Threading - Chapter 21 - echoserver.py, 
Python Network programming


import socket, traceback, os, sys
from threading import *
import time

host = ''   # Bind to all interfaces
port = 1

def handleclient(clientsock, connectionsDic):
 print "New child", currentThread().getName()
 print "Got connection from", clientsock.getpeername()
 #assign a name to this connection and put it in connectionsDic
 name = currentThread().getName()
 connectionsDic[name]=clientsock
 buffer = ""
 try:
 while 1:
 input = clientsock.recv(4096)
 if not len(input):
 break
 buffer += input
 if "\n" in buffer:
 #todo: check that \n is actually the end of buffer
 data = buffer
 buffer =""
 for connName in connectionsDic.keys():
 message = "%s says: %s"%(name, data)
 try:
 if connName!=name:
 connectionsDic[connName].sendall(message)
 else:
 connectionsDic[connName].sendall("Your 
message has been passed on\n\r")
 except:
 pass
 finally:
 # Close the connection
 clientsock.close()
 del connectionsDic[name]
 print name, " says goodbye.."

# Set up the socket.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)
#Dict to keep track og connections
connectionsDic = {}
while 1:
 try:
 clientsock, clientaddr = s.accept()
 except KeyboardInterrupt:
 raise
 except:
 traceback.print_exc()
 continue

 t = Thread(target = handleclient, args = [clientsock, connectionsDic])
 t.setDaemon(1)
 t.start()
---

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


[Tutor] Nokia 60 series

2005-10-29 Thread Matt Williams
There's some extra info here:

http://comments.gmane.org/gmane.comp.python.announce/5658

HTH,
Matt
-- 
Dr. M. Williams MRCP(UK)
Clinical Research Fellow
Cancer Research UK
+44 (0)207 269 2953
+44 (0)7834 899570
http://acl.icnet.uk/~mw
http://adhominem.blogspot.com

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


Re: [Tutor] Tkinter

2005-10-29 Thread Alan Gauld
> When I run the following code,
> script kept running and I have to force it to stop.

Yep. Thats usually what happens when you run a GUI program.
What did you expect it to do?

> Could you check the code to give suggestions how to improve it?

I'll add some comments but its not clear what you are trying to do.
Some general points first:

1) You should only have one call to mainloop() in a Tkinter program.
2) Its bad practice to have code after the "if name==main " block.
That code gets exercised as well as the if block - very confusing!

Specific comments:

class Dialog(Widget):
  def __init__(self, master=None, cnf={}, **kw):
  cnf = _cnfmerge((cnf, kw))
  self.widgetName = '__dialog__'

AG> Looks a bit weird. Names starting with underscores usually mean private
AG> and __xxx___ style names are usually private to Python itself... But 
those are
AG> merely conventions, but useful ones...

  Widget._setup(self, master, cnf)

AG> Are you sure you don't want to call Widget.__init__ first?

  self.num = self.tk.getint(
  apply(self.tk.call,
('tk_dialog', self._w,
 cnf['title'], cnf['text'],
 cnf['bitmap'], cnf['default'])
+ cnf['strings']))

AG> I have no idea whats going on here! Can you explain?

  try: Widget.destroy(self)
  except TclError: pass

AG> And having constructed the Widget subclass you now destroy it?
AG> I'm very confused.

   def destroy(self): pass

AG> except destroy doesn't do anything...

if __name__ == '__main__':
  q = Button(None, {'text': 'How are you',
Pack: {}})

AG> This is a very old fashioned way of configuring a Tkinter widget
AG> and suggests you have been looking at a very old Tkinter tutorial.

q = Button(None, text="How are you")
q.pack()

AG> would be more common.

  b1 = Listbox()
  b1.pack()

  c1 = Checkbutton(text="Check")
  c1.pack()

  q.mainloop()

AG> So you set the mainlop running here and wait for events.
AG> But you haven't defined any event handlers anywhere
AG> let alone connected them to your widgets. The only things
AG> that will work are the default window widgets

from Tkinter import *

AG> You've already done this up top

root =Tk()
menu=Menu(root)
root.config(menu=menu)
filemenu=Menu(menu)
menu.add_cascade(label="Test", menu=filemenu)
filemenu.add_command(label="Just Try")
filemenu.add_separator()

AG:> And this all looks a bit confused too, I'm not sure what
AG> you are trying to achieve here?

mainloop()

AG> And you already called mainloop above, although this mainlop isn't
AG> defined anyplace that I can see, its nopt attached to an object of
AG> any kind...

I think you need to clarify in your mind what you are trying to achieve
and restructure the code to reflect that. As it is its not clear what 
exactly
you think the code should do.

Can you simplify it? Just get a basic window/menu combination set up
and working, then once thats fixed fold the config stuff in later?

Also I'd make sure you check out the latest Tkinter tutorial, all that
configuration by dictionary stuff was deprecated about 7 years ago!

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld






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


[Tutor] OS X 10.4 and MySQL for Python

2005-10-29 Thread Eddie S
I was just about to attempt to install the python mysql package
(http://sourceforge.net/projects/mysql-python/). I just wanted to know
if anyone has attempted this on OS X 10.4. Searching the list it is
very possible on past versions of os x no one seems to have commented
on the latest version though.

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


Re: [Tutor] Global var problem

2005-10-29 Thread Nick Lunt
Alan Gauld wrote:

>> messing about with classes I've come across something basic that I 
>> don't understand.
>
>
> As you say this has nothing to do with classes its more basic. Its 
> about namespaces. Try reading the namespaces topic in my tutor for 
> more info.
>
> Meanwhile lets simplify by removing the class bit
>  
>
> def h():
>   global x
>   x += 1
>  print x
>
> h()   # prints 43


Many thanks to Alan, Andrei, Hugo and Welsey for helping me to 
understand where I was going wrong.
I thought I understood namespaces but _obviously_ not .

Thanks again,
Nick .

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


Re: [Tutor] Can anyone help me?

2005-10-29 Thread Nick.Pomponio
Title: Message



The "odds" are determined by the number of favorable 
outcomes to the number of unfavorable outcomes. In the case of flipping a 
coin, the odds are 1/1 (sometimes written as 1:1) for heads. The 
_probability_ of an event (as per a "frequency" definition) is the number of 
favorable outcomes that cause the event to occur to the total number of 
outcomes (assuming a uniform distribution). For flipping a coin, the probability 
of heads would be 1/2.
 
Whether or not the total number of tickets sold impacts 
your probability of winning depends on the way that the lottery is conducted. 
Here in Georgia, I believe that the winning lottery sequence is drawn 
from all possile sequences, not from the restricted set of those sequences from 
sold tickets only. In the former case, the probability of winning is dependent 
only on the number of tickets you purchase. In the latter case (or a similar 
case in which winning sequences were generated until someone won), the number of 
other tickets sold would affect your chances of winning.
 
-Nick 
Pomponio


From: [EMAIL PROTECTED] 
[mailto:[EMAIL PROTECTED] On Behalf Of Smith, 
JeffSent: Friday, October 28, 2005 11:08 AMTo: bob; 
Tutor@python.orgSubject: Re: [Tutor] Can anyone help 
me?

But 
the odds that you will win are not impacted by the number of tickets that 
are sold in total...only the number you buy.  When you take into account 
the total number of tickets sold, all you get are the odds that the lottery will 
be won by anyone.
 
I'm 
also a little confused by that def of odds.  Consider flipping a 
coin.  The probability that it will come up heads is 1/2.  That def 
says that the odds in favor of it coming up heads is 1.
 
Jeff
 

  
  -Original Message-From: bob 
  [mailto:[EMAIL PROTECTED] Sent: Friday, October 28, 2005 10:52 
  AMTo: Smith, Jeff; Tutor@python.orgSubject: Re: [Tutor] 
  Can anyone help me?At 07:28 AM 10/28/2005, Smith, Jeff 
  wrote:
  Aren't the odds just based on how 
many tickets you buy?  The odds aren'taffected by different people 
buying more tickets.  If only one personbuys a ticket in the entire 
lottery system, his odds of winning are thesame as if two people play, 
and the same as if 20 million play.According to the 
  wikipedia: "In probability theory 
  and statistics the 
  odds in favor of an event or a proposition are the quantity p / 
  (1-p), where p is the probability of the event 
  or proposition." If you assign equal probability of winning to each ticket 
  then odds are how many tickets you buy relative to how many tickets everyone 
  else has bought. The probability of a ticket winning is 1 / 
  m**n where m is the highest number possible and n is the number of numbers. If 
  a lottery uses 6 numbers each in the range 1..42 then the probability of a 
  ticket winning is 1/5489031744. All of this is mathematics. Sometimes 
  one or more tickets win. Is that "luck"? 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Real newbie - python can't open spam.py

2005-10-29 Thread Michael Rowan
Hi

I'm on my first day with python2.3 on Windows XP.  I'm able to run 
python interactively.

I've created a text file using NotePad, named it spam.py (as per 
O'REILLY Learning Python, p13)  contents as folows

import sys
print sys.argv

If I do:

 >python spam.py

it says can't open file 'spam.py'

Anyone know why?  I can open the file in NotePad without problem.

Thanks

Mike

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


Re: [Tutor] Real newbie - python can't open spam.py

2005-10-29 Thread Kent Johnson
Michael Rowan wrote:
> Hi
> 
> I'm on my first day with python2.3 on Windows XP.  I'm able to run 
> python interactively.
> 
> I've created a text file using NotePad, named it spam.py. If I do:
> 
>  >python spam.py
> 
> it says can't open file 'spam.py'
> 
> Anyone know why?  I can open the file in NotePad without problem.

Is spam.py in the current directory when you type the command? If not, cd to 
the directory containing spam.py. What is the exact error message you get?

Kent

-- 
http://www.kentsjohnson.com

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


Re: [Tutor] IDLE error msgs and line continuations?

2005-10-29 Thread Danny Yoo


On Thu, 27 Oct 2005, CPIM Ronin wrote:

> When using IDLE, after hitting F5 to save and run, if an error occurs,
> it merely flashes at the code location of the error. While I usually
> figure out what is wrong, why don't I get the detailed text error
> messages that the command line gives?
>
> Also, I'm getting most error messages when I try line continuation for
> clarity:
>
>  if (condition 123 and
>  condition 456):

Hi RC,

It might be the case that 'condition 123' is malformed.  If this is true,
then the problem doesn't stem from going across lines, but with the
'condition 123' and 'condition 456' stuff.

Just to check:

##
>>> if (condition 123 and
  File "", line 1
if (condition 123 and
^
SyntaxError: invalid syntax
##

Yeah, looks like Python immediately seizes on that part and stops at the
point where the SyntaxError is.  It doesn't even wait for me to enter in
the rest of the line.

I'm not sure if this is the real error that you're seeing; you may have
just used 'condition 123' simply as an example.  If you have code that you
can show us, we'll look at it more carefully.


Best of wishes to you!

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


[Tutor] Birthday paradox (was: Re: Random number generator (was: Can anyone help me?))

2005-10-29 Thread Danny Yoo


On Fri, 28 Oct 2005, Johan Geldenhuys wrote:

> After I tested the previous code, I noticed that the odds is 1:49 that a
> duplicate number can be found in the 6 digit range (and it happended)
> and that 0 can also be found.

Hi Johan,

I'm not exactly sure how 1 in 49 are the odds of getting a duplication.
Let's talk about this for a moment.

[Warning: long post ahead.]


Just to make sure: the situation is that we're rolling a fifty-sided dice
six times, and we'd like to see what's the probability of having
duplicates in the mix.  We have 50**6 possible rolls, but there are only:

50 * 49 * 48 * 47 * 46 * 45

ways of making sure we don't hit duplicates.  The probability that we
don't hit any duplicates, then, is:

##
>>> (50 * 49 * 48 * 47 * 46 * 45) / (50 **6)
0L
#

Oops, forgot about integer division.  *grin*


Let me try that again:

##
>>> (50.0 * 49 * 48 * 47 * 46 * 45) / (50 **6)
0.7322434559996
##

Ok, so we have about a 73% chance of not having any duplicate numbers if
we roll a 50-digit dice six times.


Since we can either have no duplication or duplication, then he
probability that we will have duplication is:

(1 - probability of not having duplication)

##
>>> 1 - (50.0 * 49 * 48 * 47 * 46 * 45) / (50 **6)
0.2677565440004
##


So we have about a 27% percent chance of getting duplication when we roll
a fifty sided dice six times.


But that's just probability theory.  Is this real?  Is this truly
probable?

Let's test this experimentally.  First, we need some way of generating a
roll of dice.  Here's a quick-and-dirty function to do that:

##
>>> def make_roll(n, r):
... return [random.randrange(n) for i in range(r)]
...
>>> make_roll(50, 6)
[11, 48, 39, 43, 30, 24]
>>> make_roll(50, 6)
[6, 47, 0, 34, 9, 38]
##


We can test things experimentally by writing a function to see a roll has
duplication:

##
>>> def has_duplication(roll):
... d = {}
... for number in roll:
... d[number] = d.get(number, 0) + 1
... for count in d.values():
... if count > 1:
... return True
... return False
...
>>> has_duplication([1, 2, 3])
False
>>> has_duplication([1, 2, 2])
True
##


Once we have this tool, then it becomes easy to do a trial run and see, if
we roll 10 times, what percentage of those are duplicates.

##
>>> count_duplicates = 0
>>> for i in range(10):
... if has_duplication(make_roll(50, 6)):
... count_duplicates = count_duplicates + 1
...
>>> count_duplicates
1
>>> 1.0 / 10
0.10001
##


Experimentally, we're seeing 1%, but that might just be a fluke.  Or maybe
it's just because the trial size is much too small.  *grin*


Let's formalize this test as a function, just to make it easier to retry:

##
>>> def do_trial(n):
... """Returns the number of duplicates if we do a n-trial."""
... count_duplicates = 0
... for i in range(n):
... if has_duplication(make_roll(50, 6)):
... count_duplicates = count_duplicates + 1
... return float(count_duplicates) / n
...
>>>
>>> do_trial(5)
0.40002
>>> do_trial(10)
0.2
>>> do_trial(100)
0.27002
>>> do_trial(1000)
0.26902
>>> do_trial(1)
0.2621
>>> do_trial(10)
0.26676
##

So we're experimentally getting evidence that the probability of rolling
duplicates is about 26%, if we have a 50-sided dice six times.  Hey,
that's not bad: that's about the value we got from doing math.

As we scale our expeiment higher, we start seeing the Law of Large Numbers
taking place: when we use lots of trials, then our experimental results
start getting very close to the one we calculated with probability theory.

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


Here's a punchline: the problem we've been looking at is another disguise
for the Birthday Paradox:

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

That article makes the assertion that if we have 23 people in a room, the
probability that we have at least two people with the same birthday is
pretty good (about 50%).  We can modify do_trial()  to experimentally see
that!

##
>>> def do_trial(n, x, y):
... """Returns the number of duplicates if we do a n-trial."""
... count_duplicates = 0
... for i in range(n):
... if has_duplication(make_roll(x, y)):
... count_duplicates = count_duplicates + 1
... return float(count_duplicates) / n
...
>>> do_trial(1, 365, 23)
0.51392
>>> do_trial(1, 365, 1)
0.0
>>> do_trial(1, 365, 2)
0.0023
>>> for i in range(23):
... print i, "people, probability of shared birthday:",
do_trial(1, 365, i)
...
0 people, probability of shared birthday: 0.0
1 people, probability of shared birthday: 0.0
2 people, probability of shared birthday: 0.0035
3 people, probability of shared birthday: 0.0087
4 people, probability of shared birthday: 0.0181
5 people, probability of shared birthday: 0.0273

Re: [Tutor] Birthday paradox (was: Re: Random number generator (was: Can anyone help me?))

2005-10-29 Thread Danny Yoo

> ##
> >>> count_duplicates = 0
> >>> for i in range(10):
> ... if has_duplication(make_roll(50, 6)):
> ... count_duplicates = count_duplicates + 1
> ...
> >>> count_duplicates
> 1
> >>> 1.0 / 10
> 0.10001
> ##
>
>
> Experimentally, we're seeing 1%, but that might just be a fluke.  Or maybe
> it's just because the trial size is much too small.  *grin*


Gaaa.  I can't add or subtract.  I meant:

Experimentally, we're seeing 10%, but that might just be a fluke.  Or
maybe it's just because the trial size is much too small.



> >>> def do_trial(n):
> ... """Returns the number of duplicates if we do a n-trial."""
> ... count_duplicates = 0
> ... for i in range(n):
> ... if has_duplication(make_roll(50, 6)):
> ... count_duplicates = count_duplicates + 1
> ... return float(count_duplicates) / n

The comment is wrong.  It should be:

 """Returns the probability of duplicates if we do an n-trial."""




> The variable names 'x' and 'y' suck (I'll try to think of better ones next
> time), but I hope that it's clear what we're doing: we're making
> do_trial() more general so it can handle different dice rolls.  And
> because they are parameters in our do_trial() function, we can then see
> what the situation loosk like as we get more and more kids in the
 ^

Looks, not loosks.


Sorry about that!


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


Re: [Tutor] Python as Application (OT now)

2005-10-29 Thread Lee Harr
Sorry about misposting this here. I always mix up the
tutor@ and edu-sig@ lists. I am just going to follow
up two things that seem tutor related.

If this seems interesting, you may want to join the
edu-sig  list for more...


>>More frightening to me than the ubiquitous use of MS Office is the
>>omnipresence of windows. Every time a student sits down in front
>>of KDE in our lab and says "Where is the internet?" I can only cringe.


>I do wonder why you cringe. Educate the user. He is expecting his
>usual metaphor, and it's not there. The majority of the world has it,
>remember, so he expects you to as well.
>


Certainly. I guess I should have said "I have to cringe" instead of
"...only cringe". I don't just walk away and leave people wondering
why it is impossible to do what they want to do.

As for why ... I guess I just see internet explorer (and windows) as
so limiting, that I cannot understand why this is what we are
teaching.

How do children reach high school without knowing what the
internet is, and that it is not the blue "e"?


>I've never worked in any workplace where anything else other than
>Excel was used.

>You can't really separate spreadsheet from Excel, or word processing
>from Word, in the general public's view.


Well. I've never worked anyplace where excel was used for anything
other than a badly designed database. Someone must be teaching
people that is what it is for. ("Formula? What is a formula?")

I also get all kinds of odd documents in my lab. People have no idea
what file formats are and are (understandably) upset when they
cannot print out their papers. And yes, we do have a computer
running windows with office, and we still get strange microsoft
documents that are unopenable.

Papers are generally poorly formatted. Things like using the space
bar or tab key to center things. Then even when the docs do open
up, the formatting is all askew.

Perhaps if teachers thought more about the _abstraction_ of a word
processor and the _abstraction_ of a spreadsheet, and focused on
how these tools are best used  --  instead of focusing on how to
use the specific implementations -- we would have fewer problems,
and more capable students.

To me, programming is all about abstraction.


Thanks for your time.
(please follow up to edu-sig)

_
Express yourself instantly with MSN Messenger! Download today it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

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


Re: [Tutor] Code Readability (was: Recursion and List Comprehensions)

2005-10-29 Thread Danny Yoo

> > I agree.  When writing for keeps (i.e. production code) I prefer
> > clarity and ease of maintenance over 'elegance' or 'trickiness'.
> > This exercise is intended, in part, to sharpen my understanding of
> > Python idioms.  If I can write highly idiomatic code that works,
> > chances are better that I will be able to decipher it when I come
> > across it elsewhere.

> Since when is elegance a dirty word?

It's not.  But there are tradeoffs.  As a concrete example, we can take a
look at Bram Cohen's fairly recent request for a pure-Python suffix tree
implmementation:

http://www.livejournal.com/users/bramcohen/22069.html

He's specifically requesting for an implementation for a data structure
algorithm that is easy to maintain, and he's willing to sacrifice the
elegant optimal solution!  But that's because he wants to make sure he can
understand the code later on.

I'm not sure I agree with Bram --- the "Ukkonen" algorithm for building
suffix trees isn't bad, and I can probably cook it up if I'm careful ---
but I can see why he values a simple implementation.

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


Re: [Tutor] Code Readability (was: Recursion and List Comprehensions)

2005-10-29 Thread Andrew P
Sorry.  *blush*  That was some late Friday night craziness.  I just
looked at the code being discussed:

retList=[word[pos]+item for item in permute3(word[0:pos]+word[pos+1:])]

And really didn't want to anybody to confuse that with Python's idea
of elegance.

List comprehensions can get pretty horrible when combined with nested
functions and/or slices and/or multiple implicit loops.  One of the
few areas where Python can get really twisted.

That's a great point, Danny. For me, elegance is an admirable goal
under any circumstance, but includes all the aspects I listed. 
Effeciency -and- understandability.  Throw it under the umbrella of
"graceful" :)

The tools we use are far from perfect, and there are still plenty of
"aha!" moments to go around.  In the real world the fast and ugly
usually go hand in hand.  I'm an optimist, tho.

Anyway, sorry to go so far off topic.  Oh, and by the way, I loved
'The Psychology of Programming'.  That was a really entertaining book,
and thanks again for recommending it.

Andrew

On 10/29/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
>
> > > I agree.  When writing for keeps (i.e. production code) I prefer
> > > clarity and ease of maintenance over 'elegance' or 'trickiness'.
> > > This exercise is intended, in part, to sharpen my understanding of
> > > Python idioms.  If I can write highly idiomatic code that works,
> > > chances are better that I will be able to decipher it when I come
> > > across it elsewhere.
>
> > Since when is elegance a dirty word?
>
> It's not.  But there are tradeoffs.  As a concrete example, we can take a
> look at Bram Cohen's fairly recent request for a pure-Python suffix tree
> implmementation:
>
> http://www.livejournal.com/users/bramcohen/22069.html
>
> He's specifically requesting for an implementation for a data structure
> algorithm that is easy to maintain, and he's willing to sacrifice the
> elegant optimal solution!  But that's because he wants to make sure he can
> understand
> I'm not sure I agree with Bram --- the "Ukkonen" algorithm for building
> suffix trees isn't bad, and I can probably cook it up if I'm careful ---
> but I can see why he values a simple implementation.
>
>
d the code later on.
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor