[Tutor] Urgent: Help

2008-01-07 Thread Shumail Siddiqui
Dear tutor, 
   I have a question regarding a functions based assignment. The assignment 
is:
  For this project, you will write two small Python programs: 
  

   Investment Thresholds   

  Define a Python function threshold(dailyGains, goal) that behaves as 
follows. The first parameter is a list of integers that represent the daily 
gains in the value of a stock. The second paramter is a single positive number 
that is a profit goal. The function should return the minimum number of days 
for which the stock should be owned in order to achieve a profit that is equal 
to or greater than the stated goal. If the goal is unreachable, the function 
should return 0.   
For example,   
threshold ([5, 3, 8, 2, 9, 1], 17)   
should return 4 because the goal (17) can be reached after the first four days 
(e.g., 5 + 3 + 8 + 2).   
  
  Write a small Python program that uses your threshold() function to 
demonstrate that it works correctly. Your program may use a pre-defined list of 
stock gains or it may generate one randomly (see the "Helpful Hints" section 
below for tips on how to do this). Your program should display this list, 
prompt the user to enter a profit goal, and then print out the total number of 
days required to reach that goal (or a message stating that the goal is 
impossible).   

  
  
   Word Windows   

  Define a Python function sliding(word, num) that behaves as follows. It 
should print out each num-length slice of the original word , aligned 
vertically as shown below.   
For example, a call to sliding("examples", 4) should produce the output   

exam   xampampl mple  ples  
  
  
  Write a small Python program to demonstrate that your sliding() function 
works correctly. Your program should prompt the user to enter a word and a 
window size, and then call sliding() with those values.   


  
  Helpful Hints  
   Python contains a set of facilities to handle random number generation. Full 
details are available at http://docs.python.org/lib/module-random.html. A quick 
summary is as follows:   

  Add the statement   
import random   
at the beginning of your program source code. This tells Python where to find 
the code that describes how to generate random values.   
  
  Pass your list of values to the random.choice() function. The function 
will return a single randomly-selected element from that list.   
For example, random.choice(range(5)) will return a random value in the range 
0-4.   
Please note that "random" does not necessarily mean "unique"; sequential calls 
to this function may return the same answer, because it is randomly chosen each 
time! 


  This is what I have so far:
   
  import random
dailyGains = int(random.range(6))
goal = random.choice(range(4)
result = []
def threshold(dailyGains, goal):
  if goal!= result: 0
  else:
result.reverse()
result.remove()
   
  As you can see I am having a great problem.


   
-
Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it now.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Program review

2008-01-07 Thread Kent Johnson
Jeff Younker wrote:

> Or if you're using python 2.5 then you can use with statements:
> 
> from __future__ import with_statements
> from contextlib import closing
> ...
> def mails(self):
> with closing(open_file(self.direcciones)) as fIncl:
>with closing(open_file(self.excluidas)) as fExcl:

closing() is not needed, this can be written as
 with open_file(self.direcciones) as fIncl:
with open_file(self.excluidas) as fExcl:

because open files are context managers.
Or,
from contextlib import nested
 with nested(open_file(self.direcciones), open_file(self.excluidas)) 
as (fIncl, fExcl):

> As you have it written it terminates, but it also silently consumes the
> exception.  If something goes wrong with your program then there is
> no way of diagnosing the problem because the failure cause is never
> reported.

The exception is written to the log. He may not want the traceback 
printed to the console.

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


Re: [Tutor] Urgent: Help

2008-01-07 Thread Alan Gauld
"Shumail Siddiqui" <[EMAIL PROTECTED]> wrote

>   I have a question regarding a functions based assignment. The 
> assignment is:
>  For this project, you will write two small Python programs:
>

OK, Since this is for homework I cannot give you the answers
but I will point out some things you shouild look at and an approach.


>   Investment Thresholds
>
>  Define a Python function threshold(dailyGains, goal) that 
> behaves as follows.

First define the function and test it using the >>> prompt.

>  Write a small Python program that uses your threshold() 
> function
> to demonstrate that it works correctly. Your program may use a
> pre-defined list of stock gains or it may generate one randomly

Use a predefined list initially, it's easier!
Only once that works try introducing random elements.

>   Word Windows

One problem at a time...

>  This is what I have so far:
>
>  import random
> dailyGains = int(random.range(6))
> goal = random.choice(range(4)

missing parenthesis, I assume a typo?

> result = []
> def threshold(dailyGains, goal):
>  if goal!= result: 0
>  else:
>result.reverse()
>result.remove()

you need to investigate the return statement in functions.

However I don;t understand how you think this will
achieve anything like what the original specification
asked for. You need to use the dailyGains list
somewhere... And why you are checking against
result I don't know.

Can you describe in English what the function should
do and how you would go about it manually using
pen and paper? Can you translate that process to
Python?

>  As you can see I am having a great problem.

It looks like the normal learning process to me :-)
Just take your time, solve one bit at a time and
build on your previous work. If you get stuck come
back here and ask specific questions and show
us what you have done.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


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


Re: [Tutor] Urgent: Help

2008-01-07 Thread bob gailer
Shumail Siddiqui wrote:
> Dear tutor,
>  I have a question regarding a functions based assignment.
I agree with Alan.

And I wonder why this assignment is hard for you.

Are you in the wrong course (insufficient prerequisites)?

Is the instructor failing to provide the resources you need?

Are you overwhelmed with life and struggling to get through?

Or do you just want to get a passing grade and don't care about learning 
programming and Python?

It might help us if we understood why you are seeking help.

Bob


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


[Tutor] Scope and elegance

2008-01-07 Thread James Newton
Hi Python Practicioners!

I'm trying to come to terms with how Python handles the scope of
objects.  In particular, I'd like to create an instance of one class and
make it available inside instances of other classes.  Something like:


# Test 1-
# I want a "global" instance of this class...
class Foo(object):
def doFoo(self):
return "foo"


# So that I can call one of its functions from another instance 
class Bar(object):
def doBar(self):
# I'd like be able to call a "global" object, but this fails:
# global name 'foo_instance' is not defined
  return foo_instance.doFoo()


def main():
foo_instance = Foo()
bar_instance = Bar()
print bar_instance.doBar()


if __name__ == '__main__': main()
# 


I know that I can pass a pointer to foo_instance as a parameter to the
Bar() call.  For example, this will work:


# Test 2 -
class Foo(object):
def doFoo(self):
return "foo"



class Bar(object):
def doBar(self, aFooInstance):
 return aFooInstance.doFoo()


def main():
foo_instance = Foo()
bar_instance = Bar()
print bar_instance.doBar(foo_instance)


if __name__ == '__main__': main()
# 


I know that I can also create a global instance outside the main()
function.  This will also work:


# Test 3 -
class Foo(object):
def doFoo(self):
return "foo"


class Bar(object):
def doBar(self):
 return foo_instance.doFoo()


foo_instance = Foo()


def main():
bar_instance = Bar()
print bar_instance.doBar()


if __name__ == '__main__': main()
# 


However, this assumes that the Foo instance() is independent of anything
that needs to be done inside the main() function. 


To put the question in context: in the Snakes and Ladders game that I am
making, I have a board divided into 100 squares.  I want a Counter
instance to know which position on the Board it should move to.  I may
have several Counter instances, but only one Board instance.  Each
Counter knows the index number of the square it should move to.  The
Board instance knows how to convert that index number into a screen
position.  I want the Counter instances to be able to ask the Board
instance for that screen position.


Is it unPythonic of me to:
a) Want to create the Board instance inside the main() function
AND
b) Want the Board instance to be globally available so that
   Counters and other objects can talk to it directly?

