RE: [Tutor] Unexpected result from decimal

2005-01-19 Thread Tony Meyer
> >>> import decimal
> >>> decimal.getcontext().prec = 2
> >>> a = decimal.Decimal(2)
> >>> b = decimal.Decimal(3)
> >>> 100*a/b
> Decimal("67")
> >>> print 100*a/b

This prints "67".

> try - 
> 
> a=decimal.Decimal(2.0)

This will not work.  You can't convert a float directly to a decimal.Decimal
(I believe this is so that you are forced to understand that there are
precision issues involved).  'a = decimal.Decimal("2.0")' will do what you
meant, though.

> b = decimal.Decimal(3)
> print 100*a/b

However, this will print out "67", just as the above did.  The reason is the
one that Tim outlined: precision isn't the number of digits after the
decimal place - when I was at school the latter was called "decimal places"
and precision was "significant digits".

> Jacob- one slight flaw/quirk in Python is if you want floating point
> computations you have to specify a floating point.
[...]
> Same as writing 100/3.0 as opposed to 100/3. Try it. 

Note that you can do 'from __future__ import division' and 100/3 will be the
same as 100/3.0 (and 100//3 will give you 3).

=Tony.Meyer

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


RE: [Tutor] ascii encoding

2005-01-25 Thread Tony Meyer
> time.timezone gives you, I think, the offset between 
> your current timezone and GMT. However, being myself in the GMT zone,
> I don't know exactly if the returned offset is positive or negative
> (it returns 0 here, which makes sense :D ).

Whether or not it's positive or negative depends on which side of GMT/UTC
you are, of course :)  Note that the result in is seconds, too:

>>> import time
>>> time.timezone
-43200
>>> time.timezone/60/60
-12

(I'm in NZ, 12 hours ahead of GMT/UTC).

=Tony.Meyer

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


RE: [Tutor] Should this be a list comprehension or something?

2005-01-25 Thread Tony Meyer
> Well, you can do this with list comprehensions, yeah:
> 
> totalmass = sum([WaterObject.mass for WaterObject in WaterList])
> totaltemp = sum([WaterObject.mass * WaterObject.temp for 
> WaterObject in 
> WaterList]) / totalmass
> return Water(totalmass, totaltemp)
> 
> Doesn't seem that much more Pythonic to me. I find it about as 
> readable as your code, but someone who isn't used to list 
> comprehensions will find that weird-looking.

I would agree that it doesn't seem any more Pythonic.  I think either way is
fairly readable (being able to use 'sum' with list comps helps readability,
IMO).

[...]
> As for the cons, as I said, it may seem less readable than the 
> original version to the non-experienced; and chances are it's slower 
> than the original version since it has to iterate through 4 lists 
> instead of 2.

Timeit gives me 6.73 seconds for the original, 10.70 seconds for list comps,
and 10.98 for gen exps, so it does look like the original is certainly
faster.

=Tony.Meyer

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


RE: [Tutor] Advise...

2005-01-25 Thread Tony Meyer
> Anyway, I know the first thing that some of you are going to 
> say is using eval().
[...] 
> Which, considering that it is supposed to be exactly 117, 
> It's darn good. 
> Unfortunately, it also takes about 10 seconds to do all that.
> Any suggestions? Any advice?

On my machine your version takes about 14 seconds.  If you replace
'eval(fofx)' with '3*x*x' it takes about 0.7 seconds.

Am I allowed to say "don't use eval()" if I'm saying it because it's
extremely slow, rather than for security reasons?  ;)

