Re: [Tutor] rounding up to the nearest multiple of 8

2012-10-04 Thread Steven D'Aprano
On Thu, Oct 04, 2012 at 05:26:13PM -0400, eryksun wrote:
> On Thu, Oct 4, 2012 at 4:04 PM, Joel Goldstick  
> wrote:
> >
>  my_string = "123"
>  pad = 8 - len(my_string) % 8
>  my_string = my_string + " " * pad
>  my_string
> > '123 '
> 
> If len(my_string) is already a multiple of 8, the above sets pad to 8:
> 
> >>> s = "12345678"
> >>> pad = 8 - len(my_string) % 8
> >>> pad
> 8

Here's another way:


py> from __future__ import division
py> from math import ceil
py> "%*s" % (int(ceil(len(mystring)/8)*8), mystring)
'123412341234'


Or left-justified:

py> "%-*s" % (int(ceil(len(mystring)/8)*8), mystring)
'123412341234'


In Python 3, there is no need for the "from __future__" line.



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Tkinter-discuss] displaying an image

2012-10-04 Thread eryksun
On Fri, Oct 5, 2012 at 12:39 AM, eryksun  wrote:
>
> # apt-get install build-essential python3-dev tk8.5-dev \
> libjpeg8-dev liblcms1-dev libfreetype6-dev

I forgot zlib:

# apt-get install build-essential python3-dev tk8.5-dev \
libjpeg8-dev liblcms1-dev libfreetype6-dev zlib1g-dev
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Tkinter-discuss] displaying an image

2012-10-04 Thread eryksun
On Thu, Oct 4, 2012 at 3:31 PM, Matthew Ngaha  wrote:
>> You need to install PIL to use the tutorial you are doing.
>>
>> http://www.pythonware.com/products/pil/
>
> the site says
> "
> The current free version is PIL 1.1.7. This release supports Python
> 1.5.2 and newer, including 2.5 and 2.6. A version for 3.X will be
> released later.
> "
>
> i have python 3. all the downloads below it only show python 2
> versions. am i stuck?:(

If you're using Windows, Christoph Gholke has an installer for an
unofficial port to 3.2/3.3 for 32-bit and 64-bit platforms:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil

He also has the ported source code available to build PIL on a
non-Windows platform. But be forewarned this is rarely a simple
process. Below I've stepped through compiling the ported code on my
Debian system. But your mileage will *probably* vary...

Extract the source and change to the directory. Switch to your root
account and update/install the development packages. I'm skipping TIFF
support since Debian's libtiff4-dev package doesn't have the private
header (tiffiop.h) needed for PIL's experimental TIFF support.

Steps:

$ sudo su
# apt-get update
# apt-get install build-essential python3-dev tk8.5-dev \
libjpeg8-dev liblcms1-dev libfreetype6-dev


Two files need to be edited before building the extension modules.

(1) As is, the library files for the optional features won't be found.
You could symlink the required library files to /usr/lib, but I'd
rather modify setup.py. After line 229 in setup.py, add the lib
directory that Debian uses:

For a 32-bit platform, add the following:

add_directory(library_dirs, "/usr/lib/i386-linux-gnu")

For a 64-bit platform, add the following:

add_directory(library_dirs, "/usr/lib/x86_64-linux-gnu")


(2) In _imagingft.c: font_getsize, someone modified the source to use "max".

Original:

PIXEL(self->face->size->metrics.height)

Modified:

PIXEL(max(
self->face->size->metrics.height,
self->face->bbox.yMax - self->face->bbox.yMin))

"max" isn't defined, however, so you have to add a macro. I defined it
on line 21:

#define max(a,b) ((a) > (b) ? a : b)


With those two edits, you should be able to build the extension
modules in place:

# python3 setup.py build_ext -i

Run the tests:

# python3 selftest.py

I get the following output:

--- PIL CORE support ok
--- TKINTER support ok
--- JPEG support ok
--- ZLIB (PNG/ZIP) support ok
--- FREETYPE2 support ok
--- LITTLECMS support ok
--
Running selftest:
--- 57 tests passed.


Now do the full the installation:

# python3 setup.py install

Then from the same directory start python3 and test showing an image:

>>> from PIL import Image
>>> img = Image.open('Images/lena.png')
>>> img.show()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie help with .pyc

2012-10-04 Thread Ashfaq
Hey Ken,

Steve has just made some innocent fun. He is eager to help the guy. Please
don't be so harsh.

Sincerely
Ashfaq
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie help with .pyc

2012-10-04 Thread ken brockman
I wonder if they might be a way for some on this forum to dispense advice and 
help others without the totally snide and obnoxious attitude? if it is 
so painfully annoying for you to deal with, why subject yourself to it? 
I suspect it is the sheer joy of showing others how bright you are and 
just how much disdain you have  for the lower forms of life you share the 
planet with.

Now give me a 4 paragraph long diatribe about top posting, netiquette and loads 
of all manner of minutia on the proper way to post and Make sure you do it in 
the most belittling way possible.





 From: Steven D'Aprano 
To: tutor@python.org 
Sent: Thursday, October 4, 2012 1:39 PM
Subject: Re: [Tutor] Newbie help with .pyc
 
On 05/10/12 01:21, tfahey1 wrote:
> Hey everyone,
>
> I am a Maya user, so I only come into contact with Python scripting on a
> surface level, but I downloaded a python script from a CG website that I
> would like to check out but I am getting an error when it is run.


Would you like us to guess what error you are getting? And how you are
trying to run it? I love guessing games!

Nah, actually I'm lying. I hate guessing games. Please tell us exactly how
you are trying to run the file, and show us the EXACT error you get. Copy
and paste the error message.


>  The only
> file included was a .pyc file. I'm wondering if there should also be a .py
> file along with it? Is there anyway I could fix this script to work without
> a .py file?

Probably. The way to "fix" it will depend on what error you are getting.



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Tkinter-discuss] displaying an image