Or is there just a declaration that I have overlooked that can make an
instance created inside a function visible inside any instance?


I am not so much concerned in getting this to work (I can already do
that); I am more concerned with understanding how to treat this in the
most Pythonesque way.


Thanks in advance for your insights,

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


Re: [Tutor] Scope and elegance

2008-01-07 Thread Kent Johnson
James Newton wrote:

> # So that I can call one of its functions from another instance 
> class Bar(object):
> def doBar(self):
> # I'd like be able to call a "global" object, but this fails:
> # global name 'foo_instance' is not defined
> return foo_instance.doFoo()

It fails because foo_instance is not a global; it is a local variable in 
the main() function. main() is a function too!

> def main():
   global foo_instance # This will do what you want
> foo_instance = Foo()
> bar_instance = Bar()
> print bar_instance.doBar()


> I know that I can pass a pointer to foo_instance as a parameter to the
> Bar() call.

In general I would say that is a better design; I'm not generally a fan 
of globals.

> To put the question in context: in the Snakes and Ladders game that I am
> making, I have a board divided into 100 squares.  I want a Counter
> instance to know which position on the Board it should move to.  I may
> have several Counter instances, but only one Board instance.  Each
> Counter knows the index number of the square it should move to.  The
> Board instance knows how to convert that index number into a screen
> position.  I want the Counter instances to be able to ask the Board
> instance for that screen position.

Hmm. Why does a Counter need to know about screen position? It sounds 
like the Counter might be doing too much. Maybe the Counters should be 
attributes of the Board which can ask them their index numbers and do 
the appropriate drawing? Maybe the code that is drawing the counter 
should ask the Board where to draw it? I can't tell for sure but it 
sounds like your design might be inside out.

> Is it unPythonic of me to:
> a) Want to create the Board instance inside the main() function

That's OK

> b) Want the Board instance to be globally available so that
>Counters and other objects can talk to it directly?

In general, globals are a bad idea in any language, not just Python.

> Or is there just a declaration that I have overlooked that can make an
> instance created inside a function visible inside any instance?

See above.

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


Re: [Tutor] Scope and elegance

2008-01-07 Thread Marc Tompkins
On Jan 7, 2008 12:07 PM, James Newton <[EMAIL PROTECTED]> wrote:

> Hi Python Practicioners!
> ...
> I am not so much concerned in getting this to work (I can already do
> that); I am more concerned with understanding how to treat this in the
> most Pythonesque way.
>

I'd like to get the party line on this as well.  For a while now, I've made
a habit of defining an empty class called Global (Mr. Newton's could be
called Board, of course) at the top of my apps, and using its attributes as
if they were global variables.  It works, of course, but it feels a bit...
dirty.  Is there a more orthodox way to handle it?  Of course, it would be
optimal to remove any need for globals...

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


[Tutor] Tutorials at PyCon 2008 (US)

2008-01-07 Thread Greg Lindstrom
Hello Everyone-

I'd like to announce the tutorials sessions for PyCon 2008 (US).  As you may
know, this year PyCon is being held in Chicago, Illinois March 14-16 with
the Thursday before (the 13th) being "Tutorial Thursday".  We are expecting
nearly 600 Python enthusiasts to meet up for the conference and have 29
tutorial sessions scheduled on Thursday in three sessions; morning,
afternoon, and evening.  There is an extra fee to attend a tutorial, but the
sessions are 3 hours long (with a break) and are taught by some of the
smartest cookies in the Python community.  Pop on over to
http://us.pycon.org/2008/about/ for more information

Here's a list of the sessions currently offered (we may cancel a session if
there are fewer than 10 people registered, but that doesn't happen very
often). In particular, note that there are 4 different introduction to
Python tutorials aimed at different audiences.

