Re: [Tutor] the binary math "wall"

2010-04-20 Thread Jerry Hill
On Tue, Apr 20, 2010 at 12:58 PM, Lowell Tackett
 wrote:
> Any of Python's help-aids that I apply to sort things out, such as formatting 
> (%), or modules like "decimal" do nothing more than "powder up" the display 
> for visual consumption (turning it into a string).  The underlying float 
> value remains "corrupted", and any attempt to continue with the math adapts 
> and re-incorporates the corruption.

Using the decimal module does not convert anything to strings.  The
decimal module gives you floating point arithmetic with base 10 rather
than base 2.

You examples seem to work okay for me using decimals:

IDLE 2.6.4
>>> import decimal
>>> n = decimal.Decimal("18.15")

>>> n
Decimal('18.15')

>>> print n
18.15

>>> divmod(n, 1)
(Decimal('18'), Decimal('0.15'))

>>> divmod(divmod(n, 1)[1]*100, 1)[1]/decimal.Decimal("0.6")
Decimal('0.0')

If you need to avoid floating point calculations entirely, you might
try the fractions module (new in python 2.6):

>>> import fractions
>>> n = fractions.Fraction("18.15")

>>> n
Fraction(363, 20)

>>> print n
363/20

>>> divmod(divmod(n, 1)[1]*100, 1)[1]/fractions.Fraction("0.6")
Fraction(0, 1)

>>> print divmod(divmod(n, 1)[1]*100, 1)[1]/fractions.Fraction("0.6")
0

and if you need to convert to float at the end:

>>> float(divmod(divmod(n, 1)[1]*100, 1)[1]/fractions.Fraction("0.6"))
0.0
>>>

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


Re: [Tutor] smtplib help required

2010-04-23 Thread Jerry Hill
On Fri, Apr 23, 2010 at 6:41 PM, James Chapman  wrote:
> Hi there gurus and everyone else. This is my first post to this group, and
> I'm turning here because I'm stumped and search engines are not helping.
> I've used smtplib for a few things already and while wanting to use it again
> today, I'm having weird things happen.

> 
> srv1:~/python# ./email.py
> Traceback (most recent call last):
>   File "./email.py", line 3, in 
>     import smtplib
>   File "/usr/local/lib/python2.6/smtplib.py", line 46, in 
>     import email.utils
> ImportError: No module named utils
> 

You've named your script email.py, which is shadowing the email
package from the standard library.

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


Re: [Tutor] Using Regex to produce text

2010-04-28 Thread Jerry Hill
On Wed, Apr 28, 2010 at 2:27 AM,   wrote:
> Is there an way of using the regex patterns to produce text, instead of 
> matching it?

There have been some previous discussions about generating all of the
possible matches for a given regular expressions.  I believe these are
the first messages in a couple of recent threads on python-list:

http://mail.python.org/pipermail/python-list/2010-February/1235120.html
http://mail.python.org/pipermail/python-list/2010-March/1240605.html

There's at least one sample implementation using the pyparsing library here:
http://pyparsing.wikispaces.com/file/view/invRegex.py

This message appears to have another implementation, sent to the list
as attachments:
http://mail.python.org/pipermail/python-list/2010-April/1240687.html

I haven't tried any of them myself, but they may be useful to you if
you really need to go down this road.

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


Re: [Tutor] Problems installing

2010-06-30 Thread Jerry Hill
On Wed, Jun 30, 2010 at 1:35 AM, Andrew Martin wrote:

> I just downloaded Python 2.6.5 onto my windows vista laptop. I am
> attempting to install "escript version 3: Solution of Partial Differential
> Equations (PDE) using Finite Elements (FEM)." I downloaded the files and
> manually placed them in their appropriately place on my computer according
> to the ReadMe file. However, when I try to import escript, I get an error:
>

I know nothing about escript, but according to the install doc on
https://launchpad.net/escript-finley/, it requires python 2.5.4.  The
distribution appears to consist entirely of .pyc files, so I think you need
to install the version of python that it requires.

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


Re: [Tutor] A unicode print question

2010-07-30 Thread Jerry Hill
On Fri, Jul 30, 2010 at 1:33 PM, Joel Goldstick wrote:

> I was reading this: http://diveintopython.org/xml_processing/unicode.html
>
> and tried the exercise:
>


> But oddly enough, when I typed it into my python shell I did NOT get the
> UnicodeError, and I wonder why not:
>

I believe that python is checking the encoding for stdout.  Try this:

print sys.stdout.encoding

When you attempt to print a unicode string, python will attempt to encode it
based on what it autodetected about your terminal.

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


Re: [Tutor] access class through indexing?

2010-08-04 Thread Jerry Hill
On Wed, Aug 4, 2010 at 4:17 PM, Alex Hall  wrote:

> Hi all,
> Further to my questions about overriding builtin methods earlier, how
> would I make a class able to be accessed and changed using index
> notation? For example, take the following:
> deck=CardPile(52) #creates a new deck of cards
> print(len(deck)) #prints 52, thanks to my __len__ function
> for c in deck: print c #also works thanks to __iter__
> print(deck[4]) #fails with a list index out of range error
> How would I get the last one working? I tried __getattr__(self, i),
> but it did not work. I want to be able to get an arbitrary item from
> the "pile" of cards (which can be a deck, a hand, whatever), and/or
> set an element. A "pile" is just a list of Card objects, so I would
> only need to use sequence indexing, not mapping functions.
>