2012-10-04 Thread Oscar Benjamin
On 4 October 2012 20:31, Matthew Ngaha  wrote:
>> You need to install PIL to use the tutorial you are doing.
>>
>> http://www.pythonware.com/products/pil/
>
> the site says
> "
> The current free version is PIL 1.1.7. This release supports Python
> 1.5.2 and newer, including 2.5 and 2.6. A version for 3.X will be
> released later.
> "
>
> i have python 3. all the downloads below it only show python 2
> versions. am i stuck?:(

Yes.

Well actually, no. You can just install Python 2.7 and use PIL with
that. It might be better though to focus on things that do work in
Python 3 and find a tutorial that doesn't need PIL.

It's possible that PIL will never be available for Python 3. Here's a
message from 2009 on the PIL mailing list (it looks like not much has
changed since then):
'''
The plan is to get 1.1.7 out of the door (early april) and then make a
version of that available for 3.x. There's also a preliminary port of 1.1.6
available from a third party; see the mailing list archives for pointers.
'''

http://mail.python.org/pipermail/image-sig/2009-March/005498.html

Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I Need Help With Using Tkinter/Console/Creating GUIs

2012-10-04 Thread Steven D'Aprano

On 05/10/12 07:30, tayo rotimi wrote:

Hi,

I recently started learning as a python programming 'absolute beginner'.
 I have Python 3.2 installed on my laptop, and I have learned to a point
 where I need to create GUIs. I understand from the text book I am
 reading that all I need to have access to the Tkinter toolkits in a
 window-OS is double click on the Python icon to run Tkinter program
directly; but I don't have Python icon on my desktop. I went to the
program list and the relevant stuffs I have there are the IDLE (Python
GUI) and Python (command line). Double clicking on any of these did not
 bring out the console described for creating GUIs.


Then what did they do?



I am in a fixed. Its either the Tkinter module is not available on my
 Python installation or there are things I am not doing right. Please I
 need help, I need some practical guides on how to start creating GUI.
 Again, I have Python 3.2 installed on my system.


What operating system are you using?

Open the Python command line, and you should see a console open with
something like this:

Python 3.2.2 (default, Mar  4 2012, 10:50:33)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>



Type:

import tkinter

and press the Enter key. What happens? If you get an error, copy and paste
the entire traceback, not just the error message.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] I Need Help With Using Tkinter/Console/Creating GUIs

2012-10-04 Thread tayo rotimi
Hi,

I recently started learning as a python programming 'absolute beginner'. I have 
Python 3.2 installed on my laptop, and I have learned to a point where I need 
to create GUIs. I understand from the text book I am reading that all I need to 
have access to the Tkinter toolkits in a window-OS is double click on the 
Python icon to run Tkinter program directly; but I don't have Python icon on my 
desktop. I went to the program list and the relevant stuffs I have there are 
the IDLE (Python GUI) and Python (command line). Double clicking on any of 
these did not bring out the console described for creating GUIs. I am in a 
fixed. Its either the Tkinter module is not available on my Python installation 
or there are things I am not doing right. Please I need help, I need some 
practical guides on how to start creating GUI. Again, I have Python 3.2 
installed on my system.   


Regards.

Tayo.___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rounding up to the nearest multiple of 8