*Morning Session* (9:00am-12:20pm)

   - Eggs and Buildout Deployment in
Python(Jeff Rush)
   - Python 101 for
Programmers(Steve
Holden)
   - Introduction to
SQLAlchemy(Jonathan
Ellis and and Michael Baye)
   - Python plotting with matplotlib and
pylab(John Hunter)
   - SWIG Master Class
(David Beazley)
   - Secrets of the Framework
Creators(Feihong
Hsu)
   - Introduction to
NumPy(Travis Oliphant
and Eric Jones)
   - Making Small Software for Small People, Sugar/OLPC Coding by
Example(Mike C.
Fletcher)
   - Hands-on Python for the Absolute Beginner
I(Dr. Andrew
Harrington)

*Afternoon Session* (1:20pm-4:40pm)

   - Python 101
(Stuart
Williams)
   - Getting Started with Pylons/TurboGears2 & WSGI: Modern Python Web
   Development  (Mark
   Ramm and Ben Bangert)
   - Advanced 
SQLAlchemy(Jonathan
Ellis and and Michael Baye)
   - Django Tutorial
(Jacob Kaplan-Moss)
   - wxPython I: Intro to GUI Programming with wxPython and
MVC(David
Goodger)
   - Faster Python Programs through Optimization and Extensions
I(Mike
Müller)
   - Tools for Scientific Computing in
Python(Travis
Oliphant and Eric Jones)
   - Generator Tricks for Systems
Programmers(David
Beazley)
   - Basic Python for Java
Programmers(Alex
Martelli and Anna Ravenscroft)
   - Hands-on Python for the Absolute Beginner
II(Dr.
Andrew Harrington)

*Evening Session* (6:10pm-9:30pm)

   - Python 102
(Stuart
Williams)
   - Mastering Pylons and TurboGears 2: Moving Beyond the
Basics.(Mark Ramm,
Ben Bangert)
   - Practical Applications of Agile (Web) Testing
Tools(C. Titus
Brown and Grig Gheorghiu)
   - Django Code Lab
(Jacob Kaplan-Moss,
Adrian Holovaty and James Bennett)
   - wxPython II: Advanced GUI Programming with wxPython and
MVC(David
Goodger)
   - Faster Python Programs through Optimization and Extensions
II(Mike
Müller)
   - Automating Windows Applications with
win32com(Roy H.
Han)
   - Internet Programming with
Python(Wesley
J. Chun)
   - Tail Wags Fangs: What Python Developers Should Know About
Plone(Rob Lineberger)
   - Pygame: Modern game
development(Noah
Kantrowitz and Marc Destefano)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Scope and elegance

2008-01-07 Thread Torsten Marek
Hi,

I'll try to swallow down the "Globals are eevil" comment, there's enough
literature on that already.

Maybe I'm spoiled from programming too much Java in the last year, but
IMHO it's a good idea to put the singleton instance into the class
itself rather than into some module.

This way, you (can) make sure that all accesses to the class really go
to the same instance. 

There are, of course, many ways to do that, but I'd prefer a method on
the class:

class Foo(object):
@classmethod
def instance(cls):
try:
   return cls._inst
except AttributeError:
   cls._inst = Foo()
   return cls._inst

You can also make more advanced singletons with overwriting __new__ etc,
but that probably overdoes it for the case at hand.

> Is it unPythonic of me to:
> a) Want to create the Board instance inside the main() function
> AND
No.
> b) Want the Board instance to be globally available so that
>Counters and other objects can talk to it directly?
Yes.