Implement __getitem__(self, key) (See
http://docs.python.org/reference/datamodel.html#emulating-container-types )

If you want to support slicing (access like deck[0:10]), you'll need to
handle getting a slice object as the key in addition to accepting an integer
key.

If a pile is really "just" a list of cards, you may want to look into
inheriting from list instead of re-implementing all of the functionality on
your own.

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


Re: [Tutor] access class through indexing?

2010-08-04 Thread Jerry Hill
On Wed, Aug 4, 2010 at 5:28 PM, Alex Hall  wrote:

> Here is my init, not half as pretty as yours, but it should work.
> Maybe this will explain the problem.
>
> def __init__(self, size, cards=None, fill=False):
>  #creates a pile of cards. If "fill"==true, it will auto-fill the
> pile starting from the Ace of Clubs up through the King of Spades,
> stopping if it exceeds the size arg.
>  #if the cards arg is not null, it will populate the pile with the
> cards in the list.
>  self=[]
>

This is the problem.  You cannot re-assign self inside the __init__ method
(or any method, for that matter).  Well, you can, but it doesn't do what you
expect.  All you're doing is shadowing the self that gets passed in to the
function, not changing it.

Just call list.__init__(self) to initialize self using the initialized from
the list class.



>  if fill: #auto-fill, useful to generate a new, unshuffled deck
>   for i in range(1, 14):
>for j in range(1, 5):
> self.append(Card(i, j))
>#end for
>   #end for
>   self=self[:size] #keep only the amount specified
>

The same thing goes on here, you can't re-assign self.  Instead, you can
alter it in place by doing self[:] = self[:size].  That's called slice
assignment.  There's some discussion of this here:
http://docs.python.org/release/2.5.2/ref/assignment.html and
http://docs.python.org/library/stdtypes.html#mutable-sequence-types



>  elif cards is not None: #fill the pile with the cards
>   for c in cards:
>self.append(c)
>   #end for
>  #end if
>  #end def __init__
>


I don't have a Card class built, but here's an example that uses tuples
instead:

class Pile(list):
def __init__(self, size=52, cards=None, fill=False):
list.__init__(self) #Initialize self as an empty list
if fill:
for i in range(1, 14):
for j in range(1, 5):
self.append((i,j))
self[:] = self[:size]
elif cards is not None:
for c in cards:
self.append(c)

I think that supports all the same things you had in your example.

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


Re: [Tutor] Questions regarding strings

2010-08-09 Thread Jerry Hill
On Sun, Aug 8, 2010 at 1:04 PM, Daniel  wrote:
>
> Can someone please explain this to me? Thank you so much and I wish everyone 
> a great day!

Beyond what Hugo mentioned in his message, take a look at the tutorial:
http://docs.python.org/tutorial/introduction.html#strings

I don't see a way to directly link to the section about subscripting
and slicing strings, but it's a bit below that link, and starts with
"Strings can be subscripted (indexed); like in C, the first character
of a string has subscript (index) 0"

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


Re: [Tutor] Elementtree and pretty printing in Python 2.7

2010-08-22 Thread Jerry Hill
On Fri, Aug 20, 2010 at 3:49 AM, Knacktus  wrote:
> Hi guys,
>
> I'm using Python 2.7 and the ElementTree standard-lib to write some xml.
>
> My output xml has no line breaks! So, it looks like that:
>
> 
>
> instead of something like this:
>
> 
>    
> 
>
> I'm aware of lxml which seems to have a pretty print option, but I would
> prefer to use the standard-lib ElementTree which seems not to have a feature
> like this.
>
> Do I miss something using the ElementTree-lib or is it bug?

Neither, as far as I know.  The XML you get is perfectly valid XML.
If you want to pretty print it, there's a recipe here:
http://effbot.org/zone/element-lib.htm#prettyprint, but I don't think
it's been included in the standard library yet.

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


Re: [Tutor] function with multiple checks

2010-09-27 Thread Jerry Hill
On Mon, Sep 27, 2010 at 11:09 AM, Tim Miller  wrote:
> I've got a small function that I'm using to check whether a password is of a
> certain length and contains mixed case, numbers and punctuation.
>
> Originally I was using multiple "if re.search" for the patterns but it
> looked terrible so I've read up on list comprehensions and it's slightly
> improved. I just can't escape the feeling that there's a more elegant way to
> do this that I'm missing.
>
> I've been looking through all the python stuff that I thought might be
> relevant (lambda, map, filter, set, frozenset, etc) but nothing has come
> together. Just wondering if anyone has suggested reading material for
> alternate ways they'd handle this code.

The way you've written it obviously works fine.  That being said, I'd
probably do something like this:

from string import ascii_lowercase, ascii_uppercase, digits, punctuation

def complex_password(password):
'''Checks to make sure a password is complex'''
checks = [
lambda p: len(p) > 12,
lambda p: any(c in punctuation for c in p),
lambda p: any(c in digits for c in p),
lambda p: any(c in ascii_uppercase for c in p),
lambda p: any(c in ascii_lowercase for c in p),
]

return all(check(password) for check in checks)

if __name__ == '__main__':
passwords = ['password', 'Password1234567', 'Password1.234567']
for password in passwords:
print password, complex_password(password)


In the complex_password function, I create a list of tests, each of
which is a function that returns either true or false.  In this case I
used lambdas to create the function objects, since all the tests
easily fit on a single line, but it would be fine to define a function
elsewhere and use it in the list if you had more complicated checks to
do.

all() is a built in function that returns True if all of the elements
in an iterable are true (or the iterable is empty), and otherwise
returns False.  That seems like an ideal way to execute a bunch of
tests and return True if all of them pass, and otherwise return false.
 In this case, the iterable is a generator expression that evaluates
each of the rules with the supplied password.

any() is similar, but it returns True if any member of the iterable is True.

Looking back at it, I probably should have used longer variable names
in my rules, which would have made them a bit easier to read.  When I
was writing them, I was worried about the lines getting too long with
longer names.  It didn't turn out to be a problem though.

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


Re: [Tutor] 'pydoc' is not recognized as an internal or external command, ...

2010-11-12 Thread Jerry Hill
On Fri, Nov 12, 2010 at 6:44 PM, Steven D'Aprano  wrote:
> Use the Find File command, and see if you can find something called "pydoc".
> You may need to call the full path to the program, e.g.:
>
> C:\My Documents\path\to\program\pydoc raw_input

On my windows PC, it's c:\Python31\Lib\pydoc.py

So, to do what the tutorial is suggesting, you would need to open a
command prompt (cmd.exe) and run:
c:\Python31\Lib\pydoc.py raw_input

Note: Since I have python 3.1 installed, that wouldn't actually work,
because python 3.1 no longer has a raw_input function -- it's been
renamed to just input.

If you want to be able to run pydoc.py without specifying the full
path every time, I could add C:\Python31\Lib to my PATH environment
variable.

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


Re: [Tutor] New Issues with REGEX Greediness:

2009-08-03 Thread Jerry Hill
On Sun, Aug 2, 2009 at 2:55 PM, gpo wrote:
>
> Python:
> line='>Checking Privilege for UserId:
> {874BE70A-194B-DE11-BE5C-000C297901A5}, PrivilegeId: {prvReadSdkMessage}.
> Returned hr = 0'
> (re.search('(\w+)\:.+.{8}-.{4}-.{4}-.{4}-.{12}',line)).group(0)
> RESULT
> 'UserId: {874BE70A-194B-DE11-BE5C-000C297901A5'
>
> How/Why are these results different?  What is Python doing differently in
> regex, that I need to adjust to?

The group(0) method returns the entire portion of the string that
matched your regex.  Group(1) gives you what you want -- the portion
that matched the first parenthesized capture group:

>>> import re
>>> line='>Checking Privilege for UserId: 
>>> {874BE70A-194B-DE11-BE5C-000C297901A5}, PrivilegeId: {prvReadSdkMessage}. 
>>> Returned hr = 0'

>>> (re.search('(\w+)\:.+.{8}-.{4}-.{4}-.{4}-.{12}',line)).group(0)
'UserId: {874BE70A-194B-DE11-BE5C-000C297901A5'

>>> (re.search('(\w+)\:.+.{8}-.{4}-.{4}-.{4}-.{12}',line)).group(1)
'UserId'
>>>

The section of the docs on the group method of MatchObjects may be
helpful: http://docs.python.org/library/re.html#re.MatchObject.group

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


Re: [Tutor] Simple regex replacement match (converting from Perl)

2009-09-04 Thread Jerry Hill
On Fri, Sep 4, 2009 at 1:34 PM, GoodPotatoes wrote:
> I simply want to remark out all non-word characters read from a line.
>
> Line:
> Q*bert says "#...@!$%  "
>
> in Perl
> #match each non-word character, add "\" before it, globally.
>
> $_=s/(\W)/\\$1/g;
>
> output:
> Q\*bert\ says\ \"\...@\!\$\%\ \ \"  #perfect!
>
> Is there something simple like this in python?
>
> I would imagine:
> foo='Q*bert says "#...@!$%  "'
> pNw=re.compile('(\W)')
> re.sub(pNw,'\\'+(match of each non-word character),foo)
>
> How do I get the match into this function?  Is there a different way to do
> this?

Like this:

>>> import re
>>> line = 'Q*bert says "#...@!$%  "'
>>> pattern = re.compile(r"(\W)")

>>> re.sub(pattern, r"\\\1", line)
'Q\\*bert\\ says\\ \\"\\...@\\!\\$\\%\\ \\ \\"'

Note that line is showing the single backslashes doubled up, because
it's the repr of the string.  If you print the string instead, you'll
see what you expect:

>>> print re.sub(pattern, r"\\\1", line)
Q\*bert\ says\ \"\...@\!\$\%\ \ \"

>>>

When you're using re.sub, \1 is the value of the first match.  It's
also helpful to use raw strings when you're using the python re
library, since both python and the regular expression library use '\'
as an escape character.  (See the top of
http://docs.python.org/library/re.html for more details).

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


Re: [Tutor] Which version to start with?

2009-10-06 Thread Jerry Hill
On Tue, Oct 6, 2009 at 8:59 AM, Ken G.  wrote:
> I am just starting on Python 2.6.2 on Ubuntu 9.04 and I am slightly confused
> with the numerous tutorials and books available for learning the language.
> Is there any good recommendation for a good but easy tutorial on the
> Internet to learn Python?

I'm fond of the official python tutorial: http://docs.python.org/tutorial/

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


Re: [Tutor] Curses - What does it do and why is it called this?

2009-10-22 Thread Jerry Hill
On Tue, Oct 13, 2009 at 3:11 AM, Katt  wrote:
> Now I understand.  Makes sense.  If "Curses" is for UNIX what would I use on
> a Windows XP system using Python 2.6.2?

I like the Console package:
http://effbot.org/zone/console-index.htm

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


Re: [Tutor] Still having trouble with my game of life algorithm

2007-05-25 Thread Jerry Hill
On 5/25/07, Matt Smith <[EMAIL PROTECTED]> wrote:
> def update_matrix(matrix):
> matrix_updated = matrix

That line assigns the name matrix_updated to the same list-of-lists as
matrix.  Since lists are mutable objects, changing matrix_updated is
also changing matrix.  What you need is to bind matrix_updated to a
new copy of matrix instead.

At the top of your code add:
from copy import deepcopy

and replace the first line of update_matrix() with:
matrix_updated = deepcopy(matrix)

After making that change, your code appears to run beautifully!

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


Re: [Tutor] creating a buffer object from a file ?

2007-05-31 Thread Jerry Hill
On 5/31/07, Iyer <[EMAIL PROTECTED]> wrote:
> I think this got lost among the threads:

I think it got lost because you haven't given us enough information to
answer your question.

> in reality what is a buffer object used for ? reading
> a file itself creates a string as in itself,

We don't know.  Your original email said you needed a buffer object,
but didn't tell us why.  As a consequence, the only one who knows why
you need one is you.  Perhaps if you actually showed us some code, or
mentioned what library you were using that required a buffer object?

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


Re: [Tutor] back on bytes

2007-07-06 Thread Jerry Hill
On 7/6/07, shawn bright <[EMAIL PROTECTED]> wrote:
> i have a number 12480
> i have a low byte of 192 and a high byte of 176

Maybe I'm being dense, but that doesn't make any sense at all to me.
The high byte of 12480 is 48, and the low byte is 192, isn't it?
Because (48 * 256) + 192 = 12480?

In your formula ( (176 & 127) * 256 + 192 ) you're only using 7 bits
of your high byte.  Why are you masking off that last bit?  And if you
mask it off, how do you expect to recover it going the other
direction?  I suppose for this particular example, the following would
work, but it doesn't seem like what you really are after:

>>> n = 12480
>>> low_byte = n & 0xFF
>>> low_byte
192
>>> hi_byte = n >> 8
>>> hi_byte
48
# Add the extra bit back in that was masked off
>>> hi_byte = hi_byte+128
>>> hi_byte
176
>>>

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


Re: [Tutor] How to determine if every character in one string is in another string?

2007-07-20 Thread Jerry Hill
On 7/20/07, Terry Carroll <[EMAIL PROTECTED]> wrote:
> Is there a straightforward way to find out if all characters in one string
> are present in a second string?

I like this one:
all(char in string.printable for char in testString)

>>> testString = "qwerty\buiop"
>>> all(char in string.printable for char in testString)
False

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


Re: [Tutor] How to determine if every character in one string is inanother string?

2007-07-22 Thread Jerry Hill
On 7/21/07, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > all(char in string.printable for char in testString)
>
> What is all?
> Is that a 2.5 thing (I'm still on 2.4 here)

Yes, it's a 2.5 thing.  All returns true if all of the elements of an
iterable are true.  According to the docs, it is the equivalent of the
following:

 def all(iterable):
 for element in iterable:
 if not element:
 return False
 return True

Using 'all' with a generator expression has the virtue of only needing
to look at the string until it finds a single element that is false,
and then returning.  Not only that, it's concise (a single line) and
quite readable (at least to me).

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


Re: [Tutor] Quick question

2007-09-21 Thread Jerry Hill
On 9/21/07, Tino Dai <[EMAIL PROTECTED]> wrote:
> Is there a more pythonic way of doing this:
>
>   if queuePacket.has_key('procSeq') and \
>   queuePacket.has_key('opacSeq') and \
>   queuePacket.has_key('keySeq') and \
>   len(queuePacket['procSeq']) == 0 and \
>   len(queuePacket['opacSeq']) == 0 and \
>  len(queuePacket['keySeq']) == 0:

Assuming we're talking about Python 2.5 or greater I find the
following pretty readable:

all(queuePacket.has_key(k) for k in ('procSeq', 'opacSeq', 'keySeq')) and \
all(len(queuePacket[k])==0 for k in ('procSeq', 'opacSeq', 'keySeq'))

If you're not familiar with how those work, they use generator
expressions, which are very similar to list comprehensions.  See PEP
289 [1] for more information on generator expressions, and either the
tutorial [2] or PEP 202 [3] for more on list comprehensions.

1: http://www.python.org/dev/peps/pep-0289/
2: http://docs.python.org/tut/node7.html#SECTION00714
3: http://www.python.org/dev/peps/pep-0202/

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


Re: [Tutor] how to accept an integer?

2007-12-05 Thread Jerry Hill
On Dec 5, 2007 4:01 PM, Mahesh N <[EMAIL PROTECTED]> wrote:
> I dun understand the mistake. My aim is to accept an integer number. The
> python lookup in IDLE asks for a string object but the interpreter returns
> with the following error message. Some one pls explain.
> Thank You
>
>  PS : I understand that i can do type conversion after getting input thru
> raw_input(). But how does input() function work?
>
> >>> prompt="temme a number\n"
> >>> speed =input(prompt)
>
>  Traceback (most recent call last):
>   File "", line 1, in 
> speed =input(prompt)
> TypeError: 'str' object is not callable

You have code that you haven't shown us.  My crystal ball tells me
that somewhere above this point you did input = "Some String", thus
shadowing the builtin input function.  Start a new interpreter and try
again and you should find that it works as expected.

As I'm sure you'll hear from others, it really is best to use
raw_input instead.  If you want an integer instead of a string, do
something like this:

speed = int(raw_input(prompt))

That way whatever the user types isn't run as python code, just read
in as a string and then converted into an integer.

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


Re: [Tutor] how to accept an integer?

2007-12-05 Thread Jerry Hill
On Dec 5, 2007 4:46 PM, Bryan Fodness <[EMAIL PROTECTED]> wrote:
> On Dec 5, 2007 4:16 PM, Jerry Hill <[EMAIL PROTECTED]> wrote:
> > speed = int(raw_input(prompt))
>
>
> Is this how ALL known integers should be input?

I don't think I understand the question.  If you are prompting your
user to enter an integer from the console, then yes, this is the
general way you should do it, probably wrapped in a try/except block.

You certainly don't have to do it all in one line like that.  Instead,
you could split it up into component parts, like this:

prompt = "Please enter a number between 1 and 10:\n"
user_input = raw_input(prompt)
try:
user_number = int(user_input)
except ValueError:
print "You did not enter a number."

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


Re: [Tutor] Translate this VB.NET code into Python for me?

2008-03-04 Thread Jerry Hill
On Tue, Mar 4, 2008 at 8:05 AM, Dick Moores <[EMAIL PROTECTED]> wrote:
>  By the second chapter I've begun to suspect that GUIs aside, Python
>  is a lot simpler to write. Could someone prove that to me by
>  translating the code I've pasted at
>   (from pp. 51-54 of the
>  book), which prints

This code is pretty straightforward to translate into python.  It's
pretty short so, I've pasted it inline:

import sys

class Dog(object):
def __init__(self, name, sound="barks"):
self.name = name
self.sound = sound
def bark(self):
print "%s %s" % (self.name, self.sound)
def do_your_thing(self):
raise NotImplementedError

class Rottweiler(Dog):
def do_your_thing(self):
print "%s snarls at you in a menacing fashion." % self.name

class Spaniel(Dog):
def do_your_thing(self):
print "%s licks you all over, then drools on you." % self.name

if __name__ == "__main__":
butch = Rottweiler("Butch")
mac = Spaniel("Mac", "yips")

butch.bark()
mac.bark()

butch.do_your_thing()
mac.do_your_thing()
sys.stdin.readline()

It's probably more pythonic to not define the Dog.do_your_thing()
method at all than to raise the NotImplementedError, but I think that
this way mirrors the VB code a bit better.  I don't think there's a
good way to mark the entire Dog class as abstract in python, which I
think is what the VB code does with the "MustInherit Class Dog" line.

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


Re: [Tutor] Function for converting ints from base10 to base2?

2007-02-21 Thread Jerry Hill
On 2/21/07, Dick Moores <[EMAIL PROTECTED]> wrote:
> But there's syntax(?) there I've never seen before. "['','-'][n<0]".
> I see it works:
>
>  >>> n = -6
>  >>> ['','-'][n<0]
> '-'
>  >>> n = 98
>  >>> ['','-'][n<0]
> ''
>
> What's this called? I'd like to look it up.

['', '-'] is a list with two elements: an empty string, and the string '-'.
[n<0] is an index into the list.

For example:
>>> a = ['First Element', 'Second Element']
>>> a[False]
'First Element'
>>> a[True]
'Second Element'

This works because int(True) is 1 and int(False) is 0.  Personally, I
find using boolean values to index a list to be hard to read.  If I
ever came back to looking at the code again, I'd rather have written
something like this:

sign = ''
if (n < 0): sign = '-'

It's an extra line of code, but it's a lot less cryptic to me.

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


Re: [Tutor] FW: isinstance -> instance

2007-02-26 Thread Jerry Hill
On 2/26/07, Bernard Lebel <[EMAIL PROTECTED]> wrote:
> That's fine, but that tells me that 'a' is an instance of 'A'.
> It doesn't, however, tell me if 'a' is an instance or the actual class object.

It doesn't?

>>> class A:
pass

>>> a = A()
>>> isinstance(a, A)
True
>>> isinstance(A, A)
False

If you want to know if a is an instance of any type, try this:
>>> import types
>>> isinstance (a, types.InstanceType)
True

I'm pretty sure that types.InstanceType only works on old-style
classes.  I believe you can check for an instance of a new-style class
with:
isinstance(a, object)

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


Re: [Tutor] Matching string

2007-02-27 Thread Jerry Hill
On 2/27/07, govind goyal <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I want to use a pattern matcing (regular expression) inside "if loop" such
> that if it will find "MBytes" and "Mbits/sec" both at a time  regardless of
> there position in a particular string ,then only it executes code inside "if
> block".


Something like this, perhaps?
>>> myStrings = ["[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec
2.345 ms0/  850 (0%)",
 "Server listening on UDP port 5001"]
>>> for myString in myStrings:
if ("MBytes" in myString and "Mbits/sec" in myString):
print myString

prints:
[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec  2.345 ms0/  850 (0%)

Nothing in your example calls for the use of regular expressions, so I
didn't use them.

If you need to use a regular expression to extract the numeric portion
you could do something like this to extract the values you want once
you've identified the strings you need.

import re

myStrings = ["[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec  2.345
ms0/  850 (0%)",
 "Server listening on UDP port 5001"]

mb_re = re.compile(r'(\d+\.{0,1}\d*) MBytes')
mbps_re = re.compile(r'(\d+\.{0,1}\d*) Mbits/sec')

for myString in myStrings:
if ("MBytes" in myString and "Mbits/sec" in myString):
print myString
mb = mb_re.findall(myString)[0]
mbps = mbps_re.findall(myString)[0]
print "MBytes:", mb
print "Mbits/sec:", mbps


prints:
[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec  2.345 ms0/  850 (0%)
MBytes: 1.19
Mbits/sec: 10.0

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


Re: [Tutor] howto call DOM with python

2007-02-28 Thread Jerry Hill
On 2/28/07, Ismael Farfán Estrada <[EMAIL PROTECTED]> wrote:
> I was wondering wheter someone knows how to use python to write
> a client-side scripts like if it were java

I don't think this is possible, at least without creating a
custom-compiled version of Firefox.

There's a little bit of discussion from last year on the python
mailing list here:
http://mail.python.org/pipermail/python-list/2006-November/415805.html

There's some more information available out there if you search for
PyXPCOM or python and nsdom.  If you do end up getting it working, I
would be interested in hearing how it went.

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


Re: [Tutor] Regular expressions - Ignoring linefeeds

2007-03-02 Thread Jerry Hill
On 3/2/07, doug shawhan <[EMAIL PROTECTED]> wrote:
> I've been looking through various sites, but cannot find the magic button
> that allows me to match a string with linefeeds
> I'd rather not strip out the linefeeds, then stick them back in. :-)

Try this:

>>> s = '''Good gravy! Hi there.
I'm some text someone
wants to match.
Bye there. See you around'''

>>> snippy = re.compile('Hi there.*Bye there.', re.DOTALL)

>>> yeild = re.search(snippy, s)

>>> yeild.group()
"Hi there.\nI'm some text someone\nwants to match.\nBye there."

The important bits are compiling your regular expression with
re.DOTALL so that a dot will match newlines, and using re.search
instead of re.match.

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


Re: [Tutor] White spaces in a path (from a string variable) and os.popen on Windows

2007-03-08 Thread Jerry Hill
On 3/8/07, learner404 <[EMAIL PROTECTED]> wrote:
> When I know exactly the path in advance I use a raw string r' ' and I add
> double quotes where necessary to avoid the white spaces syndrome. But I
> don't see how to do this "easily" when my path is a string variable given by
> my GUI (like C:\Documents and Settings\name\Mes documents)

You can just choose to always quote the directory name where it might
have spaces in it.  For instance, change this line:
> result=os.popen("dir "+dirPath).read()
to this:
result=os.popen('dir "%s"' % dirPath).read()

That worked fine with all the directories I threw at it.

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


Re: [Tutor] Finding the minimum value in a multidimensional array

2007-03-13 Thread Jerry Hill
On 3/13/07, Geoframer <[EMAIL PROTECTED]> wrote:
> I don't see a solution here... It is not conclusive on what's the minimum
> for an array.
>
> ln [1]: import numpy
>  In [2]: a =
> numpy.array([[1,2,3,0],[2,3,4,5],[6,5,4,3],[-1,2,-4,5]])

Well, what exactly is it that you'd like the answer to be?  The
samples page Eike pointed you to show a couple of ways to do it,
depending on exactly what piece of data you're looking for.  Here's a
bit more along the same lines.  If this doesn't help, perhaps you
could show us a bit of sample data and tell us exactly what answer
you'd like to extract.

>>> a = numpy.array([[1,2,3,0],[2,3,4,5],[6,5,4,3],[-1,2,-4,5]])
>>> a.argmin()
14
>>> a.ravel()[14]
-4
>>> divmod(14, 4)
(3, 2)
>>> a[3][2]
-4

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


Re: [Tutor] fine in interpreter, hangs in batch

2007-03-16 Thread Jerry Hill
On 3/16/07, Switanek, Nick <[EMAIL PROTECTED]> wrote:
> After creating a list of words ('wordlist'), I can run the following
> code in the interactive window of PythonWin in about ten seconds. If I
> run the script containing the code, the script seems to hang on the
> loop. I'd be grateful for help as to why; I often seem to have something
> that works in the interpreter, but not when I run the script.

I'm not sure what you mean by 'seems to hang'.  The code that you
posted isn't complete enough to run (since you didn't provide a
definition of wordlist), and just generates a NameError exception.

Beyond that, I don't understand what the code is supposed to produce
for output.  As written, you generate a list in your loop and assign
it to the name ngrams, but never do anything with that list.  Since
you're inside a for loop, your ngrams name is overwritten the next
time you run through the loop.  You also generate a string with the
statement "Finished the %d-gram list." % n, but you don't do anything
with it.  You probably want to either print it, or assign it to a
variable to print later.

Something like this:

wordlist = ['apple', 'orange', 'pear', 'banana', 'coconut']
N = [2,3,4,5]
ngramlist = [wordlist]
for n in N:
   ngrams = [' '.join(wordlist[i:i+n]) for i in range(len(wordlist)-n+1)]
   print "Finished the %d-gram list." % n
   print ngrams

produces the following output when run as a script:

Finished the 2-gram list.
['apple orange', 'orange pear', 'pear banana', 'banana coconut']
Finished the 3-gram list.
['apple orange pear', 'orange pear banana', 'pear banana coconut']
Finished the 4-gram list.
['apple orange pear banana', 'orange pear banana coconut']
Finished the 5-gram list.
['apple orange pear banana coconut']

Does that help?

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


Re: [Tutor] fine in interpreter, hangs in batch

2007-03-19 Thread Jerry Hill
On 3/19/07, Switanek, Nick <[EMAIL PROTECTED]> wrote:
> Thanks very much for your help.
>
> It appears that the step that is taking a long time, and that therefore
> makes me think that the script is somehow broken, is creating a
> dictionary of frequencies from the list of ngrams. To do this, I've
> written, for example:

Well, if you're guessing which part of your code is slow, you should
profile your code so you can stop guessing.  Python has some very
useful built in profiling tools, documented here:
http://docs.python.org/lib/profile.html

Take a look at the "Instant User's Manual", which should be enough to
get you started. Once you can see exactly which parts of your code are
taking the longest, then you'll know what the best targets are for
optimization.

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


Re: [Tutor] Writing dictionaries to a file

2008-04-07 Thread Jerry Hill
On Mon, Apr 7, 2008 at 1:09 PM, Jerrold Prothero <[EMAIL PROTECTED]> wrote:
> Relevant Python 2.5 documentation sections are 9.1.1 and 9.1.4. My
> question boils down to this: what does writerows want as an argument
> for a dictionary?

A list of dictionaries. One dictionary for each row you would like to
output.  If you want to write out a single row, you can pass a single
dictionary to writerow() instead of using writerows().

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


Re: [Tutor] Doubts about Pylint

2008-04-09 Thread Jerry Hill
On Wed, Apr 9, 2008 at 12:43 PM, Dick Moores <[EMAIL PROTECTED]> wrote:
> I'd never used Pylint until yesterday, when I discovered that Ulipad
>  had a Pylint plugin that enabled me to run Pylint on scripts within
>  Ulipad. But I'm wondering about some of the results. I noticed that
>  it was complaining that my variable names violated convention. Here's
>  an image of running Pylint on a script with only 7 lines:
>  
>
>  Since when is 'az' a bad variable name? And 'AZ' is OK?

Note: I've never used pylint before, so this is all speculation based
on a bit of reading of the pylint web page[1] and PEP 8 [2].

In your code snippet, az is a global variable.  Pylint has a regular
expression that determines if a global variable name matches your
coding convention.  By default, that regex is
(([A-Z_][A-Z1-9_]*)|(__.*__))$.  At a guess, that's because pylint's
author believes the only global variables you should have are
psuedo-constants, and that they should have all uppercase names.  That
seems reasonable to me, if a bit strict.  That particular check does
not line up with the PEP 8 coding conventions, which just suggest that
global variables follow the same naming rules as functions.

I haven't gone through pylint in a lot of detail, but it looks like
most of the other regular expressions are designed to default to the
PEP 8 coding style conventions, or something close to them.  If your
coding conventions are different from the defaults pylint assumes,
you'll probably need to do some setup.

>  And I tried Pylint on an official Python module file, calendar.py.
>  Look what I got when all the checkboxes are
>  checked!!: 
>
>  Comments?

Most of that looks like valid complaints about calendar.py.  The one
exception that jumps out at me is the warning about a relative import
from __future__.  At lot of the other warnings probably depend on the
context.  For instance, the single-character variable names are ugly,
but if they're used inside a loop or a list comprehension they are
probably fine.

Other than the fact that it's a long list, did *you* have any
comments?  You present this list like it's a bad thing, but it seems
to me that pylint is doing exactly what it should.  Do you think that
there's something wrong with pylint?  Are you just surprised that
calendar.py doesn't adhere to pylint's coding guidelines?

1: http://www.logilab.org/card/pylintfeatures
2: http://www.python.org/dev/peps/pep-0008/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehensions

2008-04-09 Thread Jerry Hill
On Wed, Apr 9, 2008 at 7:12 AM, Dinesh B Vadhia
<[EMAIL PROTECTED]> wrote:
> I want to replace the for loop with a List Comrehension (or whatever) to
> improve performance (as the data list will be >10,000].  At each stage of
> the for loop I want to print the result ie.

List comprehensions are for building lists, not consuming them.  If
you want to do something with every element in a list, other than
building a new list with it, you should be using a for loop.

> [print (item + "\n")  for item in data]
>
> But, this doesn't work as the inclusion of the print causes an invalid
> syntax error.
>
> Any thoughts?

Don't do this.

Perhaps you could share a small piece of code that you think is too
slow, and ask for advice in speeding it up?  If you're not sure which
small pieces of code are too slow, you need to profile your
application to find out.  See the documentation for python's profile
module.  If you don't have enough code written to profile, then it's
probably too early to be doing these optimizations.

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


Re: [Tutor] List comprehensions

2008-04-09 Thread Jerry Hill
On Wed, Apr 9, 2008 at 4:15 PM, Dinesh B Vadhia
<[EMAIL PROTECTED]> wrote:
> Sorry, let's start again.

This version really isn't any more helpful than the first one.  I know
you corrected the sample code, but you haven't addressed any of the
fundamental questions that Kent or I asked.

> I want to replace the for loop with another structure to improve performance
> (as the data list will contain >10,000 string items].  At each iteration of
> the for loop the result is printed (in fact, the result is sent from the
> server to a browser one result line at a time)

Are you looking for a different data structure to hold your list of
strings, or are you looking for a replacement for the for loop?  How
long does it take to generate your list?  How long does each iteration
of your for loop take?  What are acceptable times for each of these?
You need to know these things before you can seriously optimize
anything.

If building up the list takes a long time and you only use it once,
consider using a generator instead of building the whole list and then
processing it.  This spreads out the time to create the list and
operates on each piece of data as soon as it's available.

I don't think you're going to find a replacement for a for loop that
is inherently faster.  You keep talking about list comprehensions, but
I don't see how a list comprehension is even appropriate for the
problem you're describing.

> The for loop will be called continuously and this is another reason to look
> for a potentially better structure preferably a built-in.

Again, it would be helpful to discuss actual bits of code, so we can
see if there are places you can gain some performance.  It's hard to
optimize psuedocode, because there are sometimes very minor changes
you can make which affect performance quite a bit. For instance,
attribute lookup in python is relatively slow.  If you can hoist any
attribute lookups out of your loop, you will get some performance
increases.

Also, you should mention what version of python you're using and what
platform it's running on.

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


Re: [Tutor] List comprehensions

2008-04-09 Thread Jerry Hill
On Wed, Apr 9, 2008 at 4:48 PM, Kent Johnson <[EMAIL PROTECTED]> wrote:
>  You could use
>  [ sys.stdout.write(some operation on item) for item in data ]
>
>  but I consider this bad style and I seriously doubt you will see any
>  difference in performance.

This really isn't a good idea.  It will take just as long as the for
loop, plus it builds a list with the return code for each call to
sys.stdout.write() call (which is probably None).  Then after building
the list with > 10,000 entries of None, it throws it away.  That can't
be good for performance.

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


Re: [Tutor] When to use __new__ vs. __init__ ?

2008-04-18 Thread Jerry Hill
On Fri, Apr 18, 2008 at 12:08 PM,  <[EMAIL PROTECTED]> wrote:
> Any guidelines on when to use __new__ vs. __init__ when sub-classing?

Use __new__ when you need to control the creation of a new instance.
Use __init__ when you need to control initialization of a new instance.

__new__ is the first step of instance creation.  It's called first,
and is responsible for returning a new instance of your class.  In
contrast, __init__ doesn't return anything; it's only responsible for
initializing the instance after it's been created.

In general, you shouldn't need to override __new__ unless you're
subclassing an immutable type like str, int, unicode or tuple.

Some references:
The description of new style classes goes into some depth about how
instance creation works, including examples of overriding __new__ and
__init__. http://www.python.org/download/releases/2.2/descrintro/

The reference manual has a section on class customization, but I don't
think it goes into enough depth to really answer your question:
http://docs.python.org/ref/customization.html


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


Re: [Tutor] python -v command

2008-05-02 Thread Jerry Hill
On Fri, May 2, 2008 at 11:33 AM, Stephanie <[EMAIL PROTECTED]> wrote:
> Hi,
> I'm at a very beginning level of Python knowledge, but I use several Python
> programs via the Macintosh Unix Terminal.  I was trying to quickly see which
> version of Python I am running and typed in the command "python -v".  That
> was obviously not the correct command to use.  It installed several things
> and now I'm unable to run my Python programs.
>
> Can someone tell me if there there is a way to undo the python -v command?
> Any suggestions for how I can remedy the situation.

'python -v' just runs the python interpreter in verbose mode -- all
those messages are about various libraries the interactive interpreter
loads before it gives you the prompt.

Running 'python -v' didn't (or at least should not) change anything in
your environment.  Can you show us what happens when you try to run
some of your existing code that used to work?

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


Re: [Tutor] Regular expressions...

2008-05-02 Thread Jerry Hill
On Fri, May 2, 2008 at 12:08 PM, Spencer Parker <[EMAIL PROTECTED]> wrote:
> I need to use a regular expression to get a couple of items for my python
> script.  So far the script is running an 'ls' command to get a few items
> that I need

Why do you need to use regular expressions?  This problem doesn't
really seem to call for them.  You should be able to just use the
split method of strings.  Here's an example:

IDLE 1.2.2
>>> command1 = "2454112 /xen/domains2/machinename/disk.img"
>>> command2 = "-rw-r--r-- 1 root root 20980736 May  2 10:05
/xen/domains2/machinename/disk.img"
>>> command1.split()
['2454112', '/xen/domains2/machinename/disk.img']
>>> command2.split()
['-rw-r--r--', '1', 'root', 'root', '20980736', 'May', '2', '10:05',
'/xen/domains2/machinename/disk.img']
>>> bytes_used = command1.split()[0]
>>> bytes_actual = command2.split()[4]
>>> print bytes_used
2454112
>>> print bytes_actual
20980736
>>> percent = float(bytes_used) / float(bytes_actual)
>>> percent
0.11696977646542046
>>>

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


Re: [Tutor] Supported platform

2008-05-21 Thread Jerry Hill
On Wed, May 21, 2008 at 2:11 PM, Amit Kumar <[EMAIL PROTECTED]> wrote:
> Can I get list of supported platform by python?
>
> can I install python on AS/400 and HP-Unix?

I don't know of any sort of official list of supported platforms.

Activestate claims to have a python distribution for HPUX:
http://www.activestate.com/Products/activepython/features.plex

There appears to be an os/400 python package here: http://www.iseriespython.com/

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


Re: [Tutor] I need to learn more about sorting!

2008-06-23 Thread Jerry Hill
On Mon, Jun 23, 2008 at 4:06 PM, Dick Moores <[EMAIL PROTECTED]> wrote:
> I needed to sort a list of 2-element tuples by their 2nd elements. I
> couldn't see a ready-made function around to do this, so I rolled my own:
...
> colors = [('khaki4', (139, 134, 78)), ('antiquewhite', (250, 235, 215)),
> ('cyan3', (0, 205, 205)), ('antiquewhite1', (238, 223, 204)),
> ('dodgerblue4', (16, 78, 139)), ('antiquewhite4', (139, 131, 120)), ]
>
> print sort_tuple_list_by_2nd_elements(colors)
>
> """
> OUTPUT:
> [('khaki4', (0, 205, 205)), ('antiquewhite', (16, 78, 139)), ('cyan3', (139,
> 131, 120)), ('antiquewhite1', (139, 134, 78)), ('dodgerblue4', (238, 223,
> 204)), ('antiquewhite4', (250, 235, 215))]
> """
> ==
> It works, but did I really need to roll my own? I think I wouldn't have had
> to if I understood what arguments to use for either of the built-ins, sort()
> or sorted(). Can someone give me a clue?

Did that really work the way you wanted!?  It switched elements around
between tuples, which doesn't seem right.  For example, in the input
list you had ('khaki4', (139, 134, 78)) in the output list that became
('khaki4', (0, 205, 205)).

Assuming you just want to sort the list of tuples by the second
element without actually changing the tuples, you can do the
following:

>>> colors = [('khaki4', (139, 134, 78)), ('antiquewhite', (250, 235, 215)), 
>>> ('cyan3', (0, 205, 205)), ('antiquewhite1', (238, 223, 204)), 
>>> ('dodgerblue4', (16, 78, 139)), ('antiquewhite4', (139, 131, 120)), ]

>>> from operator import itemgetter
>>> sorted_colors = sorted(colors, key=itemgetter(1))
>>> sorted_colors
[('cyan3', (0, 205, 205)), ('dodgerblue4', (16, 78, 139)),
('antiquewhite4', (139, 131, 120)), ('khaki4', (139, 134, 78)),
('antiquewhite1', (238, 223, 204)), ('antiquewhite', (250, 235, 215))]
>>>

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


Re: [Tutor] s[len(s):len(s)] = [x] ??

2008-06-30 Thread Jerry Hill
On Mon, Jun 30, 2008 at 4:47 PM, Dick Moores <[EMAIL PROTECTED]> wrote:
> Show me a better way?

You can do it with slice assignment too:
>>> a = [1, 2, 3, 4]
>>> a[1:3] = [[7, 8]]
>>> a
[1, [7, 8], 4]

Now, which way is better?  The answer depends on context.  The best
way to write it is in the manner that it makes the most sense to
someone reading your program (including you, several years later)!

If, conceptually, you are removing two elements from a list, then
adding a new element which is itself a list, then doing it with remove
and insert is probably best.  On the other hand, if you are picking
two elements out of the list (a slice) and replacing it with a new
sublist, then the slice assignment may make more sense to the reader.

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


Re: [Tutor] search path

2008-07-07 Thread Jerry Hill
On Sun, Jul 6, 2008 at 3:47 PM, Robert Johansson
<[EMAIL PROTECTED]> wrote:
> Running the script file she gets error messages claiming that the textfiles
> cannot be found when they are to be opened with
> fileid=file('textfilename.txt','r') even though the same thing works fine on
> my system. Anyone how knows what the cause of this is?

Are you sure the filename is correct?  As I understand it, Window's
filesystems are case insensitive, so 'textfilename.txt' would also
work for files named 'TextFileName.txt', or 'textfilename.TXT', etc.
I believe the Mac's filesystem is case sensitive, so all of those
names would be different files, and could in fact all reside in the
same directory together.

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


Re: [Tutor] accessing string in list

2008-07-15 Thread Jerry Hill
On Tue, Jul 15, 2008 at 10:55 AM, Bryan Fodness <[EMAIL PROTECTED]> wrote:
> I have a list of labels for a data file,
>
> test = ['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
>
> I would like to get the string of the first value that is greater than a
> known value and the previous string.
>
> If I have 15.8, I would like to get the index of '20' and '15'.  I would
> also like to make sure that my known value falls in the range 4-40.
>
> I am having trouble with the mixed types.
>
> for i in range(len(test)):
> if Field < int(test[i]):
> print i

You can put your conversion into a try/except block and handle the exception:

test = ['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
my_val = 15.8
for index, value in enumerate(test):
try:
if int(value) < my_val:
print value
except ValueError:
pass


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


Re: [Tutor] Question on how to do something.

2008-07-18 Thread Jerry Hill
On Thu, Jul 17, 2008 at 6:39 PM, Mitchell Nguyen
<[EMAIL PROTECTED]> wrote:
> Hello. I'm new to Python and I was wondering how to read all the files in a
> folder. I used this program or command for single files.
>
> And if possible, is there a way to make it so that it waits at the end of
> each file for a confirmation to go onto the next file? Thanks

Try something like this:

import glob
for filename in glob.glob('*.txt'):
print filename
response = raw_input("Press ENTER to continue.")

Instead of the print statement, you can process your file any way you
like.  If you want to give the user the ability to abort the program,
or take some other action, you can look at the response variable and
decide what to do with the user's input.

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


Re: [Tutor] where to report a bug?

2008-07-25 Thread Jerry Hill
On Fri, Jul 25, 2008 at 10:04 AM, Rick Pasotto <[EMAIL PROTECTED]> wrote:
> I have a script that works fine on my linux machine but bombs out when
> run under windows using the exact same data files. The script downloads
> a file then unzips it and then scans the resulting file for certain
> records. Under Windows it gets a memory error in the unzip routine.
>
> Where should I send the error report?

In general, http://bugs.python.org/ is the place to report python bugs.

Before you do that though, you should probably put together a bit of
sample code to show the bug, and post it to comp.lang.python (or the
main python mailing list - they mirror each other).  That will help
make sure there isn't a bug in your code rather than in the zipfile
module.

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


Re: [Tutor] Python Docs (Was: Reformatting phone number)

2008-08-21 Thread Jerry Hill
On Thu, Aug 21, 2008 at 12:01 PM, Dotan Cohen <[EMAIL PROTECTED]> wrote:
> 2008/8/21 Kent Johnson <[EMAIL PROTECTED]>:
>> Chapters 2 and 3 of the library reference are highly recommended.
>> http://docs.python.org/lib/lib.html
>
> Let's start from there. I need the startswith() function, but I do not
> know it's name. I search for "strings" and find this:
> 4. String Services
>* 4.1 string -- Common string operations
>  o 4.1.3 String functions

You went too far.  Look at 3.6 (Sequence types) and 3.6.1 (String
Methods).  Those document operations that work on all types of
sequences and the methods of the string type.  That's 99% of what
you'll need to know about python strings.  Kent was pretty specific
about looking at chapter two and three of the library reference.  Why
did you start with chapter four instead?

> But on that page, this is all there is:
> """
> The following functions are available to operate on string and Unicode
> objects. They are not available as string methods.
...
> So Python has only two string functions? That's what it looks like.

There are only two (non-deprecated) functions in the string module.

>
> Thanks, Kent. I will be a nuisance! Is there any place to suggest
> improvements to the docs? I see on the python.org site it is suggested
> to email website bugs to the site admin. Does that go for the docs? I
> am not the one to improve them at this time, as I am unfamiliar with
> the language, but I could report usability issues such as that
> mentioned here.

I believe that doc bugs (and suggestions for improvements) are tracked
on the python bug tracker (http://bugs.python.org/).  If you're going
to submit doc patches, you may want to take a look at
http://docs.python.org/dev/3.0/ which I believe is the beta of the new
documentation layout for python 3.0.  I'm not sure how much the actual
contents have changed from the 2.x docs though.  I notice that the
section on the string module does now refer you back to the methods of
string and sequences in general, which the current docs do not.

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


Re: [Tutor] list slice

2008-09-15 Thread Jerry Hill
On Mon, Sep 15, 2008 at 10:56 AM, Norman Khine <[EMAIL PROTECTED]> wrote:
> Hello,
> I have this code:
>
> topics = object.parent.get_topics()
>for i, topic in enumerate(topics):
>all_previous_topics = topics[:i]
>print all_previous_topics
>
> where topics returns a list.
>
> I am trying to get all the topics before current topic in the loop.
>
> Is there a way to do this?

Yes.

Is topics a list, or a function which returns a list?  What you've
written above works for me when topics is a list.  In what way doesn't
it work for you?

>>> topics = ['Reading', 'Writing', 'Arithmetic']
>>> for i, topic in enumerate(topics):
print "Current Topic: ", topic
print "Previous Topics: ", topics[:i]


Current Topic:  Reading
Previous Topics:  []
Current Topic:  Writing
Previous Topics:  ['Reading']
Current Topic:  Arithmetic
Previous Topics:  ['Reading', 'Writing']
>>>

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


Re: [Tutor] Sort Output

2008-09-17 Thread Jerry Hill
On Wed, Sep 17, 2008 at 3:30 PM, Wayne Watson
<[EMAIL PROTECTED]> wrote:
> I'm using Python 2.4 in Win XP. I was surprised to find the result below.
>
 a =[4,2,5,8]
 b = a

This binds the name "b" to the same object that "a" is bound to.

 a.sort()
 a
> [2, 4, 5, 8]
 b
> [2, 4, 5, 8]
>
> b no longer has the same value as it began. Apparently to prevent sort from
> making it the same I have to resort to copying b into a first? What is the
> proper way to retain a variable with the original values of a?

Yes.  If you want "a" and "b" to point to different lists, you'll need
to copy the list that "a" is bound to.  This is a really common thing
to do, and python provides an easy way to do it:

>>> a = [4, 2, 5, 8]
>>> b = sorted(a)
>>> print a
[4, 2, 5, 8]
>>> print b
[2, 4, 5, 8]
>>>

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


Re: [Tutor] image processing

2008-09-23 Thread Jerry Hill
On Tue, Sep 23, 2008 at 5:38 PM, jeremiah
<[EMAIL PROTECTED]> wrote:
> I'm trying to do simple image manipulation but am getting an error. any
> ideas what i am doing wrong here?
>
> file=open("./"+name,"w")
> pic=Image.open(file)

You're opening the file for "w"riting, then asking PIL to read it.
That's not going to work.  In fact, there's no reason for you to open
the file yourself.  Just pass the filename, like this:

pic=Image.open(name)

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


Re: [Tutor] re.compile concatenating two searh words

2008-09-29 Thread Jerry Hill
On Mon, Sep 29, 2008 at 6:19 PM, Srinivas Iyyer
<[EMAIL PROTECTED]> wrote:
> Hi Tutors,
> I have a list with elements as strings. I want to search if any of these 
> element strings has two words of my interest. How can I ask re.compile to 
> look for both words.
>
> my words are 'good' and 'bad'.

If this really reflects your requirements, regular expressions are not
a good choice in the first place.  Instead, I would use some of
python's built in string functionality, like this:

>>> a = ['Rama is a good boy','Raghu is a good boy','Sita is a good 
>>> girl','Ravana is a bad boy','Duryodhan is a bad guy','good is an acceptable 
>>> nature while bad is unwanted nature in a person']

>>> for item in a:
if 'good' in item and 'bad' in item:
print item


good is an acceptable nature while bad is unwanted nature in a person
>>>



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


Re: [Tutor] cx_oracle module problems

2008-10-07 Thread Jerry Hill
On Tue, Oct 7, 2008 at 2:46 PM, jeremiah <[EMAIL PROTECTED]> wrote:
> I've downloaded the cx_oracle source module for python, howerver every
> time i try to build it, it keeps on failing. I've been unable to find a
> port for Ubuntu. Is there one? Anyone know how to get this properly
> installed?
>
> # sudo python setup.py install
> Traceback (most recent call last):
>  File "setup.py", line 36, in 
>oracleHome = os.environ["ORACLE_HOME"]
>  File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__
>raise KeyError(key)
> KeyError: 'ORACLE_HOME'

It looks to me like it expects you to already have the oracle client
libraries installed, since it's looking for the 'ORACLE_HOME'
environment variable.

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


Re: [Tutor] appending to a utf-16 encoded text file

2008-10-21 Thread Jerry Hill
On Tue, Oct 21, 2008 at 9:52 AM, Tim Brown <[EMAIL PROTECTED]> wrote:
> Hi,
> I'm trying to create and append unicode strings to a utf-16 text file.
> The best I could come up with was to use codecs.open() with an
> encoding of 'utf-16' but when I do an append I get another UTF16 BOM
> put into the file which other programs do not expect to see :-(
> Is there some way to stop codecs from doing this or is there a better
> way to create and add data to a utf-16 text file?

That appears to be bug 1701389 (http://bugs.python.org/issue1701389),
which was closed as "Won't Fix" last year.

You should be able to work around it by doing the encoding yourself, like this:

my_file = open("my_utf16_file.txt", "ab")
my_file.write(my_unicode_str.encode("utf16"))

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


[Tutor] Python in a web browser (was Re: finding numbers in range of of numbers)

2008-10-21 Thread Jerry Hill
On Tue, Oct 21, 2008 at 2:26 PM, Richard Lovely
<[EMAIL PROTECTED]> wrote:
> I don't have internet access, and I've yet to find a public computer
> with Python, so I'm unable to test any code I write.  I'm going have
> to discpline myself not to post to here unless its: a) a problem of my
> own, or b) an answer that doesn't contain code...

There are some neat things you can do to get around this limitation,
at least a little bit.  There are at least two places you can bring up
an interactive python interpreted right inside a web browser.

http://try-python.mired.org/  Appears to be a python 2.5.2 interpreter
embedded in a web page.

http://www.voidspace.org.uk/ironpython/silverlight-console/console.html
This one is an IronPython interpreter (I don't know what version),
embedded via SilverLight.

I'm pretty sure that both of those are pretty limited in
functionality, but you can at least play with some basic functionality
without having python installed locally.

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


Re: [Tutor] Iterate over multiple objects

2008-10-29 Thread Jerry Hill
On Wed, Oct 29, 2008 at 7:30 AM, W W <[EMAIL PROTECTED]> wrote:
> I'm trying to compare two strings because I want to find the difference.

Albert pointed you to zip so that you can iterate through the two
strings in lockstep.  You may also want to investigate the python
difflib module in the standard library.  It has a lot of powerful
tools for comparing texts that go beyond the simple case of comparing
two strings for single-character differences.

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


Re: [Tutor] how to read over serial port

2008-11-03 Thread Jerry Hill
On Mon, Nov 3, 2008 at 4:08 PM, shawn bright <[EMAIL PROTECTED]> wrote:
> yes, they look like this
> ��
>
> so i used your print repr(chr(ord(i))) and got this

Note that that's the same thing as just printing repr(i).

> so, what do i do now?
> and thanks for the info, by the way, been writing python for 2 years,
> but this is all new to me.

Maybe we should back up a little bit.  You said in your original post
that you were expecting ASCII characters from the serial device.  How
do you know that's what you should be getting back?  Have you tried
communicating with the device using some other program?  If so, what
program?  Do you have specs that tell you that's how it's supposed to
work?

Are you sure you're connecting to the device with the right parameters
for baudrate, byte size, parity, etc?

I notice that nowhere in this thread have you posted the code you use
to actually communicate with the serial device.  Maybe you should do
that.

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


Re: [Tutor] accessing an image with pygame.image.load()

2008-11-03 Thread Jerry Hill
On Mon, Nov 3, 2008 at 7:05 PM, bob gailer <[EMAIL PROTECTED]> wrote:
> Christopher Spears wrote:
>> self.image =
>> pygame.image.load("C:Users\Chris\Documents\python\assignment07\chris_graphics\spaceship.gif")
>>
>
> Since \ is used to "escape" certain characters it is advisable to either use
> \\ or preface the string with r.

Beyond what Bob says about being careful of the escape character ('\')
and the need to either double it up in a string literal or use a raw
string, are you sure that path is right?  Usually a drive letter is
followed by a backslash in windows.  That is, "C:\Users\Chris" rather
than "C:Users\Chris".

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


Re: [Tutor] /not/ instanciating

2008-11-17 Thread Jerry Hill
On Sun, Nov 16, 2008 at 2:57 PM, spir <[EMAIL PROTECTED]> wrote:
> * Why, then, is __init__ still executed when the instanciated object is
> 'manually' returned? What's the use of that feature?

The manual (http://www.python.org/doc/2.5.2/ref/customization.html) says:
"If __new__() returns an instance of cls, then the new instance's
__init__() method will be invoked like "__init__(self[, ...])", where
self is the new instance and the remaining arguments are the same as
were passed to __new__(). "

That seems to explain why you're seeing what you're seeing.  I don't
know how you would avoid that if that's not the behavior you want,
though.  I suppose you could then repeat your check of the type of
source in __init__, just like you did in __new__ to avoid
re-initializing.

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


Re: [Tutor] Deleting recursive folder definition

2009-01-12 Thread Jerry Hill
On Mon, Jan 12, 2009 at 2:07 PM, Alan Gauld  wrote:
> I've managed to do something incredibly stupid on my XP box.
> I've created a folder that is a link to itself - at least I think that's
> what has
> happened, it was a CASE tool that I was using that actually did the damage.

Try exploring the options in fsutil.exe.  Some (untested!) suggestions:

fsutil.exe reparsepoint query 
fsutil.exe reparsepoint delete 

If that doesn't do the job, you probably need to figure out *exactly*
what type of NTFS object you're dealing with.  Some search terms that
might get you started:

NTFS plus one of:
hard link
soft link
reparse point
junction point

There are tools out there that make dealing with some of the more
exotic NTFS file-like objects easier, but I'm not too familiar with
them.  You'll probably need to explore some, and probably learn more
about NTFS than you ever wanted to know :)

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


Re: [Tutor] How to handle exceptions raised inside a function?

2010-11-30 Thread Jerry Hill
On Tue, Nov 30, 2010 at 3:00 PM, Richard D. Moores  wrote:
> Both Hlist and Glist must contain only positive numbers, so I really
> need to test for this inside each function. But is there a good way to
> do this? What should the functions return should a non-positive number
> be detected? Is there a conventional Pythonic way to do this?

If the value passed to the function is illegal, you should raise a
ValueError exception.  Something like this in your harmonic_mean
function, maybe:

if not all(x > 0 for x in Hlist):
raise ValueError("All items in Hlist must be positive numbers.")

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


Re: [Tutor] floats

2010-12-03 Thread Jerry Hill
On Fri, Dec 3, 2010 at 1:52 PM, Christopher Spears
 wrote:
 float_a = 1.16667
>
> However, I want to pass the value of float_a to float_b, but I want the float 
> to be accurate to two decimal points.

Use the built-in round() function, like this:

>>> a = 1.16667
>>> print a
1.16667
>>> b = round(a, 2)
>>> print b
1.17


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


Re: [Tutor] Save file in a specific directory

2010-12-07 Thread Jerry Hill
> When I run the script I got the next error:
 import crawler_shp
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "crawler_shp.py", line 105, in 
>     dbf = Dbf(d,new=False)
>   File "C:\Python26\lib\site-packages\dbf.py", line 125, in __init__
>     self.stream = file(f, ("r+b", "rb")[bool(readOnly)])
> IOError: [Errno 13] Permission denied: 'R:\\Aplicaciones\\IRISv3\\mis
> proyectos\
> \HURACAN\\BUFFER1000.dbf'
>
> The error is pointing to a library I used to make the script run: dbf.py. in
> thid lines:
> if isinstance(f, basestring):
>     # a filename
>     self.name = f
>     if new:
>     # new table (table file must be
>     # created or opened and truncated)
>     self.stream = file(f, "w+b")
>     else:
>     # tabe file must exist
>     self.stream = file(f, ("r+b", "rb")[bool(readOnly)])


Sounds like you need to change your dbf object to something like this:
 dbf = Dbf(d,new=False, readOnly=True)

Note that I don't know anything about the Dbf module, other than what
you just posted.  If you really have read permission, but not write
permissions, this should do what you want though.

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


Re: [Tutor] Importing packages

2011-01-21 Thread Jerry Hill
On Fri, Jan 21, 2011 at 4:10 AM, arun kumar  wrote:
> Hi,
>
> I'm trying to program with gdata
> (http://code.google.com/p/gdata-python-client/) using python
> library.I'm having problem in writing import statements.

Have you read the Getting Started document linked from their wiki?
Particularly, there's a section on the right way to install the
library, then some example of it's use (including the import
statements) here:
http://code.google.com/apis/gdata/articles/python_client_lib.html#library

You haven't said what you tried or what error messages you've gotten,
so if those docs don't help, you'll have to give us more information.
Particularly: what version of python are you running?  What Operating
System?  How have you manipulated your sys.path, where did you install
the gdata libraries, and what is the folder structure there?

You may also find the part of the python tutorial about modules and
packages useful in figuring out what's going on:
http://docs.python.org/tutorial/modules.html

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


Re: [Tutor] The trap of the year

2011-01-25 Thread Jerry Hill
On Tue, Jan 25, 2011 at 3:41 PM, Karim  wrote:

> I am not really understanding why my init in the class made it refers to
> the same list object.
> What is the difference with 2nd example directly at the prompt?
>

See http://effbot.org/zone/default-values.htm

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


[Tutor] Homework and the Tutor list

2011-02-02 Thread Jerry Hill
>    I would have to agree with you Ian.  Coming from an art then computer
> animation visual effects background, it's not until recently that it became
> evident to me that in order to push the potential of this medium, I would
> definitely have to learn to code.  I think the stigma of the "homework
> bandwagon" comes from the very nature of coding and it's secretive and
> cryptic undertones, it's something very personal in the sense that, although
> there is usually more than 1 way to solve a problem, there's always "THE
> MOST" and more efficient way IMHO, that some people are just not willing to
> share. And, of course, this most efficient way utilizes less memory and
> resources.  This is why I always feel apprehensive to post so I purchased
> many books on python, and until I've gone through them and feel competent
> enough to post, then I'll post, which to me does no good.  Thank you for
> your insight, it makes me feel a little bet more human and inspires me not
> to give up.

I don't think that's true at all.  I think people here are happy to
help, including by posting working, efficient, code.  What we try to
avoid is having students come here with their assignments and have us
do their schoolwork for them.  I'm not sure how long you've been
subscribed to the list, but this happens on a regular basis.

If you're concerned that people will think you're looking for help
with homework, just tell us up front that it's not a homework problem.
 If it *is* a homework problem, tell us that up front too, and people
will still be happy to help, though less likely to post working code,
and more likely to try and work with you to get you to figure out the
solution on your own.

In all cases, you are most likely to get useful help if you do a
couple of things:
Tell us what you're trying to accomplish and why, as clearly as you can.

Post some code that tries to solve the problem, but doesn't work
right.  Ideally, post code that is self contained (so that other
people can run it too), along with any error messages (including the
full stack trace, if one is generated), and what your desired result
is.

Try to give us the big picture of what you're doing, as well as the
details of the problem you're having.  Sometimes we can point you to
an entirely different approach that will work better.

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


Re: [Tutor] Pygame install help

2011-03-28 Thread Jerry Hill
On Sun, Mar 27, 2011 at 1:31 PM, Chuck  wrote:
> Does anyone have familiarity with installing pygame? It seems simple and
> straight forward enough, then why do I get the following from IDLE? This is
> the 3.1 Windows pygame .msi install...

You're using pygame (probably pygame 1.9.1) built for python 3.1, but...

> Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on

...you're using python 3.2.

Don't do that.  Your versions need to match.  Since I don't see a
version of pygame built for python 3.2 on windows, you'll need to
either go back to python 3.1, or wait for someone to build pygame for
3.2.  You might be able to build it yourself, but I don't know how
convoluted that is.

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


Re: [Tutor] reading very large files

2011-05-17 Thread Jerry Hill
On Tue, May 17, 2011 at 1:20 PM, Vikram K  wrote:
> I wish to read a large data file (file size is around 1.8 MB) and manipulate
> the data in this file. Just reading and writing the first 500 lines of this
> file is causing a problem. I wrote:
...
>
> Traceback (most recent call last):
>   File
> "H:\genome_4_omics_study\GS03696-DID\GS00471-DNA_B01_1101_37-ASM\GS00471-DNA_B01\ASM\gene-GS00471-DNA_B01_1101_37-ASM.tsv\test.py",
> line 3, in 
>     for i in fin.readlines():
> MemoryError
>
> ---
> is there a way to stop python from slurping all the  file contents at once?

Well, readlines() does read in a whole file at once, splitting it into
a list with one item in the list per line in the file.  I'm surprised
that a 1.8 MB file is causing you to hit a MemoryError though -- that
isn't a very big file.  If you're really just trying to process one
line at a time, you should just use "for i in fin:", which will read
one line at a time into memory.  No need to read the whole thing at
once.

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


Re: [Tutor] lxml.html

2011-06-08 Thread Jerry Hill
On Wed, Jun 8, 2011 at 11:20 AM, nitin chandra  wrote:
> Hello Every One,
>
>         doc = lxml.html.parse('/home/dev/wsgi-scripts/index.py').getroot()

Is index.py really an XML document?  If so, it's named pretty oddly...

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


Re: [Tutor] trying to translate and ebcidic file

2011-06-14 Thread Jerry Hill
On Tue, Jun 14, 2011 at 2:40 PM, Prinn, Craig
 wrote:
> I am looking for a way to translate and ebcidic file to ascii. Is there a
> pre-existing library for this, or do I need to do this from scratch? If from
> scratch and ideas on where to start?

If the file is essentially a text file, I would read the contents in,
decode the resulting bytes to a unicode string, then encode the
unicode string to the encoding of your choice (ascii, utf-8, etc).
You'll also need to know which variant of EBCDIC you're dealing with.
I'm assuming CCSID 500.

Something like this:

input_file = open('my_ebcidic_file', 'rb')
ebcidic_bytes = input_file.read()
unicode_str = ebcidic_bytes.decode('cp500')
ascii_str = unicode_str.encode('ascii')

You can do it in less steps, but that should give you something to start with.

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


Re: [Tutor] which version do i have and how do i change it

2011-08-16 Thread Jerry Hill
On Tue, Aug 16, 2011 at 4:35 PM, Lisi  wrote:
> lisi@Tux:~$ aptitude why python
> i   reportbug Depends python (>= 2.5)
> lisi@Tux:~$

Keep in mind that that command only shows you a single dependency
chain.  Try again with "aptitude -v why python" to see all of the
dependencies.  On my ubuntu 11.04 machine, that command produces over
9000 lines of output, and over 800 distinct packages that depend on
python in one way or another.

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


Re: [Tutor] String encoding

2011-08-26 Thread Jerry Hill
On Thu, Aug 25, 2011 at 7:07 PM, Prasad, Ramit
 wrote:
> Nice catch! Yeah, I am stuck on the encoding mechanism as well. I know how to 
> encode/decode...but not what encoding to use. Is there a reference that I can 
> look up to find what encoding that would correspond to? I know what the 
> character looks like if that helps. I know that Python does display the 
> correct character sometimes, but not sure when or why.

In this case, the encoding is almost certainly "latin-1".  I know that
from playing around at the interactive interpreter, like this:

>>> s = 'M\xc9XICO'
>>> print s.decode('latin-1')
MÉXICO

If you want to see charts of various encodings, wikipedia has a bunch.
 For instance, the Latin-1 encoding is here:
http://en.wikipedia.org/wiki/ISO/IEC_8859-1 and UTF-8 is here:
http://en.wikipedia.org/wiki/Utf-8

As the other respondents have said, it's really hard to figure this
out just in code.  The chardet module mentioned by Steven D'Aprano is
probably the best bet if you really *have* to guess the encoding of an
arbitrary sequence of bytes, but it much, much better to actually know
the encoding of your inputs.

Good luck!

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


Re: [Tutor] longest common substring

2011-11-11 Thread Jerry Hill
There's nothing wrong with writing your own code to find the longest common
substring, but are you aware that python has a module in the standard
library that already does this?  In the difflib module, the SequenceMatcher
class can compare two sequences and extract the longest common sequence of
elements from it, like this:

Code:
import difflib

a = [1, 2, 3, 7]
b = [2, 3, 7]

seq_matcher = difflib.SequenceMatcher(None, a, b)
print seq_matcher.find_longest_match(0, len(a), 0, len(b))

Outputs:
Match(a=1, b=0, size=3)

See http://docs.python.org/library/difflib.html#sequencematcher-objects for
lots of details.  The SequenceMatcher class can do a lot more than finding
the common substrings, as you might expect.  The Module of the Week article
for difflib may also be of interest:
http://www.doughellmann.com/PyMOTW/difflib/index.html

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


Re: [Tutor] Find all strings that....

2011-11-11 Thread Jerry Hill
On Fri, Nov 11, 2011 at 1:21 PM, Francesco Loffredo  wrote:

> Anyway, taking for granted the rules contained in the edit distance
> definition (Thank you, Steven!), I think that finding in a given set S all
> words that can be converted into some given "target" with at most N such
> operations (better:  the subset of all words in S with an edit distance
> from "target" <= N) is a very interesting and challenging task. Thank you
> (and your friend!) for this exercise, I'll give it a try.
>

There are some standard library tools that make this pretty easy.  Take a
look into difflib if you're interested.  As always, there's nothing wrong
with doing it yourself so that you understand it better, of course.

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


Re: [Tutor] Cython vs Python-C API

2011-11-14 Thread Jerry Hill
On Mon, Nov 14, 2011 at 3:30 PM, Jaidev Deshpande <
deshpande.jai...@gmail.com> wrote:

> Hi
>
> I need to perform cubic spline interpolation over a range of points, and I
> have written the code for the same in C and in Python.
>
> The interpolation is part of a bigger project. I want to front end for the
> project to be Python. Ideally I want Python only to deal with data
> visualization and i/o, and I'll leave the computationally expensive part of
> the project to C extensions, which can be imported as functions into Python.
>
> To this end, the interpolation can be handled in two ways:
>
> 1. I can either compile the C code into a module using the Python-C/C++
> API, through which I can simple 'import' the required function.
> 2. I can use the Python code and extend it using Cython.
>
> Which will give me a better performance?
>

Aren't you, right now, in the ideal position to answer that question for
yourself?  You have the same algorithm implemented both in C and in
Python.  Can't you compile that python code with Cython, then just test the
two to see which is faster?

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


Re: [Tutor] In a pickle over pickles….Python 3

2011-11-18 Thread Jerry Hill
On Fri, Nov 18, 2011 at 11:12 AM, Joe Batt  wrote:

>
> pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','w')
> pickle.dump(filecontents,pickledfile)
> pickledfile.close()
>
>
A pickle is a binary object, so you'll need to open your picklefile in
binary mode:

pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','wb')

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


Re: [Tutor] Python Windows Vista Installation Question

2011-12-09 Thread Jerry Hill
On Fri, Dec 9, 2011 at 1:41 PM, Homme, James wrote:

> Can Python easily be installed on a Windows Vista computer without needing
> administrative rights to that machine?
>

I thought the standard installer worked for non-admin installs, as long as
you select "Just for me" instead of "All users on this computer" when given
the option.  Did you try that?

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


Re: [Tutor] Request for guidance about a python syntax

2011-12-19 Thread Jerry Hill
On Mon, Dec 19, 2011 at 10:54 AM, Ganesh Borse  wrote:

> I could know the use of unpack_from, but I could not understand the "fmt"
> part, i.e *"%dH" % nframes * nchannels*.
> Can you pls help me know, what is the purpose of two "%" signs in this
> statement?
>
>
That's python's string formatting.  See
http://docs.python.org/library/stdtypes.html#string-formatting-operations for
details.  Basically, it's building the format for the call to unpack_from
on the fly.  The "%dH" portion is calling for a single decimal value to
become part of the string (that's the "%d" portion).  That value comes from
multiplying nframes by nchannels.  So, for example, if nframes = 10 and
nchannels = 24, then the string becomes "240H".  That, in turn, tells the
program to unpack a sequence of 240 unsigned short values from the buffer.

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


Re: [Tutor] Request for guidance about a python syntax

2011-12-19 Thread Jerry Hill
On Mon, Dec 19, 2011 at 12:10 PM, Peter Otten <__pete...@web.de> wrote:

> Close, but % and * have the same operator precedence. Therefore the
> expression
>
> "%dH" % nframes * nchannels
>
> is evaluated as
>
> (%dH" % nframes) * nchannels
>
>
Thanks Peter, that's exactly correct.  Maybe this will teach me not to post
things without actually trying them in the interactive interpreter.

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


Re: [Tutor] Beginner Exercise: Why Didn't I Break It?

2011-12-20 Thread Jerry Hill
On Tue, Dec 20, 2011 at 12:31 PM, Homme, James  wrote:
> So far, the data types this little book has talked about are strings and 
> numbers.
...
> return jelly_beans, jars, crates
...
> # It returns three things in parentheses, which, I guess is one group of 
> things. I thought it would complain.


You book may not have talked about it yet, but there is a third data
type involved here, a tuple.  The secret_formula() function doesn't
actually return three separate things.  It returns a single object
that contains a sequence of three other objects.  In this case, it
specifically returns a tuple (rather than a list or other sequence
type).

Take a look here
http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences
for more about tuples in particular, and the rest of that page for an
overview of sequence types in general.

>beans, jars, crates = secret_formula(start_point)

This line performs what python calls "sequence unpacking" (sometimes
also called "tuple unpacking").  That's described in the same link I
referenced above.

Hopefully that gives you a few places to read more without explaining
the whole thing.

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


Re: [Tutor] Installing Modules

2012-01-18 Thread Jerry Hill
On Wed, Jan 18, 2012 at 1:07 PM, Downey, Patrick  wrote:

> I'm currently running Python version 2.7 through IDLE on a Windows machine.
> I'm trying to use numpy and scipy. I downloaded both modules from the scipy
> website and unzipped the files into:
> C:\Python27\Lib\site-packages
>

That is not the typical way to install software on windows, even python
modules.  Typically, software on windows is distributed in an installer.
Numpy and Scipy are the same way.  You could download the source code,
compile it, and install it from there, but that's pretty unusual on windows.

So.  Remove whatever you have unzipped into site-packages.  Download the
numpy and scipy installers.  Run them.  That should be it.

Numpy installer:
http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/numpy-1.6.1-win32-superpack-python2.7.exe/download

Scipy installer:
http://sourceforge.net/projects/scipy/files/scipy/0.10.0/scipy-0.10.0-win32-superpack-python2.7.exe/download

If you really do want to compile scipy and numpy from source, there are
instructions on getting all the required tools here:
http://scipy.org/Installing_SciPy/Windows

-- 
Jerry

PS: There *are* python packages out there that have to just be unzipped
into site-packages.  Those projects are typically pure-python modules
without any C code to compile.  Numpy and Scipy aren't among them, though.
There are other packages that expect you to download them, extract them to
a temp directory, then run "python setup.py install".   To know for sure
how to install a particular package, you'll need to dig around a bit for
installation instructions for that particular package.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding a polymer of letters in a string

2012-01-19 Thread Jerry Hill
On Thu, Jan 19, 2012 at 1:44 PM, Hs Hs  wrote:

> so I do not know what that pattern would be when I read in a string. I do
> not know if regex could solve my kind of problem too.
>

Ignore the python portion of the problem for now.

Imagine someone handed you a piece of paper with the letters
"AAATAGCAGAAATGGATTGGAACTAGGTCAG" written on it, and asked you to
circle the section that you're trying to identify.  How would you do it,
without using a computer?  How do you figure out where there was a
mutation, and then how do you discover if that location is in a polymer
region?

If you can describe that process to us, maybe we can help you turn that
into a python program.

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


Re: [Tutor] New user Knows nothing about python I Need HELP

2012-01-30 Thread Jerry Hill
On Mon, Jan 30, 2012 at 2:02 PM, William Stewart
 wrote:
> I have no Idea how to start this task I have never used ANY programming 
> programs before And I dont Know the language either
> The online help files from python Did not help a bit


Here's a few resources that might get you started.

First, if you haven't seen it, I found the official python tutorial to
be a great place to start: http://docs.python.org/tutorial/  That may
assume more familiarity with programming in general than you are
comfortable with, though.

In that case, you might be interested in a whole bunch of resources
designed to teach python to people who haven't done any programming at
all: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Once you're a bit more comfortable, there are a ton more documentation
aimed at learning python for people who are already somewhat familiar
with other programming languages:
http://wiki.python.org/moin/BeginnersGuide/Programmers

Hope that helps some,
Jerry
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] For/Else loops

2012-02-07 Thread Jerry Hill
On Tue, Feb 7, 2012 at 1:50 PM, Debashish Saha  wrote:
> for i in range(1, 8):
>    print(i)
>    if i==3:
>        break
> else:
>    print('The for loop is over')
>
>
>  Output:
> 1
> 2
> 3
>
> Question:but after breaking the for loop why the else command could not work?

Because that's the way a for/else statement works.  The else suite is
only run if you do not break out of the loop.  See the docs here:
http://docs.python.org/reference/compound_stmts.html#the-for-statement

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


Re: [Tutor] (no subject)

2012-02-08 Thread Jerry Hill
On Wed, Feb 8, 2012 at 5:21 PM, Joel Goldstick wrote:

> The else clause runs if the loop breaks for some reason.  So you would
> use it only to do some processing if the loop completes completely.
>
>
No.  The else clause only runs if the loop does NOT break out early.  The
else clause only runs if the loop runs to completion without breaking.

For what it's worth, I loathe for/else loops, and will probably never use
them in my code.  They confuse me every time I see them, and I have to go
look up the behavior.  My brain always jumps to the conclusion that the
"else" clause should run when we do hit a break, which is the exact
opposite of how it actually works.  Maybe if they had been written into the
language as for/then loops I would remember it correctly.

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


Re: [Tutor] __name__=='__main__'

2012-02-20 Thread Jerry Hill
On Mon, Feb 20, 2012 at 6:46 PM, Michael Lewis  wrote:
>  I at first put it outside and after all my functions but got the error below

That's the right place for it, you just spelled it wrong.

> and then put it inside my last function and the program ran.

That's not the right place for it.  Your program ran, but only because
nothing ever called your GetUserInput() function any more.

> Traceback (most recent call last):
>   File "C:/Python27/Homework/Homework5_1.py", line 24, in 
>     if __name == '__main__':
> NameError: name '__name' is not defined

It needs to be spelled "__name__" -- that's two underscores on each side.

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


Re: [Tutor] Create a table by writing to a text file.

2012-02-22 Thread Jerry Hill
On Wed, Feb 22, 2012 at 10:24 AM, David Craig  wrote:

> you had me worried for a minute, but
> a = [[]] * 3
> a[0]=[1,2,3]
> a
> [[1, 2, 3], [], []]
>

That's not the same thing.  In your example you create three copies of the
same empty list inside your outer list.  You then throw away the first copy
of the empty list and replace it with a new list.  What Peter showed was
mutating that inner list in place.  If you aren't really, really careful,
you will eventually get bitten by this if you create your lists with
multiplication.

>>> container = [[]] * 3

You can see that this really is three references to the exact same list:
>>> print [id(item) for item in container]
[17246328, 17246328, 17246328]

If you replace the items, you're fine:
>>> container[0] = [1, 2, 3]
>>> print [id(item) for item in container]
[17245808, 17246328, 17246328]

But as soon as you change the contents of one of those duplicate lists,
you're in trouble:
>>> container[1].append('Data')
>>> print container
[[1, 2, 3], ['Data'], ['Data']]
>>> print [id(item) for item in container]
[17245808, 17246328, 17246328]
>>>

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


Re: [Tutor] number of mismatches in a string

2012-03-02 Thread Jerry Hill
On Fri, Mar 2, 2012 at 2:11 PM, Hs Hs  wrote:
> Hi:
> I have the following table and I am interested in calculating mismatch
> ratio. I am not completely clear how to do this and any help is deeply
> appreciated.
>
> Length     Matches
> 77      24A0T9T36
> 71      25^T9^T37
> 60      25^T9^T26
> 62      42A19
>
>
> In length column I have length of the character string.
> In the second column I have the matches my reference string.
>
>
> In fist case, where 77 is length, in matches from left to right, first 24
> matched my reference string following by a extra character A, a null (does
> not account to proble) and extra T, 9 matches, extra T and 36 matches.
>  Totally there are 3 mismatches
>
> In case 2, I lost 2 characters (^ = loss of character compared to reference
> sentence)   -
>
> TOMISAGOODBOY
> T^MISAGOOD^OY   (here I lost 2 characters)  = I have 2 mismatches
> TOMISAGOOODBOOY (here I have 2 extra characters O and O) = I have two
> mismatches
>
>
> In case 4: I have 42 matches, extra A and 19 matches = so I have 1 mismatch
>
>
> How can that mismatch number from matches string.
> 1. I have to count how many A or T or G or C (believe me only these 4
> letters will appear in this, i will not see Z or B or K etc)
> 2. ^T or ^A or ^G or ^C will also be a mismatch
>
>
> desired output:
>
> Length     Matches   mismatches
> 77      24A0T9T36    3
> 71      25^T9^T37     2
> 60      25^T9^T26     2
> 62      42A19             1
> 10      6^TTT1           3
>

It looks like all you need to do is count the number of A, T, C, and G
characters in your Matches column.  Maybe something like this:

differences = [
[77, '24A0T9T36'],
[71, '25^T9^T37'],
[60, '25^T9^T26'],
[62, '42A19']
]


for length, matches in differences:
mismatches = 0
for char in matches:
if char in ('A', 'T', 'G', 'C'):
mismatches += 1
print length, matches, mismatches


which produces the following output:
77 24A0T9T36 3
71 25^T9^T37 2
60 25^T9^T26 2
62 42A19 1

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


Re: [Tutor] creating dict of dict : similar to perl hash of hash

2012-03-06 Thread Jerry Hill
On Tue, Mar 6, 2012 at 6:21 PM, Alan Gauld  wrote:
> But it doesn't have the same dynamic depth that the Perl version has, you
> need to know your maximum depth. The last level will always have the default
> set to None.
>
> You could create a class subclassed from defaultdict that would do it
> though...

It's a pretty easy class to write:

from collections import defaultdict

class recursivedefaultdict(defaultdict):
def __init__(self):
self.default_factory = type(self)

Given that bit of code, the OP's example looks a bit like this:

a = 1
b = 2
c = 'apples'

my_hash = recursivedefaultdict()
my_hash[a][b][c] = "value"
if my_hash[a][b][c]:
print("found value")

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


Re: [Tutor] how to build a multiplayer game?

2012-04-11 Thread Jerry Hill
On Wed, Apr 11, 2012 at 9:30 AM, Surya K  wrote:
> Well, can we make the program so that user enters his IP, DNS addresses
> before starting?

You could, sure.  That's fine for testing purposes, but most people
don't know their own IP addresses.  Many people don't have a DNS entry
for their home PC.  Also, what about NAT?

> Don't you think DNS is required as IP addr may be same for some people in
> this world.. after all, we only have limited number of combinations.
> (xx.xx.xx.xx .. )

Again, not every computer has a DNS address.  If you are going to ask
a user to hand enter their IP address, it would make sense to accept
either a numeric IP address, or a DNS name.


> * I even got a wild idea, can't we use a IRC channel, create a group and we
> make sure that each user of the game will be a member of the group??

Sure, but now you have to write (or embed) an IRC client.  Do you need
to worry about someone joining your channel that isn't using your game
client?  Does that have potential security implications?

> approx, how much delay would be there??

That depends on the delay from each client to the IRC server.

> Hmm, google app engine is a nice option but thing is I don't know how to use
> it.

You're going to have to learn quite a bit about networking and
probably client / server architecture to write a networked game.

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


Re: [Tutor] need help with a script..

2012-04-11 Thread Jerry Hill
On Wed, Apr 11, 2012 at 9:50 AM, Khalid Al-Ghamdi  wrote:
> Hi All,
>
> I'm using python 3.2 on a windows xp.
>
> I wrote the below script and ran it with the hope of returning a list of
> proctors (list_proc), but when it runs it  doesn't call the function
> convert_proctors() as intended. On the other hand, when i import the module
> from the IDLE prompt and call the convert_proctors() function, the function
> returns the desired list.
>
> Why is this so?

When you run that code as a script, it does call your
convert_proctors() function.  But since all you do is create a list,
and you never save it to disk, or print it to the screen, or even
assign it to a variable, the result is just thrown away.  Try changing
the last line to:

print(convert_proctors())

and you'll see the results you were expecting.

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


Re: [Tutor] is it possible to create and amend classes during run-time?

2012-05-02 Thread Jerry Hill
On Wed, May 2, 2012 at 3:56 PM, Bjorn Madsen
 wrote:
> Hi,
> I have been studying http://docs.python.org/tutorial/classes.html for a
> while, but still have two questions which I could not answer. Perhaps you
> could help?
>
> Does anyone know if it is possible during run-time to:
> a) add attributes to classes, which will unknown at program start, but
> "emerge" later whilst the program is running?
> b) add subclasses to class (also during runtime)

As far as I understand your questions, the answer to both of those is
yes.  It might help for you to provide an example of exactly what you
mean, though.

Here's a quick examples (python 2.6, from the interactive interpreter)
of adding an attribute to an existing class:

>>> class Foo(object):
pass

>>> my_foo = Foo()
>>> Foo.bar = True
>>> print my_foo.bar
True
>>>

I defined the class Foo, created an instance of that class, then later
added an attribute to the class itself.  As you'd expect, that
attribute is also visible on the instance.

You second question is a little more difficult to understand.  Classes
don't know about their subclasses, so you wouldn't normally "add a
subclass to a class".  Perhaps if you describe what you're trying to
accomplish, it would be easier to demonstrate how to do it.

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


Re: [Tutor] How to exit this loop in the interpreter

2012-05-03 Thread Jerry Hill
On Thu, May 3, 2012 at 9:57 AM,   wrote:
> Hello all,
>
> I have encountered the following scenario.
> Here is the code - on IDLE on Windows XP.
>
 while True:
>     try:
>         number = raw_input("enter number - ")
>         print number * number
>     except ValueError:
>         print "invalid number"
>     except:
>         print "unspecified exception"
>     else:
>         print "other conditions"
>
>
> enter number - 3
> unspecified exception
>
> What I noticed is that no matter, what input I give, I cannot exit this
> loop. I have tried control-C, control-D etc. all the keys. So how can I exit
> from this loop?

You can't, because you've painted yourself into a corner.  The bare
"except:" line will catch any exception at all.  Including the
KeyboardInterrupt exception that is raised when you hit control-c.  If
you must catch unknown exceptions, but still want to allow the
KeyboardInterrupt exception from pressing control-c to exit your
program, then use "except Exception:"
 instead of a bare "except:" statement.  Since KeyboardInterrupt (and
SystemExit) are not subclasses of Exception, they won't be caught.

KeyboardInterrupt and SystemExit are subclasses of a class called
BaseException, instead of Exception, for this exact purpose.  See more
about python's exception hierarchy here:
http://docs.python.org/library/exceptions.html

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


Re: [Tutor] List Indexing Issue

2012-05-08 Thread Jerry Hill
On Tue, May 8, 2012 at 4:00 PM, Spyros Charonis  wrote:
> Hello python community,
>
> I'm having a small issue with list indexing. I am extracting certain
> information from a PDB (protein information) file and need certain fields of
> the file to be copied into a list. The entries look like this:
>
> ATOM   1512  N   VAL A 222       8.544  -7.133  25.697  1.00 48.89
> N
> ATOM   1513  CA  VAL A 222       8.251  -6.190  24.619  1.00 48.64
> C
> ATOM   1514  C   VAL A 222       9.528  -5.762  23.898  1.00 48.32
> C
>
> I am using the following syntax to parse these lines into a list:
...
> charged_res_coord.append(atom_coord[i].split()[1:9])

You're using split, assuming that there will be blank spaces between
your fields.  That's not true, though.  PDB is a fixed length record
format, according to the documentation I found here:
http://www.wwpdb.org/docs.html

If you just have a couple of items to pull out, you can just slice the
string at the appropriate places.  Based on those docs, you could pull
the x, y, and z coordinates out like this:


x_coord = atom_line[30:38]
y_coord = atom_line[38:46]
z_coord = atom_line[46:54]

If you need to pull more of the data out, or you may want to reuse
this code in the future, it might be worth actually parsing the record
into all its parts.  For a fixed length record, I usually do something
like this:

pdbdata = """
ATOM   1512  N   VAL A 222   8.544  -7.133  25.697  1.00 48.89   N
ATOM   1513  CA  VAL A 222   8.251  -6.190  24.619  1.00 48.64   C
ATOM   1514  C   VAL A 222   9.528  -5.762  23.898  1.00 48.32   C
ATOM   1617  N   GLU A1005  11.906  -2.722   7.994  1.00 44.02   N
""".splitlines()

atom_field_spec = [
slice(0,6),
slice(6,11),
slice(12,16),
slice(16,18),
slice(17,20),
slice(21,22),
slice(22,26),
slice(26,27),
slice(30,38),
slice(38,46),
slice(46,54),
slice(54,60),
slice(60,66),
slice(76,78),
slice(78,80),
]

for line in pdbdata:
if line.startswith('ATOM'):
data = [line[field_spec] for field_spec in atom_field_spec]
print(data)


You can build all kind of fancy data structures on top of that if you
want to.  You could use that extracted data to build a namedtuple for
convenient access to the data by names instead of indexes into a list,
or to create instances of a custom class with whatever functionality
you need.

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


Re: [Tutor] pip errors for numpy, scipy matplotlib

2012-05-11 Thread Jerry Hill
On Fri, May 11, 2012 at 2:42 PM, Bjorn Madsen
 wrote:
> Hi,
> when attempting to use pip to install numpy, scipy matplotlib I get a mile
> of errors. There is simply too much information printed - so it must be a
> systematic error (http://paste.ubuntu.com/982180/). What am I missing/doing
> wrong?

The error messages sound like you're missing a bunch of the thing
required to build the packages you're trying to compile.  It looks
like libraries called Atlas and Blas, plus a fortran compiler, from
the errors you posted.

Are you using ubuntu?  You didn't say, but I see you're using a ubuntu
pastebin.  Are you wedded to compiling and installing with pip?  It's
a whole lot easier to just use the packaging system included with
ubuntu when you can.  In this case you should be able to do `sudo
apt-get install python-numpy` to install numpy.

If you do want to compile and build via pip, I would start by doing
`sudo apt-get build-dep python-numpy` to get all the required
prerequisites installed, then retry installing via pip.

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


Re: [Tutor] special attributes naming confusion

2012-06-06 Thread Jerry Hill
On Wed, Jun 6, 2012 at 4:32 PM, Dave  wrote:
> I'm not sure where this comment belongs, but I want to share my perspective
> on the documentation of these special method names. In the following section
> there is an inconsistency which could be confusing to someone just learning
> Python (e.g., me).
>
> In the sentence on implementing custom mapping objects, the recommended
> method names are listed as the short calling names: eys(), values(),
> items(), etc.
>
> But, in contrast, in the sentence on implementing sequence types, the
> recommended method names are listed as the double underscore internal
> implementation names: __add__(), __radd__(), __iadd__(), __mul__(), etc.
>
> Here's the section of the documentation with this inconsistency. I think it
> would help to use one or the other of these pairs (calling name vs. internal
> implementation name) consistently in this section.

Those aren't pairs, where you can implement either one.  You have to
implement ALL of those methods to correctly emulate one of the built
in container classes.  The difference is that the "normal" method
names (the ones without double underscores) are meant to be called
directly on an instance of your class.  The double underscored names
are called by the internals of python, often in a variety of different
places.

For instance, the __iter__() method is called by the iter() built-in.
It can also called by any other piece of code that needs to acquire an
iterator from a generic container object.  There is no list of all
such pieces of code that could ever call the __iter__() method of your
object.

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


Re: [Tutor] Opening filenames with unicode characters

2012-06-28 Thread Jerry Hill
On Thu, Jun 28, 2012 at 1:55 PM, James Chapman  wrote:
> Thanks Tim, while this works, I need the name to be stored in a variable as
> it's dynamic.
>
> In other words, how do I rewrite
> open(u"blah£.txt")
>
> to be
> filename = "blah£.txt"
> open(filename)

You have to create a unicode-string, not a byte-string.  So, like this:

filename = u"blah£.txt"
open(filename)

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


Re: [Tutor] Opening filenames with unicode characters

2012-06-28 Thread Jerry Hill
On Thu, Jun 28, 2012 at 2:55 PM, James Chapman  wrote:
> Why can I not convert my existing byte string into a unicode string?

That would work fine.

> In the mean time I'll create my original string as unicode and see if that
> solves my problem.
>
 fileName = unicode(filename)
>
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 35:
> invalid start byte

Here's a couple of questions that you'll need to answer 'Yes' to
before you're going to get this to work reliably:

Are you familiar with the differences between byte strings and unicode
strings?  Do you understand how to convert from one to the other,
using a particular encoding?  Do you know what encoding your source
file is saved in?  If your string is not coming from a source file,
but some other source of bytes, do you know what encoding those bytes
are using?

Try the following.  Before trying to convert filename to unicode, do a
"print repr(filename)".  That will show you the byte string, along
with the numeric codes for the non-ascii parts.  Then convert those
bytes to a unicode object using the appropriate encoding.  If the
bytes are utf-8, then you'd do something like this:
unicode_filename = unicode(filename, 'utf-8')

If your bytestring is actually shift-jis encoded, you'd do this instead:
unicode_filename = unicode(filename, 'shift-jis')

If you don't know what encoding your byte string is in, you either
have to give up, guess, or try a bunch of likely possibilities until
something works.  If you really, really have to guess and there's no
way for you to know for sure what encoding a particular byte string is
in, the third party chardet module may be able to help.

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


Re: [Tutor] Opening filenames with unicode characters

2012-06-28 Thread Jerry Hill
On Thu, Jun 28, 2012 at 3:48 PM, James Chapman  wrote:
> Informative thanks Jerry, however I'm not out of the woods yet.
>
>
>> Here's a couple of questions that you'll need to answer 'Yes' to
>> before you're going to get this to work reliably:
>>
>> Are you familiar with the differences between byte strings and unicode
>> strings?
>
> I think so, although I'm probably missing key bits of information.

Okay.  I would start with this article as a refresher:
http://www.joelonsoftware.com/articles/Unicode.html

This isn't a bad reference either:
http://docs.python.org/howto/unicode.html

>> Do you understand how to convert from one to the other,
>> using a particular encoding?
>
> No not really. This is something that's still very new to me.

Okay.  The lowest level way is to work with the strings themselves.
Byte strings (the python2.x str type) have a .decode() method that
will transform a byte string in a particular encoding into the
equivalent unicode string.  Unicode strings have a .encode() method to
convert a unicode string into the equivalent byte string in a
particular encoding.

So, for example:

byte_string = "This is a pound sign: \xA3"

My terminal uses cp1252 as the encoding.  I know that because I
checked sys.stdin.encoding as I was working up this example.  In
CP1252, the pound character is 0xA3.  I looked that up on a chart on
wikipedia.

So, if I print the string, and the encoding of the byte string matches
the encoding on my terminal, everything should look fine:

>>> print byte_string
This is a pound sign: £

That works, because the encoding my terminal knows to display is the
same as the bytes python put out.  If I want to convert that string to
unicode, I could do this:

unicode_string = byte_string.decode('cp1252')

now unicode_string has the unicode version of my original string.  I
can now encode that to any encoding I want.  For instance:

>>> print repr(unicode_string.encode('utf8'))
'This is a pound sign: \xc2\xa3'

>>> print repr(unicode_string.encode('utf-16'))
'\xff\xfeT\x00h\x00i\x00s\x00 \x00i\x00s\x00 \x00a\x00
\x00p\x00o\x00u\x00n\x00d\x00 \x00s\x00i\x00g\x00n\x00:\x00
\x00\xa3\x00'

>>> print repr(unicode_string.encode('shift-jis'))
'This is a pound sign: \x81\x92'

>> Do you know what encoding your source
>> file is saved in?
>
> The name of the file I'm trying to open comes from a UTF-16 encoded text 
> file, I'm then using regex to extract the string (filename) I need to open. 
> However, all the examples I've been using here are just typed into the python 
> console, meaning string source at this stage is largely irrelevant.
>
>> If your string is not coming from a source file,
>> but some other source of bytes, do you know what encoding those bytes
>> are using?
>>
>> Try the following.  Before trying to convert filename to unicode, do a
>> "print repr(filename)".  That will show you the byte string, along
>> with the numeric codes for the non-ascii parts.  Then convert those
>> bytes to a unicode object using the appropriate encoding.  If the
>> bytes are utf-8, then you'd do something like this:
>> unicode_filename = unicode(filename, 'utf-8')
>
 print(repr(filename))
> "This is_a-test'FILE to Ensure$ that\x9c stuff^ works.txt.js"
>
 fileName = unicode(filename, 'utf-8')
> Traceback (most recent call last):
>  File "", line 1, in 
> UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 35: 
> invalid start byte
>
 fileName = unicode(filename, 'utf-16')
>
 fileName
> u'\u6854\u7369\u6920\u5f73\u2d61\u6574\u7473\u4627\u4c49\u2045\u6f74\u4520\u736e\u7275\u2465\u7420\u6168\u9c74\u7320\u7574\u\u205e\u6f77\u6b72\u2e73\u7874\u2e74\u736a'
>
>
>
> So I now have a UTF-16 encoded string, but I still can't open it.

No.  You have mojibake  Try printing that unicode string, and you'll
see that you have a huge mess of asian characters.  You need to figure
out what encoding that byte string is really in.  If you're typing it
on the terminal, do this:

import sys
print sys.stdin.encoding

If the pound sign is being encoded as 0x9c (which it is, based on the
example you showed), then your terminal is using an odd encoding.  At
a guess, cp850, maybe?

>
 codecs.open(fileName, 'r', 'utf-16')
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "C:\Python27\lib\codecs.py", line 881, in open
>file = __builtin__.open(filename, mode, buffering)
> IOError: [Errno 2] No such file or directory: 
> u'\u6854\u7369\u6920\u5f73\u2d61\u6574\u7473\u4627\u4c49\u2045\u6f74\u4520\u736e\u72
> 75\u2465\u7420\u6168\u9c74\u7320\u7574\u\u205e\u6f77\u6b72\u2e73\u7874\u2e74\u736a'
>
>
> I presume I need to perform some kind of decode operation on it to open the 
> file but then am I not basically going back to my starting point?

Once you have the name properly decoded from a byte string to a
unicode string, just supply the unicode string to the open() function.
 Everything should be okay then.

-- 
Jerry
_

  1   2   >