2012-10-04 Thread eryksun
On Thu, Oct 4, 2012 at 4:04 PM, Joel Goldstick  wrote:
>
 my_string = "123"
 pad = 8 - len(my_string) % 8
 my_string = my_string + " " * pad
 my_string
> '123 '

If len(my_string) is already a multiple of 8, the above sets pad to 8:

>>> s = "12345678"
>>> pad = 8 - len(my_string) % 8
>>> pad
8

You could special case when the modulo value is 0, or use pad % 8, but
I think it's simpler to calculate "-len(s) % 8":

>>> [(charlen, -charlen % 8) for charlen in range(9)]
[(0, 0), (1, 7), (2, 6), (3, 5), (4, 4), (5, 3), (6, 2), (7, 1), (8, 0)]


For example:

>>> len_mod = lambda s, n: len(s) + (-len(s) % n)

>>> s = ''; s.ljust(len_mod(s, 8))
''
>>> s = '12345678'; s.ljust(len_mod(s, 8))
'12345678'
>>> s = '123456'; s.ljust(len_mod(s, 8))
'123456  '
>>> s = '123456789'
>>> len_mod(s, 8)
16
>>> s.ljust(len_mod(s, 8))
'123456789   '

>>> s.ljust(len_mod(s, 9))
'123456789'
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MAXIMUM LOOP LOGIC

2012-10-04 Thread Brian van den Broek
On 4 Oct 2012 13:22, "medusa"  wrote:
>
> Hello
>
> i got stuck with the last bit of my programming practice.



> Instead of printing off a number beside the email, i got another email
and i
> dont know how to fix it.
> 

Hi,

Is your code long? If not, you should include it in your message. If it is,
you should spend the time to trim it down to a short chunk that
demonstrates the issue.

While opinions are divided, many don't like code provided via a link in
tutor posts. That cuts down on the number of people willing to look at your
code. By the link you gave, it seems like you've posted a screenshot or
other image. Even those who are happy to follow links to code are unlikely
to be willing to retype what is shown in your image file.

I'd suggest posting again, this time with code.

Best,

Brian vdB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hello Can someone looked at my problem? stuck

2012-10-04 Thread Walter Prins
On 3 October 2012 04:39, Palice Fan  wrote:

> Hello
> i got stuck with the last bit of my programming practice.
> Can somebody help me?
> Write a program to read through a mail log, and figure out who had the most
> messages in the file. The program looks for “From” lines and takes the
> second parameter on
> those lines as the person who sent the mail.
> The program creates a Python dictionary that maps the sender’s address to
> the total number of
> messages for that person.
> After all the data has been read the program looks through the dictionary
> using a maximum loop
> (see Section 5.7.2) to find who has the most messages and how many
> messages the person has.
>
> Enter a file name: mbox-short.txt
> c...@iupui.edu :5
> Enter a file name: mbox.txt
> zq...@umich.edu :195
>
> Instead of printing off a number beside the email, i got another email and
> i dont know how to fix it.
>

For future reference, please either include the source code in the email as
text or as text attachment.  A screen capture means I have to retype all
your code (and in this case some data) in order to have a look at your
problem.  Not fun.

To fix your problem you have to reverse engineer what's going on in your
program.  I'll try and walk you through a little thought process in
figuring out what's going on to try and help you.

The last statement in your program (which is where the error is apparent)
prints a fixed email address followed by a value that's assigned earlier on
in a loop from the "values" variable. Consequently you should carefully
inspect your code and ask yourself how it's possible that an email address
instead of a number is being assigned to the "values" variable and thereby
eventually to the "max" variable.  (By the way, note that "max" is not
recommended as a variable name since max is also a built-in function in
Python and so by declaring a variable with the same name you're hiding
(known as shadowing) the Python function.  You can see there's something
special about it by the fact that IDLE colours it purple, which should tip
you off.)  But anyway, back to your "max" variable and "values" variable,
we now look back carefully at the loop to see how or where we might be
picking up email addresses when we should be getting integer counts...
Let's look carefully at the loop declaration:

for values in messages:

Hmmm, this is looping directly over the dictionary "messages".  What is
returned when you iterate directly over a dict like that?  (Hint, it's not
the values, but the keys... e.g. the email addresses.)  Add some print
statements in your loop so you can see what happens when it runs, for
example:

print 'Starting iterating over "messages" dict'
for values in messages:
print 'Value of "values" this iteration =', values
if max is None or values > max:
print 'Updating max...'
max = values
print 'Value of "max" after this iteration =', max

If you apply similar changes to your program and run that you'll see why
the program doesn't work -- "values" is being assigned the keys (email
addresses) from the dict, not the values.  It should also become clear that
basically "values" is also a bad choice for the items being iterated over
in the messages dict and is perhaps adding to the confusion, better would
be:

for email_sender in messages:

This would make it clear that the items being iterated over are in fact the
email addresses.  It's always a good idea to use descriptive specific names
in your programs, not least because you yourself also need to read and
understand your own code.  Anyway, then later in your loop it's then
obvious that you can't just do:

if max is None or values > max:
max = values

(or if we use my suggested renaming)

if max is None or email_sender > max:
max = email_sender

Instead you want to retrieve the actual value (count) from the dict for
that specific email sender, e.g.

if max is None or messages[email_sender] > max:
max = messages[email_sender]

... and with that I've now basically explained the essence of your first
main problem.

However there remains another major flaw. Why are we assigning and
outputting 'c...@iupui.edu' as the email address with the maximum number of
emails, for any input?  Clearly that can't be right - if the input changes
and another email address has the highest count then this code will output
the wrong result.  So in addition to saving the max count, you must also
save the max sender in the loop.  I think that's enough for now, see if you
can fix your program given the above hints and if not post back again.

HTH,

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MAXIMUM LOOP LOGIC

2012-10-04 Thread eryksun
On Wed, Oct 3, 2012 at 12:11 AM, medusa  wrote:
>
> After all the data has been read the program looks through the dictionary
> using a maximum loop
>
> Instead of printing off a number beside the email, i got another email and i
> dont know how to fix it.
> 

A dict iterates over its keys, so your loop is finding the 'max' email
address (in string sort order), which is the one starting with the
letter 'z'.

You need to iterate over iteritems() if you want both keys and values:

for item in messages.iteritems():

"item" is a tuple containing the (key, value) pair. You can
immediately unpack this tuple if you want:

for email, count in messages.iteritems():

BTW, your variable named "max" is masking the built-in function "max"
that will do what you want, faster and simpler -- especially since
you're testing if "max is None" for every value in the loop.

In general for a reducing operation such as max (or min, sum, etc),
initialize to the first item of the iterable/iterator. You can get the
first item of an iterator using the built-in next() function. This
function has an optional 2nd argument to set a default value, which
could be used as a sentry, but let's use a simple test to see if
"messages" is empty instead of worrying about default values and
exception handling:

if messages:
it = messages.iteritems()
max_item = next(it)
for item in it:
if item[1] > max_item[1]:
max_item = item
print max_item[0], max_item[1]
else:
print "no messages"


There's also the built-in function "reduce" for this kind of thing.
Here's a simple example of how it works:

>>> from operator import add
>>> add(1, 1)
2
>>> reduce(add, [1,1,1,1,1])
5

Here's what this does:

add(1, 1) => 2
add(2, 1) => 3
add(3, 1) => 4
add(4, 1) => 5


So you could replace the reducing loop with the built-in reduce()
function. First you have to define a simple function (call it "imax")
to return the max of two key/value tuple items based on the value in
index 1:

imax = lambda a, b: b if b[1] > a[1] else a

if messages:
max_item = reduce(imax, messages.iteritems())
print max_item[0], max_item[1]
else:
print "no messages"


Finally, here's a solution using "max". It's similar, but more efficient:

from operator import itemgetter

if messages:
max_item = max(messages.iteritems(), key=itemgetter(1))
print max_item[0], max_item[1]
else:
print "no messages"


dict.get also has a default value option, which will help to simplify
the code in your first for loop. Instead of testing if email is in
messages and special casing the first insertion, you can use
get(email, 0):

messages[email] = messages.get(email, 0) + 1

Also, using a defaultdict would be even simpler and faster:

>>> from collections import defaultdict
>>> messages = defaultdict(int)

>>> messages['ma...@gmail.com'] += 1
>>> messages
defaultdict(, {'ma...@gmail.com': 1})
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rounding up to the nearest multiple of 8

2012-10-04 Thread Joel Goldstick
On Thu, Oct 4, 2012 at 3:47 PM, Albert-Jan Roskam  wrote:
> Hi,
>
> The function below works, but it's such a kludge! Is there a way to make this 
> more elegant?
> As said in the docstring, I want to round up a given integer to the nearest 
> multiple of 8. I was thinking
> of something like math.ceil.
>
> def _getPadding(charlen):
> """ Helper function to replace null bytes ('\x00') at the end of
> string values. Rounds up  to the nearest multiple of 8.
> Every string value is 8 bytes or a multiple thereof. For example, a
> 5-character string needs a padding of 3 spaces to prevent the
> null bytes
> >>> dict([(charlen, _getPadding(charlen)) for charlen in range(1, 40, 7)])
> {1: 8, 36: 40, 8: 8, 15: 16, 22: 24, 29: 32}
> >>> s = "I love Python"
> >>> s.ljust(_getPadding(len(s)))
> 'I love Python   '
> """
> i = 0
> while True:
> i += 1
> if (i * 8) > charlen:
> return (i * 8) % charlen + charlen if charlen > 1 else 8
> if __name__ == "__main__":
> import doctest
> doctest.testmod()
>
> Thanks!
>
> Regards,
> Albert-Jan
>
>
>>> my_string = "123"
>>> pad = 8 - len(my_string) % 8
>>> my_string = my_string + " " * pad
>>> my_string
'123 '