> 
> I am not so much concerned in getting this to work (I can already do
> that); I am more concerned with understanding how to treat this in the
> most Pythonesque way.
> 
IMHO it would be better to hand in the board instance into the counter
instances. Globals add hidden dependencies, make code harder to test
etcetc. (Swallowing down didn't work ;-)


best regards,

Torsten
-- 
Torsten Marek <[EMAIL PROTECTED]>
ID: A244C858 -- FP: 1902 0002 5DFC 856B F146  894C 7CC5 451E A244 C858
Keyserver: subkeys.pgp.net



signature.asc
Description: Dies ist ein digital signierter Nachrichtenteil
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Scope and elegance

2008-01-07 Thread James Newton
Kent Johnson [mailto:[EMAIL PROTECTED] wrote:
> Why does a Counter need to know about screen position?
> It sounds like the Counter might be doing too much.
> Maybe the Counters should be attributes of the Board
> which can ask them their index numbers and do the
> appropriate drawing?
> Maybe the code that is drawing the counter should ask
> the Board where to draw it? I can't tell for sure but
> it sounds like your design might be inside out.

Hi Kent,

Thanks for your reply.  It has encouraged me to think in new directions.

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


[Tutor] Urgent: Help

2008-01-07 Thread Michael H. Goldwasser

Very good questions indeed.  Also familiar ones to me. The first is
Exercise 5.28 and the second is Exercise 5.23 from the text book
"Object-Oriented Programming in Python."

Alan's advice was very sound, but I strongly recommend that you work
with your instructor in guiding you through these problems.  He or she
is best qualified to know your current level and the context for such
a homework assignment. Of course, reading the book is also likely to
help.

For everyone else, if you like these exercises there are 300 more
where they came from.  ;-)

With regard,
Michael

   +---
   | Michael Goldwasser
   | Associate Professor
   | Dept. Mathematics and Computer Science
   | Saint Louis University
   | 220 North Grand Blvd.
   | St. Louis, MO 63103-2007



On Sunday January 6, 2008, Shumail Siddiqui wrote: 

>   Investment Thresholds   
>
>  Define a Python function threshold(dailyGains, goal) that behaves as 
> follows. The first parameter is a list of integers that represent the daily 
> gains in the value of a stock. The second paramter is a single positive 
> number that is a profit goal. The function should return the minimum number 
> of days for which the stock should be owned in order to achieve a profit that 
> is equal to or greater than the stated goal. If the goal is unreachable, the 
> function should return 0.   
>For example,   
>threshold ([5, 3, 8, 2, 9, 1], 17)   
>should return 4 because the goal (17) can be reached after the first four 
> days (e.g., 5 + 3 + 8 + 2).   
>  
>  Write a small Python program that uses your threshold() function to 
> demonstrate that it works correctly. Your program may use a pre-defined list 
> of stock gains or it may generate one randomly (see the "Helpful Hints" 
> section below for tips on how to do this). Your program should display this 
> list, prompt the user to enter a profit goal, and then print out the total 
> number of days required to reach that goal (or a message stating that the 
> goal is impossible).   


>   Word Windows   
>
>  Define a Python function sliding(word, num) that behaves as follows. 
> It should print out each num-length slice of the original word , aligned 
> vertically as shown below.   
>For example, a call to sliding("examples", 4) should produce the output   
>
>exam   xampampl mple  ples  
>  
>  
>  Write a small Python program to demonstrate that your sliding() 
> function works correctly. Your program should prompt the user to enter a word 
> and a window size, and then call sliding() with those values.   


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


Re: [Tutor] Scope and elegance

2008-01-07 Thread Kent Johnson
Marc Tompkins wrote:
> I'd like to get the party line on this as well.  For a while now, I've 
> made a habit of defining an empty class called Global (Mr. Newton's 
> could be called Board, of course) at the top of my apps, and using its 
> attributes as if they were global variables.  It works, of course, but 
> it feels a bit... dirty.  Is there a more orthodox way to handle it?  Of 
> course, it would be optimal to remove any need for globals...

We had a discussion pretty recently on the evils of global variables:
http://thread.gmane.org/gmane.comp.python.tutor/44760

In most cases there is a better way, either direct parameter passing or 
instance attributes. Without seeing some code it's hard to make a 
suggestion, though.

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


Re: [Tutor] Scope and elegance

2008-01-07 Thread Kent Johnson
Torsten Marek wrote:

> Maybe I'm spoiled from programming too much Java in the last year, but

Hmm. Would that be
spoil 3 a: to damage seriously : ruin
or
spoil 4 b: to pamper excessively : coddle

? ;-)

> IMHO it's a good idea to put the singleton instance into the class
> itself rather than into some module.
> 
> This way, you (can) make sure that all accesses to the class really go
> to the same instance. 

This is not needed in Python, module-level variables are essentially 
singletons.

> There are, of course, many ways to do that, but I'd prefer a method on
> the class:
> 
> class Foo(object):
> @classmethod
> def instance(cls):
> try:
>return cls._inst
> except AttributeError:
>cls._inst = Foo()
>return cls._inst

Yikes! Looks like 3a to me! How is this safer than having a single 
global instance?

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


Re: [Tutor] [tutor] Pil image related question -- resending messagewithout attachments

2008-01-07 Thread Tiger12506
I assume you realize that jpeg is a lossy format and that consecutively
resizing the same image will no doubt end poorly in image quality.

Also, I assume that you have a better understanding of the NEAREST and
BICUBIC options than I do because you are apparently comparing them. I do
know that those will affect your image quality.

I do not doubt that somewhere in the documentation for PIL (it can be an old
copy) that it will tell you how to set the compression level for jpeg
images, particularly when you save them back, possibly a default
parameter(?).

Kinda shooting in the dark.

> Hello All,
>  I am actually working on a project which deals with image processing.
> I just used pil function to resize the image into the dimensions i want. i
> was able to resize the image but the clarity of the new image is not good.
> Can anyone suggest which other functions i should use to improve the
> clarity. I am attaching the code and sending the images in the attachment.
> Can anyone suggest me how to do it ?
>
> import Image
>
> imageFile = "srk.jpg" #original small image
>
> im1 = Image.open(imageFile)
>
> width = 680
> height = 420
>
> im2 = im1.resize((width,height), Image.NEAREST)
> im3 = im1.resize ((width,height), Image.BICUBIC)
>
> #images get saved in c drive with jpg extensions
> ext = ".jpg"
> im2.save("C:/nearest" + ext)
> im3.save("C:/Bicubic" + ext)
>
> print "files are saved"
>
>
>
> -- 
> Varsha Purohit,
> Graduate Student
>





> ___
> 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] classes and the deepcopy function

2008-01-07 Thread Tiger12506
> Hi
>
> I was trying to learn about classes in Python and have been playing
> around but I am having a problem with the deepcopy function. I want to
> have a function that returns a clean copy of an object that you can
> change without it changing the original, but no matter what I do the
> original changes as well. Can anyone give ma a pointer?

What's really cute about this is the underlying pointers to PyObject s 
giving you troubles. ;-) So you see, you have lots of pointers!

> def move_rectangle(rect, dx, dy):
>rect2 = copy.deepcopy(rect)
>rect2.corner.x += dx
>rect2.corner.y += dy
>return rect2

I want to mention something, even though the whole discussion has been 
beneficial to me as well as to others I'm sure, that you don't need a 
deepcopy here at all. I know that perhaps this is a simplified version of 
code that you might be working on, but perhaps the full version can be 
adapted as well???

def move_rectangle(rect, dx, dy):
  rect2 = rectange()
  rect2.width = rect.width
  rect2.height = rect.height
  rect2.corner.x = rect.corner.x+dx
  rect2.corner.y = rect.corner.y+dy
  return rect2