If the user must be able to enter in the function, then it would be better
to evaluate this once and turn it into some sort of function that you can
call inside the loop (it's the eval that is so expensive).  How to do that
depends a lot on how complex the possible functions can be (if they'll only
include 'x*+/-' and numbers, for example, it's not so tricky).

=Tony.Meyer

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


RE: [Tutor] Advise...

2005-01-25 Thread Tony Meyer
[Tony Meyer]
> If the user must be able to enter in the function, then it 
> would be better to evaluate this once and turn it into some 
> sort of function that you can call inside the loop (it's the 
> eval that is so expensive).

I should have included some code that does this:

"""
from __future__ import division
import psyco
psyco.full()
fofx = raw_input("What is the function? ")
minimum = raw_input("What is the minimum? ")
maximum = raw_input("What is the maximum? ")
start = time.time()
minimum = float(minimum)
maximum = float(maximum)
total = 0
step = 10
x = minimum
a = compile(fofx, '', 'eval')
while minimum <= x <= maximum:
area = eval(a)/step
total = total+area
x = x+1/step
print total
"""

This takes ~1.7 seconds here, so about 8 times faster than without the
compile() call, but about 2.5 times slower than directly with the 3*x*x.

=Tony.Meyer

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


RE: [Tutor] New to Python

2005-01-26 Thread Tony Meyer
[Jason White]
>> I'm curious about good tutorial websites and books to buy.

[Max Noel]
> I learned Python (well, the basics thereof -- enough to do useful 
> stuff on my summer job, anyway ^^) in an afternoon using the official 
> tutorial that's found somewhere on http://www.python.org/. It's very 
> good provided you already have some programming experience 

If you (Jason) are using Windows, then you absolutely want to install Mark
Hammond's pywin32 extensions as well as Python itself.  If you use PythonWin
as your IDE (and you might as well, at least at first), then to get to the
tutorial, you can just open PythonWin, and select "Python Manuals" from the
Help menu, then click "Tutorial".  I absolutely agree that it's the best
place to start.

>> I also have a development question for anybody who might know.  The
>> project I'm working on now to develop my python skills is a prgram to 
>> script control another windows program.  The program doesn't have a 
>> published API so I'll probably need to locate memory addresses data 
>> fields and button routines.

There's a Python library for controlling Windows in this sort of way
(simulating mouse clicks and so on), although the name escapes me at the
moment.  However, are you positive that you can't control it properly?
Check to see if it has a COM interface (you can use PythonWin to do that),
and use that if possible.

=Tony.Meyer

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


RE: [Tutor] Should this be a list comprehension or something?

2005-01-27 Thread Tony Meyer
[Sean Perry]
>> And now, for the pedant in me. I would recommend against naming 
>> functions with initial capital letters. In many languages, this 
>> implies a new type (like your Water class). so 
>> CombineWater should be combineWater.

[Brian van den Broek]
> Do you mean implies by the dominant coding conventions, or 
> by language syntax? (Indulging the curious pedant in me.)

You might want to read PEP 8, which is the official recommendations for
Python code in terms of style.  A bit more than half way down there's a
"Naming Conventions" section which has this:



"""
Modules should have short, lowercase names, without underscores.
[...]
Almost without exception, class names use the CapWords convention.
Classes for internal use have a leading underscore in addition.
[...]
Function names should be lowercase, possibly with words separated by
underscores to improve readability. 
"""

(BTW, 'CombineWater' should be 'combine_water', officially).

=Tony.Meyer

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


RE: [Tutor] Dividing 1 by another number ?

2005-01-30 Thread Tony Meyer
> I'm trying to write a program they may involve
> needing to divide 1 by another number. In the
> program below when I use 4 for the diameter of
> the bore, and 1 for the diameter of the rod,
> and 60 for the PSI, the  force should be 706.8 .
> However the program keeps giving me 0 for "rodarea".
> If I use a value other than 1 the program works
> fine. am I missing something, this the 3rd program
> I have wrote.
[...]
> PI = 3.14
> area = (bore**2/4)*PI
> rodarea = (rod**2/4)*PI

Dividing two integers will give you an integer (truncated) result:

>>> 1/2
0

Dividing an integer by a float (or vice-versa) will give you a float:

>>> 1/2.0
0.5
>>> 1/float(2)
0.5

If you want '1/2' to give you 0.5 (throughout your script), you can do:

>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0

Notice that '//' (with or without the from __future__ import) will give you
the integer result.

=Tony.Meyer

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


RE: [Tutor] Dividing 1 by another number ?

2005-01-30 Thread Tony Meyer
> btw is there a place I can read everyones questions, 
> like I posted, or does this work my emailing a few 
> knowledgable people?

The archives of the list are available here:



(The messages from the future at the top are obviously ones where people's
mailers were in poor shape - ignore those).

=Tony.Meyer

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


RE: [Tutor] Dividing 1 by another number ?

2005-01-30 Thread Tony Meyer
> In that case you need it to use floating point numbers.
> The easiest way is to use 1.0 but if it comes from a table 
> or user entry you might have to explicitly convert:
> 
> one = 1
> other = 42
> result = float(one/other)

What Alan meant, presumably, was this:

one = 1
other = 42
result = float(one)/other

Otherwise the code simply gives 0.0 rather than 0, when we want ~0.0238.
Note that it doesn't matter which one you convert to a float, as long as one
of them is.

=Tony.Meyer

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


RE: [Tutor] Tweaking list comprehensions

2005-02-13 Thread Tony Meyer
>> def approachB(files):
>>
>> isHTML = [filename if filename.endswith('.htm') or\
>>filename.endswith(.html') for filename in files]
>> return isHTML
> 
> No, it should be...
> 
> isHTML = [filename for filename in files if 
> filename.endswith('.htm') or\
> filename.endswith('.html') for filename in files]

Actually:

isHTML = [filename for filename in files if filename.endswith('.htm') or \
  filename.endswith('.html')]

>>> files = "a.html", "b.htm", "c.txt"
>>> [filename for filename in files if filename.endswith('.htm') or
filename.endswith('.html') for filename in files]
['a.html', 'b.htm', 'c.txt', 'a.html', 'b.htm', 'c.txt']
>>> [filename for filename in files if filename.endswith('.htm') or
filename.endswith('.html')]
['a.html', 'b.htm']

FWIW, if you're getting "files" from a directory listing of a local drive,
you might be able to use 'glob.glob("*.htm?")' instead.

=Tony.Meyer

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


RE: [Tutor] writing list to new file

2005-02-13 Thread Tony Meyer
> How would I save a list to a new file
> 
> for example: 
> 
> If line.startswith('XXX'):
> save list to new file
> 
> But I get errors saying only stings can be saved this
> way. 

What do you want to do with the file afterwards?

If you want to load it back in as a list at some later point, then something
like pickle is probably what you want:

>>> l = ['1','2','3','4','5']
>>> import pickle
>>> f = open("temp.txt", "w")
>>> pickle.dump(l, f)
>>> f.close()

The file looks like this:

"""
(lp0
S'1'
p1
aS'2'
p2
aS'3'
p3
aS'4'
p4
aS'5'
p5
a.
"""

If you just want a human to be able to read the file, then you probably just
want to turn the list into a string, e.g.:

>>> l = ['1','2','3','4','5']
>>> f = open("temp.txt", "w")
>>> f.write(','.join(l))
>>> f.close()

The file looks like this:

"""
1,2,3,4,5
"""

=Tony.Meyer

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


RE: [Tutor] writing list to new file

2005-02-13 Thread Tony Meyer
> I'm just trying to create a new file for all
> the lines that startswith my string. So if my original
> file looks like this:
> 
> 1 Line 1
> 1 Line 2
> 2 Line 1
> 2 Line 2
> 3 Line 1
> 4 Line 1
> 
> I want to read in all the ones starting with 1 and
> then save them to a new file. I can get the result I
> want there by using :
> If line.startswith('1'):
>
> But can't figure out how to save these lines to
> another file.

Something like this, perhaps?

"""
def filter_file(in_fn, out_fn, to_match):
fin = open(in_fn, "r")
fout = open(out_fn, "w")
for line in fin:
if line.startswith(to_match):
fout.write(line)
fin.close()
fout.close()
"""

Or, to be concise (but less clear):

"""
def filter_file(in_fn, out_fn, to_match):
open(out_fn, "w").write("".join([line for line in open(in_fn, "r") if
line.startswith(to_match)]))
"""

(That's all one line).

=Tony.Meyer

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


RE: [Tutor] Case acceptance using raw_input

2005-02-15 Thread Tony Meyer
>> Is there a better way for raw_input to accept both caps and 
>> lower case letters than:
[...]
>>if action == 'y' or action == 'Y':
>
> if action in 'yY':
> dostuff()
[...]
> Although, that does mean that if a user enters 'nN' they'll 
> get no, but that shouldn't be a huge problem, and it it does, 
> you can just do a if len(action) != 1...

Alternatively, you could do:

if action.lower() == 'y':

This is the most readable, IMO, but is probably slower (function calls are
expensive) than 'if len(action) == 1 and action in "yY"' or 'if action ==
"y" or action == "Y"'.  (Of course, the difference in speed here is almost
certainly irrelevant).

=Tony.Meyer

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


RE: [Tutor] Intro for interfacing with Microsoft Access?

2005-03-06 Thread Tony Meyer
> Does anyone know of any online resource that explains how to
> interface to Microsoft Access via Python, where the intended
> audience is someone who knows Python, but not the Microsoft innards?

These two pages are quite good:




=Tony.Meyer

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


RE: [Tutor] Intro for interfacing with Microsoft Access?

2005-03-06 Thread Tony Meyer
[Terry Carroll]
>>> Does anyone know of any online resource that explains how to 
>>> interface to Microsoft Access via Python, where the intended 
>>> audience is someone who knows Python, but not the Microsoft innards?

[Tony Meyer]
>> These two pages are quite good:
>> 
>> <http://starship.python.net/crew/bwilk/access.html>
>> <http://www.ecp.cc/pyado.html>

[Terry Carroll]
> Thanks.  Unfortunately, both of those seem to assume you know 
> Python and the Win APIs, but not how to connect the, For 
> someone who doesn't know the APIs, they're actually not very helpful.

The second link has very simple steps - you basically just retype the code
from steps 1 to 3 and you're all connected.  Then pick one of the following
steps, depending on what you want to (read, insert, etc), and retype the
code from there.  Once you have the recordset object (steps 1-3), you can
easily modify the existing examples to do whatever you want just by
referencing the reference material in Access itself (I forget what it's
called - the object reference material that you get to via the macro stuff).

When I first needed to work with Access, I knew nothing about ADO or coding
Access, but something about writing Python, and this got me up and running
very easily.

> But I do appreciate you taking the time to point them out.

No worries.

=Tony.Meyer 

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


RE: [Tutor] new

2005-03-15 Thread Tony Meyer
> Hey I am new at python and i am trying to learn about
> it.  I was wondering if you could tell me how to write
> a range to 100. such as   1+2+3+4+5  ect. without
> writing it out.

Do you want a container with a range in it, like the list
[1,2,3,4,5,...,100]:

>>> range(100)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 99]

Or do you want the sum of a range 1+2+3+4+...+100?:

>>> sum(range(100))
4950

I highly recommend working through the Python tutorial that's included in
the documentation.  It is a great help in figuring out the way things work.
(You can still ask questions here, of course!).

=Tony.Meyer

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


RE: [Tutor] new

2005-03-15 Thread Tony Meyer
> Do you want a container with a range in it, like the list
> [1,2,3,4,5,...,100]:
> 
> >>> range(100)
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 
[...]
> 92, 93, 94, 95, 96, 97, 98, 99]

Opps.  Notice that I did the range 0-99, of course.  But it's still the
function that you want.

[...]
> >>> sum(range(100))
> 4950

And again...

=Tony.Meyer

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


RE: [Tutor] Sorting more than one list

2005-03-31 Thread Tony Meyer
> What's b.index(x) do?
> 
> I'm guessing the for a list Delta = ["a,"b","c"], you get 
> 
> Delta.index("b")
> 
> 1
> 
> Am I right? 

Yes.  For future use, the easiest way to answer a question like that is to
do:

>>> help([].index)
Help on built-in function index:

index(...)
L.index(value, [start, [stop]]) -> integer -- return first index of
value

Or, if you have an idea, just try it out:

>>> Delta = ["a","b","c"]
>>> Delta.index("b")
1

=Tony.Meyer

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


RE: [Tutor] str.split and quotes

2005-04-05 Thread Tony Meyer
> >>> s = 'Hi "Python Tutors" please help'
> >>> s.split()
> ['Hi', '"Python', 'Tutors"', 'please', 'help']
> >>> 
> 
> I wish it would leave the stuff in quotes in tact:
> 
> ['Hi', '"Python Tutors"', 'please', 'help']

You can do this with a regular expression:

>>> import re
>>> re.findall(r'\".*\"|[^ ]+', s)
['Hi', '"Python Tutors"', 'please', 'help']

The regular expression says to find patterns that are either a quote (\")
then any number of any characters (.*)then a quote (/") or (|) more than one
of any character except a space ([^ ]).

Or you can just join them back up again:

>>> combined = []
>>> b = []
>>> for a in s.split():
... if '"' in a:
... if combined:
... combined.append(a)
... b.append(" ".join(combined))
... combined = []
... else:
... combined.append(a)
... else:
... b.append(a)
... 
>>> b
['Hi', '"Python Tutors"', 'please', 'help']

(There are probably tidier ways of doing that).

Or you can do the split yourself:

def split_no_quotes(s):
index_start = 0
index_end = 0
in_quotes = False
result = []
while index_end < len(s):
if s[index_end] == '"':
in_quotes = not in_quotes
if s[index_end] == ' ' and not in_quotes:
result.append(s[index_start:index_end])
index_start = index_end + 1
index_end += 1
if s[-1] != ' ':
result.append(s[index_start:index_end])
return result

>>> print split_no_quotes(s)
['Hi', '"Python Tutors"', 'please', 'help']

=Tony.Meyer

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


RE: [Tutor] str.split and quotes

2005-04-05 Thread Tony Meyer
> I recommend this http://www.amk.ca/python/howto/regex/ 
> and python2x/tools/scripts/redemo.py to learn how to use regexes well.

I also highly recommend  for learning
how to use regexes.

In addition, Kodos is a great tool to both experiment around with regexes
and to test them out:



(It will work with Windows, Linux, Mac...)

=Tony.Meyer

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


RE: [Tutor] str.split and quotes

2005-04-06 Thread Tony Meyer
> That won't work for the general case. I spent about 30 minutes trying 
> to come up with a reliably non-re way and kept hitting bugs like the 
> one here. Given that Tony_combine is a function wrapping Tony's logic:
> 
>  >>> Tony_combine('This will not work as "more than two words" are 
> quoted')
> ['This', 'will', 'not', 'work', 'as', 'than', 'two', '"more words"', 
> 'are', 'quoted']

Opps.  You're right.  This is probably even uglier (can't be bothered
tidying it up), but should work in the more general case and does combine
them up again:

def Tony_combine2(s):
combined = []
b = []
in_quotes = False
for a in s.split():
if '"' in a and in_quotes:
combined.append(a)
b.append(" ".join(combined))
combined = []
in_quotes = False
continue
elif '"' in a and not in_quotes:
in_quotes = True
if in_quotes:
combined.append(a)
else:
b.append(a)
return b

>>> Tony_combine('This will not work as "more than two words" are quoted')
['This', 'will', 'not', 'work', 'as', '"more than two words"', 'are',
'quoted']

Writing your own split or using re is definitely nicer, though.

=Tony.Meyer

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


RE: [Tutor] str.split and quotes

2005-04-07 Thread Tony Meyer
> Is there a reason to prefer one over the other?  Is one
> faster?  I compiled my regular expression to make it quicker.

With Python 2.4 I get these results (all imports are factored out, all give
the same result except for CSV which strips the "s) with timeit.py:

Own split:   26.8668364275
Tokenize:78.8295112926
Rejoin:  11.237671827
Re:  13.9386123097
Re compiled:  8.19355839918
CSV: 23.3710904598

Of course, speed isn't everything (or you wouldn't be using Python).
Readability is probably the most important factor - I'd say that a re
(particularly a verbose re) would be the most readable, followed by using
the CSV module, followed by writing your own split function.  Since re is
also the fastest of the methods suggested so far, it seems like a good
choice.

> What a rich language!  So many choices.

Somewhat ironically, one of the tenets of Python is "there should be one--
and preferably only one --obvious way to do it." (type "import this" at an
interactive prompt).

=Tony.Meyer
import re
import csv
import tokenize
from StringIO import StringIO

def split_with_csv(s):
input = StringIO(s)
return csv.reader(input, delimiter=' ').next()

r = re.compile(r'\".*\"|[^ ]+')
def split_with_re_compiled(s):
return r.findall(s)

def split_with_re(s):
return re.findall(r'\".*\"|[^ ]+', s)

def split_with_tokenize(s):
results = [tokenTuple[1] for tokenTuple in 
tokenize.generate_tokens(StringIO(s).readline)]
return results[:-1]

def split_and_rejoin(s):
combined = []
b = []
in_quotes = False
for a in s.split():
if '"' in a and in_quotes:
combined.append(a)
b.append(" ".join(combined))
combined = []
in_quotes = False
continue
elif '"' in a and not in_quotes:
in_quotes = True
if in_quotes:
combined.append(a)
else:
b.append(a)
return b

def split_no_quotes(s):
index_start = 0
index_end = 0
in_quotes = False
result = []
while index_end < len(s):
if s[index_end] == '"':
in_quotes = not in_quotes
if s[index_end] == ' ' and not in_quotes:
result.append(s[index_start:index_end])
index_start = index_end + 1
index_end += 1
if s[-1] != ' ':
result.append(s[index_start:index_end])
return result

if __name__ == "__main__":
import timeit

t = timeit.Timer("temp3.split_no_quotes('Hi \"Python Tutors\" please 
help')", "import temp3")
print "No quotes", t.timeit()
t = timeit.Timer("temp3.split_with_tokenize('Hi \"Python Tutors\" please 
help')", "import temp3")
print "Tokenize", t.timeit()
t = timeit.Timer("temp3.split_and_rejoin('Hi \"Python Tutors\" please 
help')", "import temp3")
print "Rejoin", t.timeit()
t = timeit.Timer("temp3.split_with_re('Hi \"Python Tutors\" please help')", 
"import temp3")
print "Re", t.timeit()
t = timeit.Timer("temp3.split_with_re_compiled('Hi \"Python Tutors\" please 
help')", "import temp3")
print "Re compiled", t.timeit()
t = timeit.Timer("temp3.split_with_csv('Hi \"Python Tutors\" please 
help')", "import temp3")
print "CSV", t.timeit()

t = timeit.Timer("temp3.split_no_quotes('This will not work as \"more than 
two words\" are quoted')", "import temp3")
print "No quotes", t.timeit()
t = timeit.Timer("temp3.split_with_tokenize('This will not work as \"more 
than two words\" are quoted')", "import temp3")
print "Tokenize", t.timeit()
t = timeit.Timer("temp3.split_and_rejoin('This will not work as \"more than 
two words\" are quoted')", "import temp3")
print "Rejoin", t.timeit()
t = timeit.Timer("temp3.split_with_re('This will not work as \"more than 
two words\" are quoted')", "import temp3")
print "Re", t.timeit()
t = timeit.Timer("temp3.split_with_re_compiled('This will not work as 
\"more than two words\" are quoted')", "import temp3")
print "Re compiled", t.timeit()
t = timeit.Timer("temp3.split_with_csv('This will not work as \"more than 
two words\" are quoted')", "import temp3")
print "CSV", t.timeit()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


RE: [Tutor] str.split and quotes

2005-04-07 Thread Tony Meyer
> Wow Tony.  That is so generous of you to do this experiment.  
> It must be a great re engine.

It really wasn't much effort - just copying & pasting it all together and
throwing in a few timeit statements.  The timeit module is another great
thing about Python :)

> "Obvious" doesn't mean we can, necessarily, all see it 
> immediately, or that even any one of us can see it without 
> study, thought and inspiration, but, it means we can all see 
> it once it's pointed out.

Nicely said :)

=Tony.Meyer

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


RE: [Tutor] Python backwards program

2005-04-12 Thread Tony Meyer
> I am very new to programming and I have an assignment
> to have a raw_input string that is inputted by the user
> and then is printed backwards.  Can anyone help me?  I can
> get it to print regular but backwards in not working.

I guess that I shouldn't give code if this is for an assignment, but if you
are using Python 2.4, then try seeing what the "reversed()" built-in
function does.  If you're not using Python 2.4, then read up about "slices"
- which is when you get subsections of a string (e.g. "tony"[2:4] is "ny").
You can pass a 'direction' in a slice as well.

=Tony.Meyer

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


RE: [Tutor] Python backwards program (fwd)

2005-04-12 Thread Tony Meyer
> I have read about loops, strings, tuples.  I am taking this 
> class on distance education and I am lost with this 
> assignment.  I have read what Tony has wrote and that does me 
> no good.  I do not understand what he is talking about.

Which bits?  The whole lot?  I teach university students programming, so
maybe the language doesn't fit with you.  Whatever it is, just say what
doesn't make sense and I'll happily rephrase it, or expand, or whatever is
needed.

> I understand how slicing works and what the numbers mean.  I 
> know what the -1 and such like that mean.  I know what the 
> len function does. 

Why then do you not understand that the answer is simply this?

"""
my_string = raw_input("Prompt:")
print my_string[::-1]
"""

(I'm not trying to be offensive; I would like to know why you don't
understand that, if you understand how slicing works).

As Danny said, if you can't simply use slicing (it is pretty simple), then
you're probably after a loop.  You want to run through the string, but with
a negative step.  The most explicit way to do this is to have an index
variable that keeps track of where you are up to in the string.  Normally
this would go from 0 to the length of the string, but you want it to go
backwards, so from the length of the string to 0.  Each time around the
loop, you want the index to go down one.

So:

start index at length of string
while index has not reached 0:
print character at string[index]
decrease index by one

Do you see what that is doing?  It translates very simply into Python (one
of the advantages of the language):

index = len(my_string)
while index >= 0:
print my_string[index]
index = index -1

This will of course print out the string one character per line, which isn't
what you want.  But that's easy enough to change.

There are other ways of doing this, but I suspect something like the above
is what you are after in a beginning course.  You could, for example, build
a new (reversed) string, rather than printing it out as you go, and then
print that out.

In C, it would look something like this:

"""
for (unsigned int i==0; ++i)
{
printf("%c", my_string[i]);
}
"""

Which is a fairly common sort of exercise when you're learning C, since C
doesn't have the nice slicing capabilities that Python does.

> I am wasting you guys time.

Not at all.  We come here to try and help.

=Tony.Meyer

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


RE: [Tutor] Python backwards program (fwd)

2005-04-12 Thread Tony Meyer
> We will not do your homework for you
[snip]

The slicing answer I posted is possibly the answer, but I assume that the
loop solution, which I didn't post (in Python), is what is actually
required.  If slicing is what is wanted, then I apologise for giving an
answer! :)

=Tony.Meyer

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


RE: [Tutor] Python backwards program

2005-04-13 Thread Tony Meyer
> In the print word [::-1] line it gives me this message
> (sequence index must be an integer)  What does that mean

As others have said, it means you're using Python 2.2 or older (so can't use
extended slicing).  It seems likely that what you're after is the loop
approach that has been mentioned by various people, including me.  Have a go
with that method, and give us the code that you have, along with any
error/output that you get.

=Tony.Meyer

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


RE: [Tutor] newbie intro to pickle

2005-04-15 Thread Tony Meyer
> Does anyone know if there are some *beginner*-user-friendly tutorials
> out there for pickle? Or can give a sample of how you would implement
> it into a VERY SIMPLE program? Obviously I can get to the "import
> pickle" step, but once I'm past that, I'm totally lost!

There's the example in the documentation:



But to put it really simply, you can just use it like this:

>>> import pickle
>>> my_list = [4,5,6,6]
>>> pickle.dump(my_list, file("temp.pik", "w"))

(restart Python here to show that it works across sessions)

>>> import pickle
>>> my_list_reloaded = pickle.load(file("temp.pik"))
>>> my_list_reloaded
[4, 5, 6, 6]

=Tony.Meyer

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


Re: [Tutor] character format

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

>From the email address, chances are that this was a New Zealand cultural
assumption.  Ah, the French, lumping all English speakers under the American
banner .

Anyway, the explanation was right, if the label wasn't.  They are simply
hexidecimal representations of characters.

Denise: there are many uses for this - to know what you need to do, we need
to know what you are trying to do.  Where are you finding these characters?
Are they in a file?  If so, what type of file is it, and what do you want to
do with the file?  Those questions are more likely to lead you to the module
you're after.

I believe Max's guess was that the file is compressed with bzip (the first
two characters will be BZ, as you found).  Try doing:

>>> import bz2
>>> print bz2.decompress(data)

Where data is a string containing the characters you have.  (Although you
say that compression is unlikely, the BZ characters would be a big
co-incidence).

=Tony.Meyer

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


Re: [Tutor] character format

2005-05-11 Thread Tony Meyer
[me, typo'ing]
>> hexidecimal representations of characters.

[Bob Gailer]
> Did you mean "hexadecimal"?

Sigh.  Yes.  I did a one character typo.  Please forgive me.

=Tony.Meyer

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


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

2005-05-22 Thread Tony Meyer
> I have the local machine's administration privilege.
[...]
> When I run the command as you point out, I got the following
> messages
>
> (5, 'InitiateSystemShutdown', 'Access is denied.')

The process itself needs to have the privilege.  This message has complete
instructions:



=Tony.Meyer

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


Re: [Tutor] Covert numbers to hex fails

2005-05-24 Thread Tony Meyer
> FAILS
> --
> >>> value = 1234567890
> >>> hexoutput = hex('%d' % (value))
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: hex() argument can't be converted to hex

Just don't convert the number to a string, e.g:

>>> value = 1234567890
>>> hexoutput = hex(value)
>>> hexoutput
'0x499602d2'

=Tony.Meyer

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