-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 104, Issue 24

2012-10-04 Thread Aceway
your last for iterater maybe should like this:
for key,values in messages:
if max is None or values>max:
sender=key
max=values




在 2012-10-5,1:13,tutor-requ...@python.org 写道:

> Send Tutor mailing list submissions to
>tutor@python.org
> 
> To subscribe or unsubscribe via the World Wide Web, visit
>http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>tutor-requ...@python.org
> 
> You can reach the person managing the list at
>tutor-ow...@python.org
> 
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>   1. Hello Can someone looked at my problem? stuck (Palice Fan)
> 
> 
> --
> 
> Message: 1
> Date: Tue, 2 Oct 2012 23:39:00 -0400
> From: Palice Fan 
> To: tutor@python.org
> Subject: [Tutor] Hello Can someone looked at my problem? stuck
> Message-ID:
>
> Content-Type: text/plain; charset="windows-1252"
> 
> Hello
> i got stuck with the last bit of my programming practice.
> Can somebody help me?
> Write a program to read through a mail log, and figure out who had the most
> messages in the file. The program looks for ?From? lines and takes the
> second parameter on
> those lines as the person who sent the mail.
> The program creates a Python dictionary that maps the sender?s address to
> the total number of
> messages for that person.
> After all the data has been read the program looks through the dictionary
> using a maximum loop
> (see Section 5.7.2) to find who has the most messages and how many messages
> the person has.
> 
> Enter a file name: mbox-short.txt
> c...@iupui.edu :5
> Enter a file name: mbox.txt
> zq...@umich.edu :195
> 
> Instead of printing off a number beside the email, i got another email and
> i dont know how to fix it.
> -- next part --
> An HTML attachment was scrubbed...
> URL: 
> 
> -- next part --
> A non-text attachment was scrubbed...
> Name: 9.4 stuck.png
> Type: image/png
> Size: 67410 bytes
> Desc: not available
> URL: 
> 
> 
> --
> 
> Subject: Digest Footer
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> --
> 
> End of Tutor Digest, Vol 104, Issue 24
> **
> 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] rounding up to the nearest multiple of 8

2012-10-04 Thread Albert-Jan Roskam
Hi,
 
The function below works, but it's such a kludge! Is there a way to make this 
more elegant?
As said in the docstring, I want to round up a given integer to the nearest 
multiple of 8. I was thinking
of something like math.ceil.
 
def _getPadding(charlen):
    """ Helper function to replace null bytes ('\x00') at the end of
    string values. Rounds up  to the nearest multiple of 8.
    Every string value is 8 bytes or a multiple thereof. For example, a
    5-character string needs a padding of 3 spaces to prevent the
    null bytes
    >>> dict([(charlen, _getPadding(charlen)) for charlen in range(1, 40, 7)])
    {1: 8, 36: 40, 8: 8, 15: 16, 22: 24, 29: 32}
    >>> s = "I love Python"
    >>> s.ljust(_getPadding(len(s)))
    'I love Python   '
    """
    i = 0
    while True:
    i += 1
    if (i * 8) > charlen:
    return (i * 8) % charlen + charlen if charlen > 1 else 8
if __name__ == "__main__":
    import doctest
    doctest.testmod()

Thanks!

Regards,
Albert-Jan


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~ 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Tkinter-discuss] displaying an image

2012-10-04 Thread Matthew Ngaha
> You need to install PIL to use the tutorial you are doing.
>
> http://www.pythonware.com/products/pil/

the site says
"
The current free version is PIL 1.1.7. This release supports Python
1.5.2 and newer, including 2.5 and 2.6. A version for 3.X will be
released later.
"