Hmmm... perhaps the necessary but cumbersome width and the height 
assignments are what makes the deepcopy so helpful in this example... 
Certainly they foreshadow the application of a lot of work with similar 
examples and larger objects

HTH 

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


Re: [Tutor] Program review

2008-01-07 Thread Ricardo Aráoz
Kent Johnson wrote:
> Jeff Younker wrote:
> 
>> Or if you're using python 2.5 then you can use with statements:
>>
>> from __future__ import with_statements
>> from contextlib import closing
>> ...
>> def mails(self):
>> with closing(open_file(self.direcciones)) as fIncl:
>>with closing(open_file(self.excluidas)) as fExcl:
> 
> closing() is not needed, this can be written as
>  with open_file(self.direcciones) as fIncl:
> with open_file(self.excluidas) as fExcl:
> 
> because open files are context managers.
> Or,
> from contextlib import nested
>  with nested(open_file(self.direcciones), open_file(self.excluidas)) 
> as (fIncl, fExcl):
> 

Nice! How would you add exception reporting to this?

>> As you have it written it terminates, but it also silently consumes the
>> exception.  If something goes wrong with your program then there is
>> no way of diagnosing the problem because the failure cause is never
>> reported.
> 
> The exception is written to the log. He may not want the traceback 
> printed to the console.
> 

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


Re: [Tutor] Review and criticism of python project

2008-01-07 Thread Tiger12506
> Tiger12506 wrote:
>
>> Ouch. Usually in OOP, one never puts any user interaction into a class.
>
> That seems a bit strongly put to me. Generally user interaction should be
> separated from functional classes but you might have a class to help with
> command line interaction (e.g. the cmd module in the std lib) and GUI
> frameworks are usually built with classes.

Sorry... made that a little too general. I just have personal experiences
with putting a whole bunch of raw_inputs in a class once and learned never
to make that mistake again when I wanted to use the code for something else.
;-)

>>>uh, tf = line.split(',')
>>>if uh in self.uhdata:
>>>f=self.uhdata[uh]
>>>if tf not in f:
>>>f.append(tf)
>>>else:
>>>self.uhdata[uh]=[tf]
>>
>> This can read
>>
>> try:
>>   f = self.uhdata[uh]
>> except KeyError:
>>   self.uhdata[uh] = []
>> finally:
>>   self.uhdata[uh].append(tf)
>
> These are not equivalent - the original code avoids duplicates in
> self.uhdata[uh].
>
> Possibly self.uhdata[uh] could be a set instead of a list. Then this could
> be written very nicely using defaultdict:
>
> from collections import defaultdict
>   ...
>   self.uhdata = defaultdict(set)
>   ...
>   self.uhdata[uh].add(tf)
>
>>>for uh, Sections in self.uhdata.items():
>>>Sections.sort()
>>
>> This will not work. In the documentation, it says that dictionary object
>> return a *copy* of the (key,value) pairs.
>> You are sorting those *copies*.
>
> No, the original code is fine. The docs say that dict.items() returns "a
> copy of a's list of (key, value) pairs". This is a little misleading,
> perhaps. A dict does not actually contain a list of key, value pairs, it
> is implemented with a hash table. dict.items() returns a new list
> containing the key, value pairs.
>
> But the keys and values in the new list are references to the same keys
> and values in the dict. So mutating the values in the returned list, via
> sort(), will also mutate the values in the dict.

Ah hah! Yes knew about hashes... It was the references that got me. I need
to learn to use id() at the python prompt a little more often. ;-)

>>>missingpgcounts={}
>>>fmissingpgcounts=[]
>>>for x in self.uhdata:
>>>for f in self.uhdata[x]:
>>>if f not in fmissingpgcounts:
>>>fmissingpgcounts.append(f)
>>
>> fmissingpgcounts = [f for f in self.uhdata.itervalues() if f not in
>> fmissingpgcounts]
>> Ahhh... This looks like a set.
>> fmissingpgcounts = set(self.uhdata.itervalues())
>
> Again, this is not quite the same thing. The original code builds a set of
> the contents of the values. You are building a set from the values (which
> are already lists). You still need one loop:
> fmissingpgcounts = set()
> for v in self.uhdate.itervalues():
>   fmissingpgcounts.update(v)
>
>> self.pgcounts = dict((x,0) for x in fmissingpgcounts)
>
> or, self.pgcounts = dict.fromkeys(fmissingpgcounts, 0)
>
> That's all I have energy for...
> Kent
>

Hmm... Apparently I didn't have enough energy. I must remember to eat
breakfast more often, it's affecting how I think... You're completely right
of course, Kent! What would all of us do without you?

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


Re: [Tutor] Program review

2008-01-07 Thread Kent Johnson
Ricardo Aráoz wrote:
> PEP 0343 is not an
> example of clarity in the definition of a statement, it mixes
> justification with historic development with definition with actual
> equivalent code. Couldn't or wouldn't bother to understand it.

Here is a better starting point:
http://docs.python.org/whatsnew/pep-343.html

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


Re: [Tutor] Scope and elegance

2008-01-07 Thread Ricardo Aráoz
James Newton wrote:
> Hi Python Practicioners!
> 
> I'm trying to come to terms with how Python handles the scope of
> objects.  In particular, I'd like to create an instance of one class and
> make it available inside instances of other classes.  Something like:
> 
> 
> # Test 1-
> # I want a "global" instance of this class...
> class Foo(object):
> def doFoo(self):
> return "foo"
> 

Puafff!!! Global = B (unless, of course, there is no other way)

> I know that I can pass a pointer to foo_instance as a parameter to the
> Bar() call.  For example, this will work:
> 

Better!

> I know that I can also create a global instance outside the main()
> function.  This will also work:
> 

Worse!


> To put the question in context: in the Snakes and Ladders game that I am
> making, I have a board divided into 100 squares.  I want a Counter
> instance to know which position on the Board it should move to.  I may
> have several Counter instances, but only one Board instance.  Each
> Counter knows the index number of the square it should move to.  The
> Board instance knows how to convert that index number into a screen
> position.  I want the Counter instances to be able to ask the Board
> instance for that screen position.
> 

Maybe you have a design issue here (it is usually the case if you have
to use globals). I would think it this way initially, a Board object has
(amongst other properties) a list property containing Piece objects, the
 Piece objects have the piece owner's name and the piece's position in
the board. The Board has a throwDice method which gets the dice result
and applies it to the nextPlayer (another property of Board, or of the
player's list which could be an object itself and manage nextPlayer),
nextPlayer would update it's position and ask the Board (it's container)
to update it's position. This comes off the top of my head so it will
certainly require redesign, but you get the idea, no globals. To start
the game you would call Board.play() which would have a loop till the
end of game is reached.

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


Re: [Tutor] Program review

2008-01-07 Thread Kent Johnson
Ricardo Aráoz wrote:
> Kent Johnson wrote:
>> from contextlib import nested
>>  with nested(open_file(self.direcciones), open_file(self.excluidas)) 
>> as (fIncl, fExcl):
>>
> 
> Nice! How would you add exception reporting to this?

I don't have a good answer to that, that's why I didn't propose it 
originally. You could use

try:
   with nested(open_file(self.direcciones), open_file(self.excluidas))
as (fIncl, fExcl):
 try:
   do_something_with(fIncl, fExcl)
 except:
   # handle exceptions from do_something_with()
except:
   pass # We already logged exceptions from the open_file calls

You could omit the inner try/except if you are sure that 
do_something_with() won't raise an exception, but it's pretty hard to be 
sure of that unless it wraps its contents already.

Looking at PEP 343, it's pretty clear ;-) that exceptions raised by 
open_file() will just be passed out of the with statement. Look at the 
pseudo-code in the section "Specification: The 'with' Statement". The 
exception is raised in the very first line - mgr = (EXPR) - when 
open_file() is called.

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


Re: [Tutor] Program review

2008-01-07 Thread Ricardo Aráoz
Jeff Younker wrote:
>> Maybe it is my poor understanding of exception handling. My intention
>> here is to open the first file, if error then report in logging and
>> finish normally, else open the 2nd file, if error then report in  
>> logging
>> close the 1st file and finish normally. If no error then process.
>>
> 
> Right, but it helps to break up the error handling and the cleanup.
> Right now the error reporting exception handlers are intermixed
> with your cleanup error handlers.  Separating them makes the code
> clearer.
> 

Yes, but in such a simple program I'd rather have shallow level of
function/method callings. After all the pertinent code fits all in a
screen and is not hard to understand. If it was bigger or more
complicated I agree with you and I would re-factor it.

> def open_file(filename):
>   try :
>   return open(filename)
>   except Exception:
>   logging.error('No pude abrir "%s"' % filename, exec_info=True)
>   raise
> 
> # Goes into configuration class
> def mails(self):
>fIncl = open_file(self.direcciones)
>try:
>   fExcl = open_file(self.excluidas)
>   try:
>   return enumerate(
>   set(addr.strip() for addr in fIncl)
>   - set(excl.strip() for excl in fExcl))
>   finally:
>fExcl.close()
>finally:
> fIncl.close()
> 

Both open_file assignments should go after the respective 'try:' statement.
Besides both 'finally:' blocks will be executed after an exception (i.e.
the file is not open) generating a second exception. Wrong use of
'finally:', it is executed even if an exception has occurred.
>From Python 2.5 Documentation :
"""
If finally is present, it specifies a `cleanup' handler. The try clause
is executed, including any except and else clauses. If an exception
occurs in any of the clauses and is not handled, the exception is
temporarily saved. The finally clause is executed. If there is a saved
exception, it is re-raised at the end of the finally clause. If the
finally clause raises another exception or executes a return or break
statement, the saved exception is lost.
"""

> Or if you're using python 2.5 then you can use with statements:
> 
> from __future__ import with_statements
> from contextlib import closing
> ...
> def mails(self):
>  with closing(open_file(self.direcciones)) as fIncl:
> with closing(open_file(self.excluidas)) as fExcl:
> return enumerate(
> set(addr.strip() for addr in fIncl)
> - set(excl.strip() for excl in fExcl))
> 
>> close the 1st file and finish normally. If no error then process.
> 

How would that look with exception handling included? PEP 0343 is not an
example of clarity in the definition of a statement, it mixes
justification with historic development with definition with actual
equivalent code. Couldn't or wouldn't bother to understand it.

> If an exception is raised then the code terminates right there and
> then.   So, if procesar is written as:
> 
> def procesar(mensaje):
>   mails = mensaje.mails()
>   miCorreo = Correo(mensaje)
>   
> 
> then if mensaje.mails() raises an exception then the code
> terminates immediately, and the body of Correo will only be
> executed if there is no error.
> 
> As you have it written it terminates, but it also silently consumes the
> exception.  If something goes wrong with your program then there is
> no way of diagnosing the problem because the failure cause is never
> reported.

Yes, it is reported in the log. And that's exactly how I want it to be.
In my experience non tech users will go into panic if they see an error
screen with all that info up their faces. OTOH if they look at a log
file they seem to feel they have more control over the situation and
that what happened is not catastrophic.