i have python 3. all the downloads below it only show python 2
versions. am i stuck?:(
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help new to python

2012-10-04 Thread Joel Goldstick
On Wed, Oct 3, 2012 at 11:38 AM,   wrote:
> Hi im new to python and im stuck on my homework. I have to define the
> functions appropriately in the python file so they all test and work but im
> not even sure where to begin or what to I could really use some help. Ive
> attached the file.
>
> Thank you,
>
> Adam
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
So, start defining each function.  You must have done this before this
assignment.
Because many of these functions use a string as the input parameter,
lookup in the python docs about strings, and string methods.

come back with code that works or doesn't.  Include the code in your
reply along with the results and the traceback


-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie help with .pyc

2012-10-04 Thread Steven D'Aprano

On 05/10/12 01:21, tfahey1 wrote:

Hey everyone,

I am a Maya user, so I only come into contact with Python scripting on a
surface level, but I downloaded a python script from a CG website that I
would like to check out but I am getting an error when it is run.



Would you like us to guess what error you are getting? And how you are
trying to run it? I love guessing games!

Nah, actually I'm lying. I hate guessing games. Please tell us exactly how
you are trying to run the file, and show us the EXACT error you get. Copy
and paste the error message.



 The only
file included was a .pyc file. I'm wondering if there should also be a .py
file along with it? Is there anyway I could fix this script to work without
a .py file?


Probably. The way to "fix" it will depend on what error you are getting.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why difference between printing string & typing its object reference at the prompt?

2012-10-04 Thread eryksun
On Wed, Oct 3, 2012 at 11:11 PM, boB Stepp  wrote:
>
> What happens if str() or repr() is not supported by a particular
> object? Is an exception thrown, an empty string returned or something
> else I am not imagining?

The __str__ method inherited from "object" calls __repr__.

For a class, __repr__ is inherited from type.__repr__, which returns
"".

For an instance, __repr__ is inherited from object.__repr__, which returns
"".


If you override __str__ or __repr__, you must return a string. Else
the interpreter will raise a TypeError.


Basic example:

>>> class Test:...

repr of the class:

>>> repr(Test)
""

repr of an instance:

>>> repr(Test())
'<__main__.Test object at 0x958670c>'


> As I go along in my study of Python will it become clear to me when
> and how repr() and str() are being "...used, or implied in many
> places"?

str is Python's string type, while repr is a built-in function that
returns a string suitable for debugging.

You can also call str without an argument to get an empty string, i.e.
str() == ''. This is similar to other built-in types: int() == 0,
float() == 0.0, complex() == 0j, tuple() = (), list() = [], and dict =
{}. The returned value is either 0 or empty -- and boolean False in
all cases.

str also takes the optional arguments "encoding" and "errors" to
decode an encoded string:

>>> str(b'spam', encoding='ascii')
'spam'

bytes and bytearray objects have a decode() method that offers the
same functionality:

>>> b'spam'.decode('ascii')
'spam'

But other objects that support the buffer interface might not. For
example, take the following array.array with the ASCII encoded bytes
of "spam":

>>> arr = array.array('B', b'spam')

Here's the repr:

>>> arr
array('B', [115, 112, 97, 109])

Without an argument str just returns the repr of the array:

>>> print(arr)
array('B', [115, 112, 97, 109])

(The print function calls str.)

But we can tell str to treat the array as an ASCII encoded buffer:

>>> print(str(arr, 'ascii'))
spam
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] modifying lists of lists

2012-10-04 Thread eryksun
On Thu, Oct 4, 2012 at 7:21 AM, Dave Angel  wrote:
>
> This is how eryksun knew that a shallow copy was good enough.  And for a
> shallow copy, using the slice notation is perfect.
>
 J42 = [H[:1]]
 print J42[0]
> [(1, 2)]
 print id(J42[0])
> 13964568
>
> (Note that my shallow copy is not quite what eryksun was using.  His
> lost one level of the nesting, by doing both the subscript and the slice.)
> Now, since the id is different, you won't get the problem you saw first.

>>> H = [[1, 2]]

Copy the list [1,2] at H[0] and nest it in a list:

>>> J = [H[0][:]]
>>> J
[[1, 2]]

Modify the original list:

>>> H[0][1] = H[0][0]
>>> H
[[1, 1]]

The copy is unchanged:

>>> J
[[1, 2]]

Seems OK to me. Then I switched to the Ed's original problem. This
problem no longer uses another named list (J in the above), but it's
similar. Here's H:

>>> H = [[(0, 1), (2, 3)], [(1, 2), (3, 4)]]

The problem is to insert a copy of list H[0] at index 1 of H. At a
minimum it has to be shallow copied because later Ed wants to modify
it (i.e. H[1].pop(1)) without affecting H[0]. Copying H up to index 1
would preserve an undesired nested structure, so you'd have to
subscript, but then the subscripted value would be the original H[0]
list. You actually have to copy H[0], either by slicing with H[0][:],
or calling the list constructor with list(H[0]), or using
copy.copy(H[0]).
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Newbie help with .pyc