Ricardo

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


Re: [Tutor] Program review

2008-01-07 Thread Ricardo Aráoz
Kent Johnson wrote:
> Ricardo Aráoz wrote:
>> PEP 0343 is not an
>> example of clarity in the definition of a statement, it mixes
>> justification with historic development with definition with actual
>> equivalent code. Couldn't or wouldn't bother to understand it.
> 
> Here is a better starting point:
> http://docs.python.org/whatsnew/pep-343.html
> 
> Kent
> 

Thanks Kent, it's clearer, but it gets rapidly complicated. Anyway
looking at the simpler use, if you would have exception handling in :

try :
with open('/etc/passwd', 'r') as f:
for line in f:
print line
... more processing code ...
except ExceptionsOnOpening :
... exception handling
except :
... exceptions inside the for



Whereas traditionally :

try :
f = open('/etc/passwd', 'r')
for line in f:
print line
... more processing code ...
except ExceptionsOnOpening :
... exception handling
except :
... exceptions inside the for


I don't see much difference except in the with example you have one more
level of indentation.

Don't know about more advanced uses, I'll try to understand them when
and if I ever need them.






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


Re: [Tutor] Program review

2008-01-07 Thread Ricardo Aráoz
Kent Johnson wrote:
> Ricardo Aráoz wrote:
>> Kent Johnson wrote:
>>> from contextlib import nested
>>>  with nested(open_file(self.direcciones), open_file(self.excluidas)) 
>>> as (fIncl, fExcl):
>>>
>> Nice! How would you add exception reporting to this?
> 
> I don't have a good answer to that, that's why I didn't propose it 
> originally. You could use
> 
> try:
>with nested(open_file(self.direcciones), open_file(self.excluidas))
> as (fIncl, fExcl):
>  try:
>do_something_with(fIncl, fExcl)
>  except:
># handle exceptions from do_something_with()
> except:
>pass # We already logged exceptions from the open_file calls
> 
> You could omit the inner try/except if you are sure that 
> do_something_with() won't raise an exception, but it's pretty hard to be 
> sure of that unless it wraps its contents already.
> 
> Looking at PEP 343, it's pretty clear ;-) that exceptions raised by 
> open_file() will just be passed out of the with statement. Look at the 
> pseudo-code in the section "Specification: The 'with' Statement". The 
> exception is raised in the very first line - mgr = (EXPR) - when 
> open_file() is called.
> 

Yes, I can see that. I don't like it, too much hair splitting to get
something that is easily programmed the traditional way. I don't want to
be thinking about if the exception will or will not be passed out of the
with statement, and I CERTAINLY don't want the person who will be
modifying my code to have to think about those things. I'll stay with
the old way, easier, clearer and almost the same length, I fail to see
what I would win by coding this way.


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


Re: [Tutor] Program review

2008-01-07 Thread Torsten Marek

On Mo, 2008-01-07 at 21:15 -0300, Ricardo Aráoz wrote:
> Kent Johnson wrote:
> > Ricardo Aráoz wrote:
> >> PEP 0343 is not an
> >> example of clarity in the definition of a statement, it mixes
> >> justification with historic development with definition with actual
> >> equivalent code. Couldn't or wouldn't bother to understand it.
> > 
> > Here is a better starting point:
> > http://docs.python.org/whatsnew/pep-343.html
> > 
> > Kent
> > 
> 
> Thanks Kent, it's clearer, but it gets rapidly complicated. Anyway
> looking at the simpler use, if you would have exception handling in :
> 
> try :
> with open('/etc/passwd', 'r') as f:
> for line in f:
> print line
> ... more processing code ...
> except ExceptionsOnOpening :
> ... exception handling
> except :
> ... exceptions inside the for
> 
> 
> 
> Whereas traditionally :
> 
> try :
> f = open('/etc/passwd', 'r')
> for line in f:
> print line
> ... more processing code ...
> except ExceptionsOnOpening :
> ... exception handling
> except :
> ... exceptions inside the for

Hi Ricardo,

don't forget the "f.close()" call after the for loop, in a finally block
[0]. Context managers are all about generalizing non-adjacent parts of
setup and teardown code  

Actually, the fact that you forgot the close call is an argument for
using the context manager;)

best,

Torsten
[0] http://docs.python.org/lib/bltin-file-objects.html
-- 
Torsten Marek <[EMAIL PROTECTED]>
ID: A244C858 -- FP: 1902 0002 5DFC 856B F146  894C 7CC5 451E A244 C858
Keyserver: subkeys.pgp.net



signature.asc
Description: Dies ist ein digital signierter Nachrichtenteil
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Scope and elegance

2008-01-07 Thread Tiger12506
I like this.

class Counter:
  def __init__(self):
  self.score = 0
  def incr(x, y):
 self.score += 2*x+3*y

class Board:
  def __init__(self):
self.counter = Counter()
self.curcoords = (0,0)
  def update(self)
self.counter.incr(*self.curcoords)


Whatever OOP term is used to describe that. In other words, make your board
class be a container for the various counters. Especially if certain Boards
always contain certain counters. Just personal opinion...

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


Re: [Tutor] Urgent: Help

2008-01-07 Thread bob gailer
Please reply to the list not just me. We all participate and learn.

Shumail Siddiqui wrote:
> I know this assignment is not too hard, but I have been greatly 
> overwhelmed with work as I have been taking a 19 credits recently. I 
> kind of have an approach to this by importing random numbers and 
> random.choice leaves the first four numbers as a result. But, I don't 
> know how to add these numbers in the program, 
One approach is:

start with a total of 0
add the first number to the total
if the total does not reach the goal
add the next number
etc.