2012-10-04 Thread tfahey1
Hey everyone,

I am a Maya user, so I only come into contact with Python scripting on a
surface level, but I downloaded a python script from a CG website that I
would like to check out but I am getting an error when it is run. The only
file included was a .pyc file. I'm wondering if there should also be a .py
file along with it? Is there anyway I could fix this script to work without
a .py file?

Thanks, 

Tim Fahey



--
View this message in context: 
http://python.6.n6.nabble.com/Newbie-help-with-pyc-tp4991028.html
Sent from the Python - tutor mailing list archive at Nabble.com.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] MAXIMUM LOOP LOGIC

2012-10-04 Thread medusa
Hello 

i got stuck with the last bit of my programming practice. 

Can somebody help me?

Write a program to read through a mail log, and figure out who had the most
messages in the file. The program looks for “From” lines and takes the
second parameter on
 those lines as the person who sent the mail.
The program creates a Python dictionary that maps the sender’s address to
the total number of
messages for that person.
After all the data has been read the program looks through the dictionary
using a maximum loop
 (see Section 5.7.2) to find who has the most messages and how many messages
the person has.


Enter a file name: mbox-short.txt
c...@iupui.edu :5
Enter a file name: mbox.txt
 zq...@umich.edu :195

 

Instead of printing off a number beside the email, i got another email and i
dont know how to fix it.
 




--
View this message in context: 
http://python.6.n6.nabble.com/MAXIMUM-LOOP-LOGIC-tp4990842.html
Sent from the Python - tutor mailing list archive at Nabble.com.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why difference between printing string & typing its object reference at the prompt?

2012-10-04 Thread Steven D'Aprano

On 04/10/12 13:11, boB Stepp wrote:


What happens if str() or repr() is not supported by a particular
object? Is an exception thrown, an empty string returned or something
else I am not imagining?


I don't think that is possible, at least not by accident or neglect.
In Python 3, everything inherits from object, which supports both str
and repr, so everything else should too:

py> class MyClass:
... pass
...
py> obj = MyClass()
py> str(obj)
'<__main__.MyClass object at 0xb7c8c9ac>'
py> repr(obj)
'<__main__.MyClass object at 0xb7c8c9ac>'


Not terribly exciting, but at least it tells you what the object is,
and gives you enough information to distinguish it from other, similar,
objects.

I suppose you could write a class that deliberately raised an exception
when you called str() on it, in which case it would raise an exception
when you called str() on it... :) Likewise for repr().


py> class Stupid:
... def __str__(self):
... raise TypeError('cannot stringify this object')
...
py> obj = Stupid()
py> str(obj)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in __str__
TypeError: cannot stringify this object




What larger phrase does "repr" stand for? My text mentions
"representational form" later in the book, which sounds similar in
concept to what you are discussing.



repr is short for "representation", as in "string representation".




As I go along in my study of Python will it become clear to me when
and how repr() and str() are being "...used, or implied in many
places"?


Generally, print and the interactive interpreter are the only implicit
string conversions. At least the only ones I can think of right now...
no, wait, there's another one, error messages.

print() displays the str() of the object. The interactive interpreter
displays the repr() of the object. Error messages could do whatever
they like. Anything else, you have to explicitly convert to a string
using the form you want:

s = repr(x).lower()
t = str(y).replace('ss', 'ß')


or whatever.


--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why difference between printing string & typing its object reference at the prompt?

2012-10-04 Thread Steven D'Aprano

On 04/10/12 13:39, boB Stepp wrote:


But not always. For example:

py>  from decimal import Decimal as D
py>  x = D("1.23")
py>  print(str(x))
1.23
py>  print(repr(x))
Decimal('1.23')


These contrasting examples are very illuminating. So in print(str(x))
the object, D("1.23"), is being converted into a readable string,
which makes the most sense as 1.23. But print(repr(x)) is giving a
string representation of the object as code, which is more than just
1.23, the Decimal('1.23'). Am I understanding this correctly?


Pretty close.

In the example above, the calls to print are only there to avoid
distracting you with the string delimiters, the outer quote marks. It's
str() and repr() that are doing the real work.

Apart from that, you've got it right. str(x) returns a human-readable
version of x, which in this case is "1.23" (excluding the quote marks,
of course). The designer of the Decimal class choose for repr() of a
decimal to look as much as possible like the call to the class that
created the object in the first place. (Or at least an equivalent
call.) In this case, that is "Decimal('1.23')".



Unfortunately, the difference between str() and repr() is kind of
arbitrary and depends on the object. str() is supposed to return a
"human-readable" version of the object, for display, while repr() is
supposed to return a string which would work as code, but those are more
guidelines than hard rules.