That can be implemented in a loop.

Give it a try and show us how far you can come.

> while I know that I can use append to add those scores.
I don't know how to use append to add

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


Re: [Tutor] Program review

2008-01-07 Thread Ricardo Aráoz
Torsten Marek wrote:
>> try :
>> with open('/etc/passwd', 'r') as f:
>> for line in f:
>> print line
>> ... more processing code ...
>> except ExceptionsOnOpening :
>> ... exception handling
>> except :
>> ... exceptions inside the for
>>
>>
>>
>> Whereas traditionally :
>>
>> try :
>> f = open('/etc/passwd', 'r')
>> for line in f:
>> print line
>> ... more processing code ...
>> except ExceptionsOnOpening :
>> ... exception handling
>> except :
>> ... exceptions inside the for
> 
> Hi Ricardo,
> 
> don't forget the "f.close()" call after the for loop, in a finally block
> [0]. Context managers are all about generalizing non-adjacent parts of
> setup and teardown code  
> 
> Actually, the fact that you forgot the close call is an argument for
> using the context manager;)
> 

Hi Torsten,

or an argument for going to sleep at 10 pm after a hard day's work and
38º Centigrades temperature.  ;c)


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


Re: [Tutor] Program review

2008-01-07 Thread Kent Johnson
Ricardo Aráoz wrote:
> looking at the simpler use, if you would have exception handling in :
> 
> try :
> with open('/etc/passwd', 'r') as f:
> for line in f:
> print line
> ... more processing code ...
> except ExceptionsOnOpening :
> ... exception handling
> except :
> ... exceptions inside the for
> 
> 
> 
> Whereas traditionally :
> 
> try :
> f = open('/etc/passwd', 'r')
> for line in f:
> print line
> ... more processing code ...
> except ExceptionsOnOpening :
> ... exception handling
> except :
> ... exceptions inside the for
> 
> 
> I don't see much difference except in the with example you have one more
> level of indentation.

The with version will close the file when the with block exits.

> Don't know about more advanced uses, I'll try to understand them when
> and if I ever need them.

Maybe 'with open(...) as ...' is more useful in contexts where you are 
not so picky about exception handling.

Here is a context manager and associated decorator you might be 
interested in - it traps errors and logs them :-)
http://blogmaker.googlecode.com/svn/trunk/blogmaker/util/trap_errors.py

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


[Tutor] Error checking and such in a console "guess my number" game

2008-01-07 Thread Brett Wilkins
Hi there,

I'm been following a tutorial in a Python Programming book, making a 
Guess My Number game.
I decided to go and modify it a bit more, therefore expanding it.

What I added in was the ability to modify the range of the pseudo-random 
number generator, an exit strategy (i.e. type stop at the prompt), 
something that keeps track of the amount of times you've gotten it 
right, and error checking. Now, without further ado, here's the code 
I've got:


#! /usr/bin/python

#imports area
import random

#main body
guessed_number = 0
stop = "n"
times_played = 0
range_for_random = 0
inter_range = ''
default = 100
print """
Welcome to

Guess My Number!

In this game you will attempt to guess a number that
the computer will psuedo-randomly generate, With
a range for which you dictate the ending point.
Good Luck!"""
while 1:
inter_range = raw_input("\n\n Please specify the range for the 
randon number to reside within: ")

alphabet = "abcdefghijklmnopqrstuvwxyz"
intermediary_number = raw_input("\n\nPlease enter your guess, or 
type stop to end game: ")

if intermediary_number == "stop":
exit()
elif 1:
for char in alphabet:
if char in inter_range:
range_for_random = default
continue
else:
if inter_range == '':
range_for_random = default
else:
range_for_random = int(inter_range)

while 1:
if times_played > 0:
stop = raw_input("\n\nTo end the game, type in stop, Or to 
change the range, type change. Otherwise just press Enter:")
if stop.lower() == "change": break
elif stop.lower() == "stop": exit()
print "\n\nTime to start Guessing My Number!"
random_number = random.randrange(range_for_random) + 1
   
while 1:
alphabet = "abcdefghijklmnopqrstuvwxyz"
intermediary_number = raw_input("\n\nPlease enter your 
guess, or type stop to end game: ")
   
if intermediary_number == "stop":
exit()
elif 1:
for char in alphabet:
if char in intermediary_number:
guessed_number = 0
continue
else:
if intermediary_number == '':
guessed_number = 0
else:
guessed_number = int(intermediary_number)
if guessed_number > random_number:
print "\nYour guess was too high!"
elif guessed_number < random_number:
print "\nYour guess was too low!"
elif guessed_number == random_number:
print "\nYes, you got the right answer! The answer was: 
" + str(random_number)
times_played += 1
print "You have now played %s time(s)." % (times_played)
break

Now I was wondering first off, is there a better way about doing the 
error checking? I already tried try-except blocks, but as I'm new to 
python (this is my second program after "Hello World") I don't know how 
to only catch certain exceptions (in this case a ValueError). Using 
try-except without limiting seems to disable Ctrl+C breaking in the 
console, I found.

The next thing is my real problem:

if times_played > 0:
stop = raw_input("\n\nTo end the game, type in stop, Or to 
change the range, type change. Otherwise just press Enter:")
if stop.lower() == "change": break
elif stop.lower() == "stop": exit()

What I want the break statement to do here is exit the while loop isn't 
currently in, but it just seems to break the current if decision, making 
it rather redundant. A little help with this in particular would be much 
appreciated :)

And just so you know, I'm teaching myself python, for fun and for an 
upcoming job, and this is just fun for me.

Cheers,

Brett


-- 
**
Brett Wilkins
A.K.A Beedub
The Fixit

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