Will these fine distinctions be easy for me to pick up on as I
progress in my Python studies? I suspect that I am going to have to
experiment with str() and repr() in each new situation to see what
results.


*shrug* I've been programming in Python for over 10 years, and I still
forget when str() is used and when repr() is used. I always have to check.
But maybe that's just me.

Remember, there is no hard rule that tells you what the output of str()
and repr() must be (apart from strings). Different programmers have
different ideas of what is useful, meaningful, or possible.


[...]

But repr() of a string creates a new string showing the representation
of the original string, that is, what you would need to type in source
code to make that string. That means:

1) wrap the whole thing in delimiters (quotation marks)
2) escaping special characters like tabs, newlines, and binary
characters.


As to point 2), will repr() insert "\" (I am assuming Python uses a
backslash like other languages to escape. I have not read about this
in Python yet.) for these special characters? Will str() do the same?


Yes to repr(), no to str().

Remember, str() of a string is just the same string unchanged. If the
input string contains a newline, the output will also contain a newline:

py> s = "abc" + chr(10) + "def"
py> print(s)
abc
def
py> print(str(s))
abc
def


But repr() will create a new string, and escape any "non-printable"
character (and a few which are printable):

py> print(repr(s))
'abc\ndef'


So this shows us that instead of creating string s as I did above, by
concatenating two substrings and a newline character, I could just as
easily have created it in one go using a \n escape:

py> t = "abc\ndef"
py> s == t
True


Notice too that there is no difference between the two different
flavours of single quote delimiters. Whether you write "a" or 'a'
is entirely a matter of personal preference. Python accepts both to
make it easy to input strings containing quote marks:

s = "this string contains ' a single-quote"
t = 'this string contains " a double-quote'


Such single quote strings must start and end on the same line. On the
other hand, *triple-quote* delimiters """ or ''' are used for
multiline strings. They can extend over multiple lines.


Now, ask me about *raw strings*, and the difference between Unicode
and byte strings :)


--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] modifying lists of lists

2012-10-04 Thread Dave Angel
On 10/03/2012 11:52 PM, Ed Owens wrote:
> You are fundamentally correct about my confusion, though I'm trying to work
> with tuples as the lowest level, which may not be relevant here.
The tuples are an example of an immutable object.  An immutable object
(which contains only immutable objects) may be safely shared without
risk of the kind of problem you're having.  ints would have worked just
as well.

Eryksun  is almost correct, but I'm going to attempt to show you how to
figure it out for yourself, next time.

>
> -Original Message-
> .
>
> py> H = [[1, 2]]
> py> J = [H[0]]
> py> print H
> [[1, 2]]
> py> print J
> [[1, 2]]

Here, if you print id(H[0]) and id(J[0]) you'll see they're the same. 
You've already shown they're lists, and therefore mutable.  Thus, you
have a risk.  H and J are different lists, each containing the same list
as their content.  Also try

>>> H is J
False
>>> H[0] is J[0]
True
>>>

Now, if we go one more level down, to H[0][0], we'll see a tuple.  And
although they're also identical, there's no problem there.

This is how eryksun knew that a shallow copy was good enough.  And for a
shallow copy, using the slice notation is perfect.

>>> J42 = [H[:1]]
>>> print J42[0]
[(1, 2)]
>>> print id(J42[0])
13964568

(Note that my shallow copy is not quite what eryksun was using.  His
lost one level of the nesting, by doing both the subscript and the slice.) 
Now, since the id is different, you won't get the problem you saw first.


-- 

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why difference between printing string & typing its object reference at the prompt?

2012-10-04 Thread Dave Angel
On 10/03/2012 11:11 PM, boB Stepp wrote:
> Thanks to all who responded.
> .
> What happens if str() or repr() is not supported by a particular
> object? Is an exception thrown, an empty string returned or something
> else I am not imagining?

Let's try it and see:

>>> class A:pass
...
>>> a = A()
>>> a
<__main__.A object at 0x16ae790>

This is generic information about an object with no methods at all, and
in particular without a __repr__ method.  It identifies the module where
the class was defined, the name of the class, and the address the
particular instance happens to be located at.  (In CPython, that happens
to be identical to id(a).  I'd be happier if it would just identify the
number as the id, since ordinarily, the address is of no use.   BTW, as
far as I know, there's no promise as to how this is formatted, so I
wouldn't try to parse it with a program.

>> 
>> What larger phrase does "repr" stand for? My text mentions
>> "representational form" later in the book, which sounds similar in
>> concept to what you are discussing.

That would be my guess.  I don't recall seeing anything about it.



-- 

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor