Re: [Tutor] Combining dictionaries

2005-09-06 Thread bob
At 04:14 PM 9/6/2005, Mike Cheponis wrote:
>On Tue, 6 Sep 2005, Danny Yoo wrote:[snip]
>
>How can I actively help fix these Python bugs?

I am concerned when you use the term "bugs". The behaviors you describe are 
part of the design of Python, and they work as designed. To me a bug is a 
failure of something to work as designed.

 Microsoft has much more practice designing things that don't work as 
designed than the Python development team.  Even as I attempt to type 
this I am reminded that Eudora also has a lot of experience delivering 
buggy (or at least user-unfriendly) software.

How to influence the evolution of Python?

0 - subclass things that you wish behaved the way you want, then write 
magic methods e.g. __add__ and __radd__ to provide new behavior for +.

1 - develop modules that add features. Promote them thru sourceforge or 
Useless Python or the Vaults of Parnassus or the Python Cookbook, and 
certainly thru this e-mail list.

2 - write PEPs. See http://www.python.org/peps/ for the PEPs written to 
date. Someplace there's a PEP writing guideline, but I don't know where. 
Some PEPs make it into the language. 

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


Re: [Tutor] Combining dictionaries

2005-09-07 Thread bob


I enjoy "philosophical" discussions like this. To help us have
common terminology I present some quotes from dictionary.com: 
---
bug:
An unwanted and unintended property of a program or piece of hardware,
especially one that causes it to malfunction. Antonym of
feature.
---
feature: 
An intended property or behaviour (as of a program). Whether it is good
or not is immaterial (but if bad, it is also a misfeature) 
---
misfeature:
A feature that eventually causes lossage, possibly because it is not
adequate for a new situation that has evolved. Since it results from a
deliberate and properly implemented feature, a misfeature is not a bug.
Nor is it a simple unforeseen side effect; the term implies that the
feature in question was carefully planned, but its long-term consequences
were not accurately or adequately predicted (which is quite different
from not having thought ahead at all). A misfeature can be a particularly
stubborn problem to resolve, because fixing it usually involves a
substantial philosophical change to the structure of the system
involved.
Many misfeatures (especially in user-interface design) arise because the
designers/implementors mistake their personal tastes for laws of nature.
Often a former feature becomes a misfeature because trade-offs were made
whose parameters subsequently change (possibly only in the judgment of
the implementors). "Well, yeah, it is kind of a misfeature that file
names are limited to six characters, but the original implementors wanted
to save directory space and we"re stuck with it for
now."
-end of definitions --
Does not it seem odd that if a
and b are dictionaries, c = a + b does not
result in their union?  
Given that the (relatively new) set type in Python, use boolean operators
& and | for union and intersection, I'd prefer & to +.
Does it not seem to violate the
Principal of Least Astonishment to notice
what print "spam " "eggs"*3 does?
Any language that imposes operator precedence will have unexpected
outcomes. That is why I have always liked APL, which has no precedence.
Strictly right-to-left evaluation with () to group operations in some
other order.
And, surely, you are not
suggesting that Python 2.4 represents the zenith of
programming language design?
I certainly hope not. I am merely asserting that there is a design that
has evolved over 14 or so years, and that my ability to use a language
depends on my learning it rather than expecting it to behave the way I
want (expect) it to.
Having worked with APL I am always disappointed that Python does not have
native array operations. I 'd like to write [1,2,3] + [2,4,6] and get
[3,6,9], and +/[1,2,3] and get 6. Unfortunately Python does not work that
way.
Having recently used _javascript_ I find it has features that make some
aspects of programming easier than Python!
Incidentally, I've been writing
compilers and interpreters since 1968 and have
an EECS degree from MIT, so I do have a clue.
I started studying formal language theory (on my own) in 1972, maintained
the APL interpreter in 1975 and devised and helped implement my first
language in 1976. My BSEE from RPI predates any CS departments.

Bob Gailer
phone 510 978 4454 

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


Re: [Tutor] making a table

2005-09-08 Thread bob


At 04:34 PM 9/8/2005, [EMAIL PROTECTED] wrote:
I
would like to construct a table for my program but it does not seem to be
coming out evenly. Could someone please let me know what to do so that
everything will work out correctly? 
def main(): 
   print "This program shows a table of Celsius
temperatures and there Fahrenheit equivalents every 10 degrees from 0C to
100C" 
   print "C F" 
   for i in(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100): 
   fahrenheit = (9.0/5.0) * i + 32

   print i 
   print "   ",

   print fahrenheit 
    
main() 
1 - you are getting C and F on different lines because there is no ,
after print i. After you fix that you will get:
C F
0 32.0
10 50.0
... similar lines deleted
40 104.0
... similar lines deleted
100 212.0
Now the trick is to get things lined up. Here % formatting comes
in:
print "  C   F"
...
    print '%3s    %5.1f' % (i,
farenheit)
Giving:
  C 
F
  0 32.0
 10 50.0
etc.

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


Re: [Tutor] Aschenputtel problem

2005-09-16 Thread bob
At 10:12 AM 9/15/2005, Christopher Arndt wrote:
>Hi,
>
>I wonder if there is a shorter form of the following idiom:
>
>list1 = []
>list2 = []
>for item in original_list:
> if condition(item):
> list1.append(item)
> else:
> list2.append(item)

Consider (5 lines instead of 7):

lists = [[], []]
for item in original_list:
 lists[condition(item)].append(item)
list1 = lists[0]
list2 = lists[1]

This assumes condition() returns 0 or 1 (True)

or if you don't mind the result in sets (assumes unique elements):

set1 = set([x for x in original_list if cond(x)])
set2 = original_list - set1 

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


Re: [Tutor] Why won't it enter the quiz? (off topic)

2005-09-16 Thread bob
At 09:30 PM 9/16/2005, Nathan Pinno wrote:
>Hey all,
>
>It looks like I started another running debate, the last time I did this, it
>went forever it seemed.
>
>Any hints or help on that original question?
>
>For clarity, I'll ask it again:
>
>Why won't it enter the quiz? Here is the code again:
>
>{code}
>
>import random
>
>def add(a,b):
> answer = a+b
> guess = float(raw_input(a," + ",b," = "))
> return answer, guess
>
>num1 = random.choice(range(1,10)) ### To limit the numbers chosen from 1-9
>num2 = random.choice(range(1,10))
>
>while 1:
> q = random.choice(range(15,31)) ### to choose the number of questions
> cq = 1 ### To find the current question
> correct = 0
> while cq >= q: ### To find whether or not to end the quiz.

cq is never >= q

> print cq
> answer, guess = add(num1,num2)
> if guess != answer:
> print "Incorrect! The correct answer is: ",answer
> cq += 1
> elif guess == answer:
> print "Correct!"
> correct += 1
> cq += 1
> else:
> print "Questions: ",q
> print "Correct: ",correct
> print "Percent Correct: ",(cq/q)*100
> break
>
>print "Goodbye."
>
>{/code}
>
>Thanks for the help in advance,
>Nathan Pinno
>- Original Message -
> > Date: Fri, 16 Sep 2005 22:52:51 -0400
> > From: Nathan Coulter <[EMAIL PROTECTED]>
> > Subject: Re: [Tutor] Why won't it enter the quiz? (off topic)
> > Cc: Tutor@python.org
> > Message-ID: <[EMAIL PROTECTED]>
> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> >
> > Byron wrote:
> >> Hi Nathan,
> >>
> >> Wow, I have to give you some good credit -- you are quite the sneaky and
> >> innovative business guy.  You get the free tutors here to help write
> >> your programs and when they are finished, you sell them on your website
> >> for $20.00 each!  I bet more businesses wish they could do business the
> >> way you do!  Quite efficient, I must admit... 
> >>
> >
> > I'd bet that almost EVERYONE on this list is selling software with the
> > skills they may have picked up here.  There's nothing wrong with that!
> > And any of Nathan's customer's that want to try to build it themselves are
> > free to look here on the list to see exactly how he did it.  Kudos,
> > Nathan!
> >
> > Bye,
> > Poor Yorick
> >
> >
> > --
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Iterating over sorted dictionary keys in one line

2005-09-18 Thread bob
At 10:30 AM 9/18/2005, Kent Johnson wrote:
>Marcin Komorowski wrote:
> > I know that one of the ways to iterate over sorted dictionary keys is:
> > keylist = dictionary.keys()
> > keylist.sort()
> > for key in keylist:
> > ...
> >
> > Is there a way to do this in a single line.  Something like this would
> > be ideal:
> > for key in dictionary.keys().soft():
>
>Python 2.4 adds the sorted() function which returns a sorted copy of a 
>list. You can say
>for key in sorted(dictionary.keys()):

To be more precise - sorted() operates on any iterable and returns a list.

>and since iterating a dictionary is the same as iterating its keys you can 
>shorten this to
>for key in sorted(dictionary):
>
>Kent
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]

2005-09-22 Thread bob


At 06:42 PM 9/22/2005, Nathan Pinno wrote:
The URL is
http://zoffee.tripod.com/purchasecomprogs.htm
[snip]
At your invitation I visited the site. I personally would not purchase
anything listed there due to insufficient information. I don't know what
I'm getting!
I suggest you dedicate a page to each program with at least one
screenshot and explanation of what the program does.

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


Re: [Tutor] Diamond Equivalent

2005-09-22 Thread bob
At 03:46 PM 9/22/2005, [EMAIL PROTECTED] wrote:
>I am coming to Python from Perl. Does Python have anything like the diamond
>operator found in Perl?

Some of us (who don't know Perl) might help you if you tell us what the 
diamond operator does. How could we get to first base with it? What are its 
facets? Does is have a heart counterpart? Ca it sing? 

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


Re: [Tutor] Diamond Equivalent

2005-09-23 Thread bob
At 04:37 AM 9/23/2005, [EMAIL PROTECTED] wrote:
>[snip]
>In perl I can write this:
>
>@array = <>;
>print @array;
>
>If I save that and call it from the command line, I can include the name of a
>file after the script name. It will read in the file, putting each line 
>into an
>element of the array.
>
>I know how to open a specific file using Python. I wanted to know how to give
>a Python script a file name in the command line, and have it open that file.

So there are 2 parts to the question:

(1) how to retrieve command line arguments:

import sys
arg1 = sys.argv[1]

(2) how to read the lines of a file (whose path is in arg1) into an array

array = file(arg1).readlines()

That's all. Of course you don't need an intermediate variable; you can just:

import sys
array = file(sys.argv[1]).readlines()

and if you want to print the results:

print array 

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


Re: [Tutor] File mode r+

2005-09-24 Thread bob
At 01:11 AM 9/24/2005, Shitiz Bansal wrote:
>Hi,
>I want to update a textfile using the r+ file mode.
>contents of file:
>
>abcd
>efgh
>ijkl
>mnop
>qrst
>uvwx
>yx12
>
>my scripts is:
>
>file1=open("aa.txt",'r+')

Instead of readline, use skip to position the file to where you want to 
overwrite it.
file1.seek(10)

>file1.readline()
>file1.readline()
>file1.write("1234\n")
>file1.close()
>
>This should replace the third line with 1234.
>However it does nothing.
>
>Moreover the script:
>
>file1=open("aa.txt",'r+')
>file1.write("1234\n")
>file1.close()
>
>does replace the first line with 1234.
>
>could anyone explain what is happening?
>
>shitiz
>
>__
>Do You Yahoo!?
>Tired of spam?  Yahoo! Mail has the best spam protection around
>http://mail.yahoo.com
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Sum of List Elements

2005-09-24 Thread bob
At 08:11 AM 9/24/2005, Luke Jordan wrote:
>Hi All,
>
>I have spent an embarrassingly large amount of time trying to solve what 
>on its face seems like a simple problem.
>
>I have a list of intergers, and I want to assign the sum of the intergers 
>in the list to a variable. There are only intergers in the list.

In addition to the other solutions there is the (more generic?) use of the 
operator module and reduce function:

import operator
reduce(operator.add, (1,2,3))

Explore operator to see what other functions you can use.

Also there are the array handling modules such as numarray.

You can also define your own classes based on list and write methods to do 
these operations. 

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


Re: [Tutor] (no subject)

2005-09-24 Thread bob


At 03:29 PM 9/24/2005, [EMAIL PROTECTED] wrote:
Hello

How would I get the following program to accept inputs of exam scores
from 0-100 with A being 100-90, B being 89-80, C being 79-70, D being
69-60, and F being everything less than 60? 
Many solutions are available. One could use an if statement:
if g >= 90: s = 'A'
elif g >= 80: s = 'B'
...
else: g = 'F' 
although that can be hard to 
maintain.
Or associate the lower limit with the data and search using a
loop:
scores = [("A",90), ("B",80), ("C".70),
("D",60),("F",0) ] 
for letter, number in scores:
    if g >= number:break
print "The score of your exam is", letter
This separates the data from the program structure and becomes much
easier to maintain / extend, apply to new situation.
If you are using a database then you could store these value pairs in a
table and use SQL to retrieve the desired letter.
When the number ranges have a nice progression, you can reduce the number
to an index:
print "The score of your exam is",
"FEDCBAA"[g/10] # this is simpler code but harder to
read/maintain.
Or - knowing that chr(65) = "A", chr(66) = "B" you
could convert the number to be in the range 65..70 and use 
chr()
import string

You do not refer to the string module, so there is no need to import it.
Also be ware that it will eventually go away.

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


Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]

2005-09-26 Thread bob


At 10:34 AM 9/26/2005, Nathan Pinno wrote:
Bob,
 
I did what you suggested. Take
another look, and tell me if you were a potential customer, would you
purchase something?
 I tried
http://zoffee.tripod.com/purchasecomprogs.htm
I got "Sorry but the page ... is not here." 
 
Sorry, but the page or the file that you're looking for is not here.

 
Why not take the challenge? It's not like I'm asking much.
 
Nathan Pinno


- Original Message - 

From: bob 

To: Nathan Pinno 

Cc: tutor@python.org 

Sent: Thursday, September 22, 2005 10:08 PM

Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]

At 06:42 PM 9/22/2005, Nathan Pinno wrote:

The URL is http://zoffee.tripod.com/purchasecomprogs.htm

[snip]

At your invitation I visited the site. I personally would not purchase anything listed there due to insufficient information. I don't know what I'm getting!

I suggest you dedicate a page to each program with at least one screenshot and explanation of what the program does. 

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

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


Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]

2005-09-26 Thread bob


At 10:56 AM 9/26/2005, Nathan Pinno wrote:
The actual URL is
http://zoffee.tripod.com/purchasecompprogs.htm



I did what you suggested. Take another look, and tell me if you were a potential customer, would you purchase something?

No. For one thing I can (if I didn't already have one) buy a "real" calculator for $1.00. Also my WIndows op sys comes with a calculator with much more capabilities.
Also, seeing your screenshots leads me to suspect that the programs are character mode rather than providing a GUI.  This would be a turn off to most computer users.
One marketing clue - tell me how the program will benefit me. All I see is that it will take more work to do a calculation than using a "real" calculator. I think there is no benefit.
I say these things not to discourage you but to encourage you to find ways to give customers something they need/want and can't get some other way or as nice or as cheap or as fun or  IOW if I'm to spend $10 I want some real benefit.
Think about why McDonald's is successful. Why people will spend $ for food that is not outstandingly good. 
How do you find an equivalent benefit for software users?


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


Re: [Tutor] Quick way to find the data type

2005-09-27 Thread bob
At 12:08 PM 9/27/2005, Bernard Lebel wrote:
>Hello,
>
>Let say I have a string. The value of the string might be 'False',
>'True', '3', '1.394', or whatever else. Is there a quick way to
>convert this string into the appropriate data type other than with
>try/except?

eval()? 

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


Re: [Tutor] call a def/class by reference

2005-09-28 Thread bob
At 04:29 PM 9/28/2005, DS wrote:
>What I'm hoping to avoid is an
>explicit reference to any of the called functions within the program.
>By doing it that way, it would avoid a maintenance problem of having to
>remember to put a reference for every new function in the calling program.

Try this - a class in which you define all the functions. The __init__ 
method builds the dictionary.

 >>> class X:
... funcs = {}
... def y(self):
... pass
... def __init__(self):
... for itemname in dir(self):
... if not itemname.startswith('__'):
... item = getattr(self, itemname)
... if callable(item):
... self.funcs[itemname] = item
...
 >>> y = X()
 >>> y.funcs
{'y': >}


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


Re: [Tutor] call a def/class by reference

2005-09-29 Thread bob
At 08:23 AM 9/29/2005, DS wrote:
>bob wrote:
>
> > At 04:29 PM 9/28/2005, DS wrote:
> >
> >> What I'm hoping to avoid is an
> >> explicit reference to any of the called functions within the program.
> >> By doing it that way, it would avoid a maintenance problem of having to
> >> remember to put a reference for every new function in the calling
> >> program.
> >
> >
> > Try this - a class in which you define all the functions. The __init__
> > method builds the dictionary.
> >
> > >>> class X:
> > ... funcs = {}
> > ... def y(self):
> > ... pass
> > ... def __init__(self):
> > ... for itemname in dir(self):
> > ... if not itemname.startswith('__'):
> > ... item = getattr(self, itemname)
> > ...     if callable(item):
> > ... self.funcs[itemname] = item
> > ...
> > >>> y = X()
> > >>> y.funcs
> > {'y': >}
> >
>
>
>Thanks bob, that's an interesting approach.  That would be one huge class.

Well if you have lots of functions you will have one *huge* module. The 
additional class stuff is minor.

Also note that you can accomplish a similar thing by defining the functions 
outside any class and then finding them in globals(). Having said that I 
like the class approach in that it becomes a container for the functions 
you want to expose and other functions defined outside the class will be 
ignored. 

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


Re: [Tutor] Load PDF

2005-10-03 Thread bob
I am moving this to the python-win32 list where we can better handle it.
Please send further replies there.

At 03:41 AM 10/3/2005, Pepe Pena wrote:
>I am attempting to load a pdf file programatically within Adobe Reader 
>using the Adobe Acrobat 7.0 Browser Control Type Library.  If I run this 
>code PythonWin terminates abruptly, can anyone suggest any changes I 
>should make to the following lines of code, thanks.
>
>import win32com.client
>test = win32com.client.Dispatch("AcroPDF.PDF.1")
>test.LoadFile("D:\\sql.pdf")

I confirm the behavior. I have no explanation. 

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


Re: [Tutor] Line continuation with readlines

2005-10-05 Thread bob
At 07:20 PM 10/3/2005, Craig MacFarlane wrote:
>Hello,
>
>Is there a way to make line continuation work with
>the readlines function?
>
>i.e.

Do you mean e.g.?

>   this is \
> one line.

I assume the above is a 2 line file you wish to read using a file object's 
readlines method. There is nothing native to help you. I suggest you use 
the read method, then remove any sequence of \ followed by \n then split at \n.

input = file('c:/foo.txt').read()
input2 = input.replace('\\\n', '')
input3 = input2.split('\n')

Now you have a list of "logical" lines. Note there are no \n at the end. 
readlines leaves the \n at the end of the lines. 

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


Re: [Tutor] Regex help

2005-10-09 Thread bob
At 09:10 PM 10/9/2005, Bill Burns wrote:
>I'm looking to get the size (width, length) of a PDF file. Every pdf
>file has a 'tag' (in the file) that looks similar to this
>
>Example #1
>MediaBox [0 0 612 792]
>
>or this
>
>Example #2
>MediaBox [ 0 0 612 792 ]
>
>I figured a regex might be a good way to get this data but the
>whitespace (or no whitespace) after the left bracket has me stumped.
>
>If I do this
>
>pattern = re.compile('MediaBox \[\d+ \d+ \d+ \d+')
>
>I can find the MediaBox in Example #1 but I have to do this
>
>pattern = re.compile('MediaBox \[ \d+ \d+ \d+ \d+')
>
>to find it for Example #2.
>
>How can I make *one* regex that will match both cases?

pattern = re.compile('MediaBox \[ *\d+ \d+ \d+ \d+') 

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


Re: [Tutor] help with elif statements

2005-10-12 Thread bob
At 06:04 PM 10/12/2005, [EMAIL PROTECTED] wrote:
>hello
>
>below is my code and everytime I input a value of 16 or more it keeps
>returning sophomore. could anyone help me figure out what to change so
>that it won't return sophmore for things greater than or equal to 16?
>
>def getcredits(num):
> if num < 7:
> return 'Freshman'
> elif num >= 7:
> return 'Sophomore'
> elif num <16:
> return 'Sophomore'
> elif num >= 16:
> return 'Junior'
> elif num < 26:
> return 'Junior'
> else:
> return 'Senior'

I have a preference for separating data and control structure. So I would:

def getcredits(num):
 rank = ((7, 'Freshman'), (16, 'Sophomore'), (26, 'Junior'), (999, 
'Senior')
 for limit, class in rank:
 if num < limit:
 return class

>def main():
> g = input('Enter number of credits:')
> print 'Your standing is %s' % (getcredits(int(g)))
>
>main()
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] passing variable to python script

2005-10-13 Thread bob
At 04:09 PM 10/13/2005, Marc Buehler wrote:
>hi.
>
>i want to pass an argument (a number) to a python
>script when running it:
> > python script.py 
>
>i want to be able to use  within script.py
>as a parameter.
>
>how do i set this up?

In the sys module there is a property argv. The docs say: "The list of 
command line arguments passed to a Python script. argv[0] is the script name"

import sys
if len(argv) < 2:
   print "Usage: script.py "
   sys.exit(0)
try:
   numeric_arg = int(argv[1])
except:
   print '1st argument must be numeric."
   sys.exit(0)

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


Re: [Tutor] extract plain english words from html

2005-10-14 Thread bob
At 03:50 PM 10/14/2005, Marc Buehler wrote:
>hi.
>
>i have a ton of html files from which i want to
>extract the plain english words, and then write
>those words into a single text file.

http://www.crummy.com/software/BeautifulSoup/ will read the html, let you 
step from tag to tag and extract the text. Almost no effort on your part.

[snip] 

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


Re: [Tutor] Focus on the functions [Was Re: if-else statements]

2005-10-16 Thread bob
At 08:11 AM 10/16/2005, Norman Silverstone wrote:
>I am an elderly person somewhat physically handicapped with some
>experience  programming in basic and pascal, many years ago. In order to
>keep myself mentally active I decided to have a look once again at
>programming and chose python as a good language to start with. So, I had
>a look at 'Dive into Python', bought a couple of books, 'Python
>Programming for the Absolute Beginner' and 'Learn to program Using
>Python'.
>
>All was well to start with until I came to the section on functions. I
>am finding it very difficult to grasp the reasoning behind the use of
>functions and how and when to use them.

1) did you ever use GOSUB in Basic or procedure or function in Pascal?
If so, same thing here.

2) functions:
a) as a way to set aside pieces of code `that might otherwise obscure
 an algorithm. For example if I have a complex calculation to do inside
 some loop it may make the program easier to read to put the
 calculation in a function and call the function from w/in the loop.
b) the classical use of functions is to package code that might be
 called from more than one place rather than writing the same code
 twice.
c) in Python (different than Basic or Pascal) functions are objects that
 can be passed around, allowing for things like dictionaries that
 choose which function to use based on some input or condition.
d) in classes functions become methods, a way to evoke a behavior of
an object.

[snip] 

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


Re: [Tutor] Saving command line keyed input?

2005-10-19 Thread bob
At 02:12 PM 10/19/2005, CPIM Ronin wrote:
>I know that one should use IDLE or a choosen editor for any substantial
>Python coding! However, if one  happens to have written some interesting
>doodlings on the regular command line interface (under Windows XP in my
>case), is there an easy way to save ALL input to date into a selected file?

The way I do it is: select the text by dragging with the mouse (a 
recangle), then hit Enter. This puts it on the clipboard. Then go to where 
you want it and paste. As I did here:

Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> "hi"
'hi'
 >>>


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


Re: [Tutor] iteration is overwriting the previous set value

2005-10-19 Thread bob
At 04:16 PM 10/19/2005, Jonas Melian wrote:
>def _pre_save(self):
> for field in [self.name, self.native_name]:
> if not field.istitle():
> #print field.title()
> field = field.title()
>
>The change I try to do there (field = field.title()) is not being applied

Yes it is. field (a local variable) is being replaced by field.title(). You 
can confirm that by putting
print field after the assignment.

However I guess you want the change to apply to self.name and self.native_name.

Unfortunately you have a list containing the values of self.name and 
self.native_name. Even if you modified the list elements (which assignment 
to field does not do) self.name and self.native_name would not be affected.

Use getattr and setattr to access and assign the attributes, which you 
specify by name.

def _pre_save(self):
 for fieldname in ['name', 'native_name']:
 setattr(self, fieldname) = getattr(self, fieldname).title()

[snip] 

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


Re: [Tutor] iteration is overwriting the previous set value

2005-10-19 Thread bob
At 04:16 PM 10/19/2005, Jonas Melian wrote:
>def _pre_save(self):
> for field in [self.name, self.native_name]:
> if not field.istitle():
> #print field.title()
> field = field.title()

And FWIW there is no benefit in using "if not field.istitle():" since it 
calculates the title value anyway you might just as well assign it without 
checking. 

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


Re: [Tutor] iteration is overwriting the previous set value

2005-10-20 Thread bob
At 12:32 AM 10/20/2005, Jonas Melian wrote:
>bob wrote:
>
> > At 04:16 PM 10/19/2005, Jonas Melian wrote:
> >
> >> def _pre_save(self):
> >> for field in [self.name, self.native_name]:
> >> if not field.istitle():
> >> #print field.title()
> >> field = field.title()
> >>
> >> The change I try to do there (field = field.title()) is not being
> >> applied
> >
> >
> > Yes it is. field (a local variable) is being replaced by
> > field.title(). You can confirm that by putting
> > print field after the assignment.
> >
> > However I guess you want the change to apply to self.name and
> > self.native_name.
> >
> > Unfortunately you have a list containing the values of self.name and
> > self.native_name. Even if you modified the list elements (which
> > assignment to field does not do) self.name and self.native_name would
> > not be affected.
> >
> > Use getattr and setattr to access and assign the attributes, which you
> > specify by name.
> >
> > def _pre_save(self):
> > for fieldname in ['name', 'native_name']:
> > setattr(self, fieldname) = getattr(self, fieldname).title()
> >
> > [snip]
> >
>This fails:
>SyntaxError: can't assign to function call

Oops me bad. Did not test!  setattr(self, fieldname,  getattr(self, 
fieldname).title())


>Danny Yoo's goes ok
>
>You've the reason: there is no benefit in using "if not field.istitle():"

Is that a question or an appreciation? If question:

It takes execution time to test to see if something is already set. If the 
variables are already set the cost of checking them to avoid assigning then 
is about the same as the cost of just assigning. If the variables are not 
set then the cost of checking and assigning is twice the cost of just 
assigning. Also just assigning is less code to write and maintain. 

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


Re: [Tutor] new user question about while loops

2005-10-25 Thread bob


At 10:53 PM 10/25/2005, Nick Eberle wrote:
Content-class:
urn:content-classes:message
Content-Type: multipart/alternative;
boundary="_=_NextPart_001_01C5D9F1.A836CF4F"
Sorry for potential double post, error with first send
--
Hello all,
 
I had a new question about python. I am pretty
much in tutorial learning stages, but attempting to create sample
programs not in my book to learn how to construct scripts.
 
I understand the format of while loops, but is
it possible to use the random.randrange function in them?
 
My goal, create a program that flips a coin 100
times, at the end it says the number of times it flipped heads and
flipped tails.
 
My dilemia, how do I get this to work with a
while loop? I tried intially assigning
 
heads=0
tails=1
 
then I figured I could just do a while loop and
then use the random function each time. At the end it could count the
number of times the random generated a 0 or a 1.
 
However I can't seem to construct it in a way
that makes or works. 
Show us your code, as flawed as it might be. Then we can advise
you.

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


Re: [Tutor] new user question about while loops

2005-10-26 Thread bob


Thank you for posting your code. That really helps us see where you are
and therefore how to help.
I encourage you to "desk check" your code: pretend you are the
computer: write down the values of variables and expressions as things
change. Evaluate each statement to see what it does.
Example:
heads    tails    flip   
flip < 100 while flip < 100:
0   
1   100   
False loop not
entered
program ends.
I hope you understand why the loop is not entered. If not please (re)read
an explanation of while.
Noticing that you would alter the loop condition. To do that you need to
ask "When do I want the loop to end?"
Let's say you changed it to: while flip <= 100. Now your "desk
check" would look like:
heads    tails    flip   
flip <= 100 while flip <= 100:
0   
1   100   
True
loop entered
   
99 
random.randrange(2)
has no effect since nothing is done with the value returned 
flip < 100  
break
True leaves the
loop
print "\nThe amount of times tails came up
was" , tails , "The amount of times heads came up was" ,
heads
results in: The amount of times tails came up was 1 The amount of times
heads came up was 0
I hope this helps. 


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


Re: [Tutor] File IO Help again

2005-10-27 Thread bob
At 12:18 PM 10/27/2005, Mike Haft wrote:
>Apologies for not making things clearer last time.
>
>My specific problems are:
>
>why can I not get the readline() or readlines() functions to work, I'm
>told they are not defined whenever I try.

Mike * Oh * Mike ... and all others ...

Please Post The Code and the Traceback. Otherwise We Cannot Help You. As 
Much As We Want to be We are Not MindReaders.


>Also the following:
>
>if line[:1] == "1":
>
>collects data from month 1, 10, 11, and 12. How do I make the readfile
>function I defined count through 1 to 12 and retreive the fields I need?

This does not compute for me. I have no idea what you want!

>Can I just use a for loop type of construction and substitute an x
>variable where there is curently a [:1] and a "x" i.e.:
>
>if line[:y] == x:
>
>If not why not? What must I do.
[snip] 

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


Re: [Tutor] File IO Help again

2005-10-27 Thread bob
At 01:42 PM 10/27/2005, Adam wrote:
> >if line[:1] == "1":
>
>This line won't work because you're getting the first 2 characters from 
>the line

Oh? Did you test that? When I do that I get 1 character. Why? Because 
slicing goes UP TO the 2nd argument.
 >>> 'abc'[:1]
'a' 

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


Re: [Tutor] Can anyone help me?

2005-10-27 Thread bob
At 07:07 PM 10/27/2005, Nathan Pinno wrote:
>Hey all,
>I am trying to create a program that draws 6 numbers between 1 and 49 at 
>random for creating lottery tickets. I want to have a better chance when I 
>play.

Define "better chance". Lottery odds are how many tickets you buy relative 
to how many tickets everyone else has bought. No program will improve or 
degrade your odds. The only way you can reduce your odds is to buy more 
than one ticket with the same numbers.

Keep in mind that a lottery is as truly random as one can get (assuming no 
rigging). There is no memory of past outcomes involved nor of better 
guessing techniques. 

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


[Tutor] Plea for Meaningful Subject Lines (was: Can anyone help me?)

2005-10-27 Thread bob
Please in future provide meaningful subject lines. It makes it a lot easier 
to track the threads.

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


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

2005-10-27 Thread bob
At 08:06 PM 10/27/2005, Jason Massey wrote:
>All you need is the line continuation character, '\':
>
>if (condition 123 and \
>condition 456) :

Did you test that (or even read it)? That is a syntax error line 
continuation or not! Also recall that the parentheses obviate the need for 
the \. 

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


Re: [Tutor] Can anyone help me?

2005-10-28 Thread bob
At 09:42 PM 10/27/2005, Nathan Pinno wrote:

>If I create a program that randomly draws 6 numbers, its like the lottery. 
>According to an article I read in Reader's Digest, if you get a Quick Pick 
>- which is six numbers at random - you increase your odds of winning.

Odds are how many tickets you buy relative to how many tickets everyone 
else has bought. Has nothing to do with the mechanism for generating 
numbers. Any guesses you make are "random". You might as well buy fortune 
cookies and copy the numbers in them. Or add 1 to each number. Or  No 
action on your part will ensure that you win, or give you a better shot at 
winning than anyone else.

>I want to create a program that will imitate the Quick Pick process for 
>myself.

So ask the lottery people what random number algorithm they use and program 
it for yourself. Not that doing that will make any difference. 

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


Re: [Tutor] equivalent of 'last' in perl

2005-10-28 Thread bob
At 09:50 PM 10/27/2005, Johan Meskens CS3 jmcs3 approximated:
>what is Python's equivalent of 'last' in perl?
>
>if flag == 1:
> break

Yes. If flag is either 1 or 0 you may code it thus:

if flag:
   break

That's not the whole truth. Most types have a value that is seen as false 
in boolean expressions.
They includes 0 '' None False [] (,) {} 

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


Re: [Tutor] Can anyone help me?

2005-10-28 Thread bob


At 07:28 AM 10/28/2005, Smith, Jeff wrote:
Aren't the odds just based on
how many tickets you buy?  The odds aren't
affected by different people buying more tickets.  If only one
person
buys a ticket in the entire lottery system, his odds of winning are
the
same as if two people play, and the same as if 20 million
play.
According to the wikipedia: "In
probability
theory and
statistics the
odds in favor of an event or a proposition are the quantity
p / (1-p), where p is the
probability of the
event or proposition." If you assign equal probability of winning to
each ticket then odds are how many tickets you buy relative to how many
tickets everyone else has bought. 
The probability of a ticket winning is 1 / m**n where m is the
highest number possible and n is the number of numbers. If a lottery uses
6 numbers each in the range 1..42 then the probability of a ticket
winning is 1/5489031744. 
All of this is mathematics. Sometimes one or more tickets win. Is that
"luck"?

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


Re: [Tutor] Can anyone help me?

2005-10-28 Thread bob


At 08:08 AM 10/28/2005, Smith, Jeff wrote:
But
the odds that you will win are not impacted by the number of tickets that
are sold in total...only the number you buy.  When you take into
account the total number of tickets sold, all you get are the odds that
the lottery will be won by anyone.
 
I'm also a little confused by
that def of odds.  Consider flipping a coin.  The probability
that it will come up heads is 1/2.  That def says that the odds in
favor of it coming up heads is 1.
Ah there's the rub. Odds are not "in favor". The odds of heads
is 1 and the odds of tails is 1. The odds therefore are the same. If you
flip 2 coins then the odds of both being heads is 1/3, ditto both tails.
Odds of being different is 1/2.
 
Jeff
 


-Original Message-

From: bob
[mailto:[EMAIL PROTECTED]]


Sent: Friday, October 28, 2005 10:52 AM

To: Smith, Jeff; Tutor@python.org

Subject: Re: [Tutor] Can anyone help me?

At 07:28 AM 10/28/2005, Smith, Jeff wrote:

Aren't the odds just based on how many tickets you buy?  The
odds aren't

affected by different people buying more tickets.  If only one
person

buys a ticket in the entire lottery system, his odds of winning are
the

same as if two people play, and the same as if 20 million
play.

According to the wikipedia: "In
probability
theory and
statistics the
odds in favor of an event or a proposition are the quantity p /
(1-p), where p is the
probability of the
event or proposition." If you assign equal probability of winning to
each ticket then odds are how many tickets you buy relative to how many
tickets everyone else has bought. 

The probability of a ticket winning is 1 / m**n where m is the
highest number possible and n is the number of numbers. If a lottery uses
6 numbers each in the range 1..42 then the probability of a ticket
winning is 1/5489031744. 

All of this is mathematics. Sometimes one or more tickets win. Is
that "luck"? 



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


Re: [Tutor] Can anyone help me?

2005-10-28 Thread bob
At 08:03 AM 10/28/2005, Nathan Pinno wrote:
>Hey,
>I created it. Want to see the code?
>Here it is:
>[code]
>import random
>numbers = []

Move this inside the loop following if q == 1 and get rid of the occurrence 
of this statement following print numbers. Less code, easier to read, more 
to the point.

>while True:
> q = int(raw_input("Do you want a lottery number drawing? 1 for yes, 2
>for no "))

This could fail if user enters a string that does not represent an integer. 
Either stick it in a try: block or leave the input character. I prefer the 
latter as there is no advantage to treating it as a number.

> if q == 1:
> for i in range(6):
> draw = random.choice(range(1,50))
> numbers.append(draw)
> print numbers
> numbers = []
> elif q == 2:
> break
> else:
> print "Read the instructions please."
>[/code]
>
>Enjoy!
>Nathan Pinno
>For great sites go to: http://falcon3166.tripod.com
>MSN Messenger: [EMAIL PROTECTED],com
>Yahoo! Messenger: spam_swatter31
>ICQ: 199020705
>AIM: f3mighty
>- Original Message -
>From: "Alan Gauld" <[EMAIL PROTECTED]>
>To: "Nathan Pinno" <[EMAIL PROTECTED]>; 
>Sent: Friday, October 28, 2005 2:01 AM
>Subject: Re: [Tutor] Can anyone help me?
>
>
> > Nathan,
> >
> > look at the functions in the random module.
> > randrange() would be one potential candidate.
> >
> > Alan G
> >
> > - Original Message -
> > From: "Nathan Pinno" <[EMAIL PROTECTED]>
> > To: 
> > Sent: Friday, October 28, 2005 3:07 AM
> > Subject: [Tutor] Can anyone help me?
> >
> >
> > Hey all,
> > I am trying to create a program that draws 6 numbers between 1 and 49 at
> > random for creating lottery tickets. I want to have a better chance when I
> > play. Can anyone help me code this or show me how to, please?
> > Thanks,
> > Nathan Pinno
> > For great sites go to: http://falcon3166.tripod.com
> > MSN Messenger: [EMAIL PROTECTED],com
> > Yahoo! Messenger: spam_swatter31
> > ICQ: 199020705
> > AIM: f3mighty
> >
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Turning kwargs into scalars

2005-11-01 Thread bob
At 08:52 PM 10/31/2005, Steve Bergman wrote:
>Say I have a function:
>def f(self, **kwargs) :

FWIW you don't have a function at this point. You have a def statement 
which must be followed by at least one indented statement, which in turn 
must be executed. Then you have a function.

>and I want to take the key/value pairs and create a set of variables with 
>the names of the keys.
>For example, if I say:
>f(x=5, y=2)
>I want to create local variables 'x' and 'y' in the function, with values 
>of 5 and 2 respectively.
>How could I do this?

This is an FAQ. It can be done. However there are better ways to accomplish 
the same thing. Namely use the dictionary kwargs and look things up by key.

Would you give an example of what you'd do with variables x and y after 
creating them? 

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


Re: [Tutor] while/if/elif/else loops

2005-11-02 Thread bob
At 02:36 PM 11/1/2005, Zameer Manji wrote:
>Ok after looking at everyones replies my program looks like this:
>
>#Coin Toss Game
>#Zameer Manji
>import random
>
>print "This game will simulate 100 coin tosses and then tell you the
>number of head's and tails"
>
>tosses = 0
>heads = 0
>tails = 0
>
>while tosses<100:
> if tosses<100:
> coin = random.randrange(2)
> tosses +=1
> if coin == 0:
> heads +=1
> print "Heads"
> else:
> tails +=1
> print "Tails"
> else:
> print "100 tosses have been simulated. Please wait for your results"
>
>print "Out of", tosses, ",", heads, "were heads and", tails, "were tails."

Good progress. Note that
 if tosses<100
will always succeed, since the while ends when tosses is 100. Therefore the 
first print statement never happens.

Here are some incremental refinements to help you get a taste of 
programming and Python

Refinement 1 put the first print where it will execute. But what is there 
to wait for?

>while tosses<100:
> coin = random.randrange(2)
> tosses +=1
> if coin == 0:
> heads +=1
> print "Heads"
> else:
> tails +=1
> print "Tails"
>print "100 tosses have been simulated. Please wait for your results"
>print "Out of", tosses, ",", heads, "were heads and", tails, "were tails."

Refinement 2 - use for and range() instead of while:

>for tosses in range(100):
> coin = random.randrange(2)
> if coin == 0:
> heads +=1
> print "Heads"
> else:
> tails +=1
> print "Tails"
>etc.

Refinement 3 - test result of randrange directly:

>for tosses in range(100):
> if  random.randrange(2):
> tails +=1
> print "Tails"
> else:
> heads +=1
> print "Heads"
>etc.

Refinement 4 - compute heads once:

>for tosses in range(100):
> if random.randrange(2):
> tails +=1
> print "Tails"
> else:
> print "Heads"
>heads = 100 - tails
>etc.

Radical Refinement 1 - use list comprehension instead of for. Use the sum 
function:

import random
coins = [random.randrange(2) for i in range(100)]
print "1 for heads, 0 for tails", coins
# 1 for heads, 0 for tails [1, 1, 1, 0, 1, 1, 0, 0, 1, 0 ...]
heads = sum(coins)
print "Heads %i Tails %i" % (heads, 100-heads)
# Heads 64 Tails 36

Have fun groking all there is to programming and Python. 

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


Re: [Tutor] printing statement

2005-11-03 Thread bob
At 11:31 AM 11/3/2005, Johan Geldenhuys wrote:
>Hi all,
>Just a quick question;
>
>How do I code this output:
>"""
>files  dirs
>==
>"""
>
>I want to print something a few space away from the left side or in the
>middle of the line.

In the Python Library Reference look up 2.3.6.2 String Formatting 
Operations - % interpolation

In general you create a "template" of the desired output with %s (or other 
conversion type) wherever you want a value substituted.
"%-15s%-15s" % ('files', 'dirs') will give
"files  dirs   "
"%-15s%-15s" % (filename, directory) will give
"funny.doc  c:\root"
assuming the variabies filename, directory have the values shown.
the - means left align, 15 is field width. 

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


Re: [Tutor] printing statement

2005-11-03 Thread bob
At 11:31 AM 11/3/2005, Johan Geldenhuys wrote:
>Hi all,
>Just a quick question;

FWIW saying that does not help. It takes time to read it, and I can judge 
the question length by reading the question. The real concern is what does 
it take to construct an answer. 

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


Re: [Tutor] File IO

2005-11-03 Thread bob
At 01:34 PM 11/3/2005, Michael Haft wrote:
>Hello,
>  I tried the following code:
>
>def readSOMNETM(inputName):
> input = open(inputName, "r")
> result = []
> for line in input:
> fields = line.split()

   # add this; it will show you what line(s) have less than 8 fields
   if len(fields) < 8:
   print "Line too short", line
   continue

> data = fields[1] + fields[2] + fields[7]
> result.append(data)
> input.close()
> return result
>
>
>print "Here goes"
>print "Enter filename:"
>filename = raw_input("Name:")
>print readSOMNETM(filename)
>print "might work"
>
>on  a file that lookes like this:
>
>Monthly Weather Data, LAU73M.MET, converted from:
>BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR 01/01/1973-31/12/1973
>VAP, DEWP CALCULATED FROM MEASURED AVTEMP AND HUMID DATA
>MONTH   RAINAVTEMP  S10 RAD SUN WINDEVAPW
>**
>1   22.50.3 *   54.615.1*   11.9
>2   16.11.8 *   110 51.1*   18.1
>3   16.44.8 *   227.5   94.5*   36.8
>4   19.55.9 *   286.3   89  *   45.5
>5   36.113.2*   448.5   164.6   *   83
>6   36  16.9*   525.7   208.8   *   105.7
>7   37.718.2*   459.7   165.4   *   98.6
>8   29.318.2*   463.8   206.8   *   97.9
>9   27  14.8*   277.5   119.5   *   58.7
>10  57.67.6 *   158.7   72.2*   31.3
>11  23.43.9 *   98.375.6*   19.1
>12  14  0.7 *   55.538  *   12.5
>
>
>And recieved the following error:
>
>Traceback (most recent call last):
>   File "C:\Python24\INProgress.py", line 15, in -toplevel-
> print readSOMNETM(filename)
>   File "C:\Python24\INProgress.py", line 6, in readSOMNETM
> data = fields[1] + fields[2] + fields[7]
>IndexError: list index out of range
>
>Essentially I'm trying to write a bit of code that can take any of the
>fields in the above data i.e. rain temp evap for each month for a hundred
>or so files like this one and spit out a file at the end that has the data
>in a different format.
>
>Any help would be very much appreciated I need to get this done by the end
>of next week

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


Re: [Tutor] File IO

2005-11-03 Thread bob
[snip] Colin: your replies to 2 e-mails indicate that you have either not 
read the e-mails or the prior responses. Please consider the work others 
put into replying before replying.

Example: I suggested % formatting in a reply. You replied to that by saying 
the same thing.

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


Re: [Tutor] printing statement

2005-11-04 Thread bob


At 10:02 PM 11/3/2005, Johan Geldenhuys wrote:
Found it. This is what I was
looking for:
"""
>>> print ('file'+'dir'.center(20))+('\n'+'='*15)
file    dir
===
>>>   
"""
I am glad you found what you wanted. I'm sad that you did not tell us
more precisely what you wanted, as we could have steered you in that
direction. 
center() puts spaces to the right of dir. It that part of what you
wanted, or just a side effect.?
I'd find less () easier to read:
print 'file'+'dir'.center(20)+'\n'+'='*15
and 2 print statements even better:
print 'file'+'dir'.center(20)
print '*15
It's actually a string operator
'center(width)' that I was looking for.
I saw the '%', but that is what I wanted to use.
Do you also appreciate the power of %? I hope you learn to use it
also.
[snip]

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


Re: [Tutor] Namespace Problem

2005-11-04 Thread bob
At 05:47 PM 11/4/2005, Carroll, Barry wrote:
>I have a function that makes use of several global variables:
>
>##
>Include struct

Did you mean "import"?

>ABC = 1
>DEF = 2
>xyz = 0
>def do_stuff(in_str):
> hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str))
> newstr = hdr+in_str

Works find for me. Is there anything else you are not showing us?

>When I run the program containing this code I get this error:
>
> >
>Traceback (most recent call last):
>   File "sample.py", line 43, in ?
> ret_data = do_stuff(data)
>   File "sample.py", line 17, in do_stuff
> hdr = struct.pack('@2BH', ABC|DEF,xyz,len(in_str))
>UnboundLocalError: local variable 'xyz' referenced before assignment
> >
>
>The error goes away if I include a 'global' statement at the top of the
>function:
>
>##
>def do_stuff(in_str):
> global xyz
> hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str))
>##
>
>Why does the interpreter choke on xyz and not on ABC or DEF?
>
>Barry
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] pack

2005-11-05 Thread bob
At 01:57 PM 11/5/2005, Shi Mu wrote:
>when I clicked 'quit' button,
>there is no response. I want to close the interface by clicking 'x',
>the interface could not be closed.
>i had to close PYTHONWIN to get out of the program.

That is a known problem running Tkinter stuff under PythonWin. Others may 
have a solution for you.
[snip] 

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


Re: [Tutor] main

2005-11-05 Thread bob
At 03:39 PM 11/5/2005, Shi Mu wrote:
>It is very hard for me to understand why we need the following line?
>if __name__ == "__main__":

We don't need it. Often we code a module for importing into another module. 
But sometimes we also want to run the module independently as a Python 
program, perhaps just to test it, or for other purposes.
if __name__ == "__main__": is one way to test whether the module has been 
imported or is running standalone. When run standalone __name__ is 
"__main__". When imported __name__ is the module name.

Now is it easier to understand?

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


Re: [Tutor] Python and Semantic Web

2005-11-08 Thread bob
At 08:19 AM 11/8/2005, Matt Williams wrote:
>Dear List,
>
>Does anyone know of any python semweb tools? I'm especially interested
>in tools to build and handle ontologies. I've come across CWM (built by
>Tim BL) but not that much else. I'd be really interested in anything
>that can interface with a DIG reasoner.
>
>Really, I'm looking for a pythonic version of something like Protege or
>SWOOP

Acronym Limit Error! That takes the record for Unknown Acronym/Term 
Density. So I can't be of any help. I hope there are some on this list who 
recognize and can help.

Otherwise please expand some of the concepts for the rest of us.


>Thanks,
>Matt
>--
>Dr. M. Williams MRCP(UK)
>Clinical Research Fellow
>Cancer Research UK
>+44 (0)207 269 2953
>+44 (0)7834 899570
>http://acl.icnet.uk/~mw
>http://adhominem.blogspot.com
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Trouble with classes - Pypeg again

2005-11-21 Thread bob


At 08:52 PM 11/20/2005, ->Terry<- wrote:
-BEGIN PGP SIGNED
MESSAGE-
Hash: SHA1

Ok, I've got my peg game roughed out and I'm having
problems.
The error is:
Traceback (most recent call last):
   File "pypeg.py", line 113, in ?
 main()
   File "pypeg.py", line 107, in main

x.draw_board()
# Refresh screen
   File "pypeg.py", line 30, in draw_board
 screen.blit(Peg.peg, (Peg.pegs[i]))  # Blit
it.
AttributeError: class Peg has no attribute 'peg'
screen.blit(Peg.peg, (Peg.pegs[i]))

Peg is the name of a class rather than an instance of a class.
Instances of Peg have the attribute peg. The class itself does not.
Without analyzing your code in detail I'm not sure of the fix, except to
suggest you put an instance of Peg in place of Pe.
The new code is at:
<
URL:http://members.socket.net/~tvbare/pypeg/new_pypeg.py>
I'm confused as to why. The whole OO picture
has my head reeling, but I thought I had some
grasp of the basics. Now I'm not so sure. d:^)
Thanks much,
- -- 
 Terry

"Be who you are and say what you feel, because those
  who mind don't matter and those who matter don't mind."
 
-- Dr. Seuss
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.7 (GNU/Linux)
iD8DBQFDgVKHQvSnsfFzkV0RAnlyAJ9snqBt0GOWS7IpimsMkB2xaBqu2gCbBovs
ATTVhm0JbWiz+VfKSxXrGqY=
=oGAu
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org

http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Help with objects

2005-11-21 Thread bob
At 08:38 PM 11/21/2005, Vincent Wan wrote:
>I'm trying to write a tree data structure as part of my first
>object oriented program
>
>I have an error "can't assign to function call" caused by this line:
>Tree.nodeList(self.name) = self

Tree.nodeList[self.name] = self

>however, nodeList is a dictionary I'm trying to index.
>
>Beyond the error I'm still not sure I understand how to make and
>use a tree data structure using objects.
>
>Thank you for the help
>
>Here is my code
>
># obj_tree1.py
>
>import random
>
># constants that control the simulation
>NUMBER_REPS = 10# run's the simulation
>MAX_LINAGES = 10# number of species in each run
>BRANCHING_PROBABILITY = 0.5
>
>class Tree(object):
>  numLinages = 0# keeps track of how many nodes there are
>  nodeList = {}# keeps track of the nodes
>  class Node(object):
>  def __init__(self, name):
>  self.name = name# an integer
>  self.alive = True
>  self.descendents = {}# nodes descending from self
>  Tree.numLinages += 1# records node creation
>  Tree.nodeList(self.name) = self# makes node
>accesable from tree
>  def __init__(self):
>  nodeList(0) = Tree.Node(0)# adds a root node 0 to the tree
>  def AddBranch(self, offspring):
>  self.descendents(offspring) = Tree.Node(offspring)# adds
>a descendent node
>  def NumLinages( ):
>  return Tree.numLinages
>  NumLinages = staticmethod(NumLinages)
>
>currentTree = Tree()
>
>for i in range(NUMBER_REPS):
>  j = 0
>  while j <= currentTree.NumLinages():   # checks all node because
>their names are sequential integers
>  if j.alive:
>  if random.random() >= BRANCHING_PROBABILITY:
>  currentTree.AddBranch(j, (currentTree.NumLinages() +
>1)) # creates a new node
>  j += 1
>
>
>Vincent Wan
>
>
>--
>PhD Candidate
>Committee on the Conceptual and Historical Studies of Science
>University of Chicago
>
>PO Box 73727
>Fairbanks, AK 99707
>
>wan AT walrus DOT us (change CAPS to @ and . )
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Help with objects

2005-11-22 Thread bob
At 09:04 PM 11/21/2005, Vincent Wan wrote:
>Thank you bob. I fixed the errors where I tried to index a dictionary
>with name()
>so so that they say name[]
>
>>>Beyond the error I'm still not sure I understand how to make and
>>>use a tree data structure using objects.
>
>There is a new error as well
>
>Traceback (most recent call last):
>   File "/Users/Wally/obj_tree1.py", line 28, in -toplevel-
> currentTree = Tree()
>   File "/Users/Wally/obj_tree1.py", line 21, in __init__
> nodeList[0] = Tree.Node(0)# adds a root node 0 to the tree
>NameError: global name 'nodeList' is not defined
>
>Code with error bob fixed fixed throughout
>
># obj_tree1.py
>
>import random
>
># constants that control the simulation
>NUMBER_REPS = 10# run's the simulation
>MAX_LINAGES = 10# number of species in each run
>BRANCHING_PROBABILITY = 0.5
>
>class Tree(object):
> numLinages = 0# keeps track of how many nodes there are
> nodeList = {}# keeps track of the nodes

nodeList is a property of class Tree.

> class Node(object):
> def __init__(self, name):
> self.name = name# an integer
> self.alive = True
> self.descendents = {}# nodes descending from self
> Tree.numLinages += 1# records node creation
> Tree.nodeList[self.name] = self# makes node 
> accesable from tree
> def __init__(self):
> nodeList[0] = Tree.Node(0)# adds a root node 0 to the tree

To refer to a property of the class: Tree.nodeList[0] = 
Tree.Node(0)# adds a root node 0 to the tree

> def AddBranch(self, offspring):
> self.descendents[offspring] = Tree.Node(offspring)# 
> adds a descendent node
> def NumLinages( ):
> return Tree.numLinages
> NumLinages = staticmethod(NumLinages)
>
>currentTree = Tree()
>
>for i in range(NUMBER_REPS):
> j = 0
> while j <= currentTree.NumLinages():   # checks all node because
>their names are sequential integers
> if j.alive:
> if random.random() >= BRANCHING_PROBABILITY:
> currentTree.AddBranch(j, (currentTree.NumLinages() +
>1)) # creates a new node
> j += 1
>
>Thank you for the help
>
>
>Vincent Wan
>
> 
>--
>PhD Candidate
>Committee on the Conceptual and Historical Studies of Science
>University of Chicago
>
>PO Box 73727
>Fairbanks, AK 99707
>
>wan AT walrus DOT us (change CAPS to @ and . )

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


Re: [Tutor] Newbie question

2005-11-22 Thread bob


At 12:20 PM 11/22/2005, Liam Clarke-Hutchinson wrote:
Hi
Eric, 
 
Either - 
 
add this line to the end of your scripts
-
discard = raw_input("Press enter to finish.")
 
Or - 
 
Click on Start > Run... type cmd.exe and
use DOS to move to the directory where your scripts are stored and run
them via Python there.
This is preferred, since any exception traceback will remain
visible.

 It's not trivial when you're starting.
:-)
 
Regards, 

Liam
Clarke-Hutchinson

-Original Message-
From: [EMAIL PROTECTED]
[
mailto:[EMAIL PROTECTED]] On Behalf Of Douglass,
Erik
Sent: Wednesday, 23 November 2005 3:03 a.m.
To: tutor@python.org
Subject: [Tutor] Newbie question


I am trying to follow some online first timer tutorials, and I am
writing the practice scripts in notepad (only w32 at work
L)..   I save the script
with a .py extension, and when I run it it opens for a brief moment in a
command prompt then closes before I even have a chance to see what it
says.  This may seem trivial, but Python also happens to be my first
language so this is all new to me.    Using Python
2.4.2


 


Thanks for any help.


 


Erik


 
A new monthly electronic newsletter covering all aspects of MED's work is
now available.  Subscribers can choose to receive news from any or
all of seven categories, free of charge: Growth and Innovation, Strategic
Directions, Energy and Resources, Business News, ICT, Consumer Issues and
Tourism.  See
http://news.business.govt.nz
for more details.

 
 

 
  
govt.nz - connecting you to New Zealand
central & local government services


Any opinions expressed in this message are
not necessarily those of the Ministry of Economic Development. This
message and any files transmitted with it are confidential and solely for
the use of the intended recipient. If you are not the intended recipient
or the person responsible for delivery to the intended recipient, be
advised that you have received this message in error and that any use is
strictly prohibited. Please contact the sender and delete the message and
any attachment from your computer. 

___
Tutor maillist  -  Tutor@python.org

http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] TRULY NEWBIE - MENTOR NEEDED

2005-11-22 Thread bob
At 02:41 PM 11/22/2005, mike donato wrote:
>Greetings, I am new student to programming and am experimenting with PYTHON.
> >From what I have read, seems to be a very versatile language. In the
>following excercise I am getting an error
>
>class String(str, Object):

try -> class String(str, object):

>shift = 6
>
> mask = ~0 << (31 - shift)
>
> def __hash__(self):
> result = 0
> for c in self:
> result = ((result & String.mask) ^
> result << String.shift ^ ord(c)) & sys.maxint
> return result
>
> # ...
>
>
>
>Traceback (most recent call last):
>   File "", line 11, in -toplevel-
> class String(str, Object):
>NameError: name 'Object' is not defined
> >>>
>
>_
>Express yourself instantly with MSN Messenger! Download today it's FREE!
>http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] sort list alphabetically

2005-11-23 Thread bob
At 09:55 AM 11/23/2005, lmac wrote:
>i have a list with the dirs/files from the current path. When i use
>sort() to sort the list alphabetically the list is still unsorted.

When you say "unsorted" - are the list members in the same order as 
before the sort?

>dirs_files = os.listdir(os.getcwd())
>print dirs_files
>dirs_files.sort()
>print dirs_files

Works for me. On my computer:
 >>> dirs_files = os.listdir(os.getcwd())
 >>> for x in dirs_files[:10]:x
"'01GRTfiles"
'archive'
'backup'
'CU'
'data'
'documents'
'error_tbls_in'
'error_tbls_out'
'forms'
'GRTFiles'
 >>> dirs_files.sort()
 >>> for x in dirs_files[:10]:x
"'01GRTfiles"
'CU'
'DIST_TEST.DBF'
'DUP_ATTR2.BAK'
'DUP_ATTR2.DBF'
'GRTFiles'
'GRT_CS_SA.DBF'
'GRT_ITEM_XREF.DBF'
'IMP_MC_CR.BAK'
'IMP_MC_CR.DBF'

You may notice that sort is case sensitive. The names beginning with 
lower case letters follow all the names beginning with upper case 
letters. If you want case insensitivity,
dirs_files = [x.lower() for x in dirs_files] before sorting. 

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


Re: [Tutor] How to discover which OS my python is running?

2005-11-23 Thread bob
At 06:31 PM 11/23/2005, Diego Galho Prestes wrote:
>Hi! I'm using a program that I want to know if I'm running the program
>in Linux or Windows. How can I do this? I want this because I created
>all my program in Linux but if someone runs it in Windows I have to do
>some things to make it work well, and I want to do this verification
>automatically.

import os
print os.name
# on my system I get nt
# The following names have currently been registered: 'posix', 'nt', 
'mac', 'os2', 'ce', 'java', 'riscos'. 

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


Re: [Tutor] Read Excel file without COM

2005-11-29 Thread bob
At 11:58 AM 11/29/2005, [EMAIL PROTECTED] wrote:
>Hi,
>
>I have written a script which reads a Microsoft Excel file and moves
>the data inside onto a database.  The script uses the PyWin32 module
>written by Mark Hammond, but I was wondering if anyone knew of a way
>to extract the data without using COM.  A Python module would be best,
>but I suppose any conversion program that could be called from Python
>would be satisfactory.

Interesting you ask at the same time I'm researching this question. I found
http://sourceforge.net/projects/pyexcelerator
Somewhere I thought I saw a reference to its ability to read Excel 
files, but I'm having a hard time getting to that. It does a great 
job writing Excel files.


>Saving the file as .csv isn't really an option since there are
>multiple pages in the sheet, and the people sending the files have
>been somewhat "standardized" to send an Excel sheet.  I have thought
>briefly about using xml, but this would require me to rewrite a lot of
>my code, and I would like to avoid this unless there are some other
>good reasons to do so.
>
>I think I found a good resource at
>http://chicago.sourceforge.net/devel/docs/excel/, but it doesn't
>include any Python code.  Does anyone know of something similar for
>Python?
>
>Thanks,
>
>Bill
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Read Excel file without COM

2005-11-29 Thread bob
At 01:45 PM 11/29/2005, John Fouhy wrote:
>On 30/11/05, bob <[EMAIL PROTECTED]> wrote:
> > Interesting you ask at the same time I'm researching this question. I found
> > http://sourceforge.net/projects/pyexcelerator
> > Somewhere I thought I saw a reference to its ability to read Excel
> > files, but I'm having a hard time getting to that. It does a great
> > job writing Excel files.
>
>Yeah, I like pyExcelerator, but the documentation lacks in places :-)
>
>Just call pyExcelerator.parse_xls() on the filename you wish to parse.

Great. That works. But I seem to just get the data. For now that suffices.

  Is there a way to retrieve formatting and other properties?


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

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


Re: [Tutor] MS ODBC

2005-12-06 Thread bob
At 09:57 PM 12/5/2005, Gregorius Gede Wiranarada wrote:
>hello,
>how can i connect python to read data from ms access or ms foxpro?

foxpro:

Install (if you have not) Mark Hammond's pywin32 to get the odbc module
http://sourceforge.net/project/showfiles.php?group_id=78018

Create a Data Source (if you don't already have one) for the Visual 
FoxPro Driver. Call it VFP (or whatever). If you don't know what this 
means, ask.

import odbc
vfpconn = odbc.odbc(VFP)
vfpcursor = vfpconn.cursor()
vfpcursor.execute(sql) # this can be more complex, involving 
substitution parameters
rows = vfp..cursor.fetchall()

Also see http://www.python.org/windows/win32/odbc.html

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


Re: [Tutor] Timer

2005-12-06 Thread bob
At 06:57 AM 12/6/2005, Joseph Quigley wrote:
>I'd like to make a 30 minute timer. How an I do that? With time?

import time
time.sleep(30)

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


Re: [Tutor] Timer

2005-12-08 Thread bob
At 07:18 PM 12/6/2005, Liam Clarke-Hutchinson wrote:
>Hi,
>
>time.sleep() takes an argument as seconds.

Oh yeah I know that but forgot.Sigh. Thanks for the correction. 

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


Re: [Tutor] advice on idiom replacing if test requested

2005-12-11 Thread bob
At 04:15 PM 12/11/2005, Brian van den Broek wrote:
>Hi all,
>
>I have a case like this toy code:
>
>import random
>list1 = [1,2,3]
>list2 = ['a', 'b', 'c']
>item = random.choice(list1 +list2)
>if item in list1:
>  others = list2
>else:
>  others = list1
>
>
>Another way occurred to me, but I wonder if I'm being too cute:
>
>item = random.choice(list1 +list2)
>others = [list1, list2][item in list1]
>
>I believe we can rely on True and False being 1 and 0 until Python
>3.0. But, even assuming that's right, I wonder if it is obscure to others.

It is not obscure to me. I do tings like that all the time.

But I think your algorithm is unnecessarily complex and costly. Consider

import random
list1 = [1,2,3]
list2 = ['a', 'b', 'c']
len1 = len(list1)
len2 = len(list2)
item = random.randint(1, len1 + len2)
if item <= len1:
  others = list2
else:
  others = list1

But then we also could:

import random
... same as above
lists = [list1, list2]
others = lists[random.randint(1, len1 + len2) <= len1]

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


Re: [Tutor] Scope Problem with Files

2005-12-14 Thread bob
At 11:13 AM 12/14/2005, Carroll, Barry wrote:
>Greetings:
>
>I am implementing a (crude but useful) debug facility in my test 
>system client software.  Basically, I test the value of a global 
>Boolean. It True, I write pertinent data to a text file.  I want to 
>do this in multiple functions in a module.  Rather than open and 
>close the file each time I write, I want to open the file once at 
>the start of process and close it at the end.  Here are excerpts 
>from the module.
>
>##
>import socket
>import struct
>import time
>
># initialize the debug flag
>DEBUG = True
>. . .
>
>dbgf = None # File object and path for saving debug output
>dbgfname = "debug.txt"
>
>def snd_cmd(sock,cmd):
>
> . . .
>
> while remainlen > 0:
> if remainlen > MTU:
> pktstp = pktstrt + MTU
> else:
> pktstp = pktlen
> pktflags |= EOD
>
> pkthdr = struct.pack('@2BH',pktflags,seq,pktlen)
> sndpkt = pkthdr+cmd[pktstrt:pktstp]
>
> if DEBUG:
> dbgf.write("command: " + cmd + "\n")
> dbgf.write("flags: 0x%X, seq: %u, len: %u\n" % 
> (pktflags, seq, pktlen))
>
> sock.sendto(sndpkt,addr)
>
> pktstrt += MTU
> remainlen -= MTU
> pktflags = pktflags & ~SOD
> seq = (seq + 1) % 256
>
> . . .
>
>def recv_resp(sock):
> response = ''
> try:
> response = sock.recv(MTU)
> except socket.timeout:
> errtupl = ("ERROR", 'Server did not respond')
> return (errtupl, response)
>
> . . .
>
> if DEBUG:
> dbgf.write("response: " + response + "\n")
> dbgf.write("flags: 0x%X, seq: %u, len: %u\n" % (flags, retseq, dlen))
>
> . . .
>
> return (errtupl, response)
>
>def do_cmd(cmd):
>
> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> sock.settimeout(timetowait)
> retriesleft = retries
> if DEBUG:
> dbgf = open(dbgfname,mode="a")

dbgf is a local variable. If you want to reassign to the global you must add
global dbgf
to the function

> dbgf.write("\n"+str(time.localtime())+"\n")
>
> while retriesleft > 0:
> snd_cmd(sock, cmd)
> recvtupl = recv_resp(sock)
> if recvtupl[0][0] != "ERROR":
> break
> retriesleft -= 1
>
> if DEBUG:
> dbgf.close()
>
> sock.close( )
> return recvtupl
>##
>
>When I run this code, I get the following error message:
>
><<<
>A problem occurred in a Python script. Here is the sequence of 
>function calls leading up to the error, in the order they occurred.
>/var/www/cgi-bin/pagen.py
>76 # function.  Check the returned error code for success.
>77 cmdtosnd = state['s']['getcmd']
>*78 (errorcode, errorstr), 
> platformstate['itype']['curstate'] = do_cmd(cmdtosnd)
>79 if errorcode == 0:
>80 cmdtosnd = state['t']['getcmd']
>
> . . .
>
>/var/www/cgi-bin/Client.py in do_cmd(cmd='cmd')
>   160
>   161 while retriesleft > 0:
>   *162 snd_cmd(sock, cmd)
>   163 recvtupl = recv_resp(sock)
>   164 if recvtupl[0][0] != IIPSRVERROR:
>
>global snd_cmd = , sock = object>, cmd = 'cmd'
>
>
>  /var/www/cgi-bin/Client.py in snd_cmd(sock= object>, cmd='cmd')
>65
>66 if DEBUG:
>*67 dbgf.write("command: " + cmd + "\n")
>69
>
>global dbgf = None, dbgf.write undefined, cmd = 'cmd'
>
>
>AttributeError: 'NoneType' object has no attribute 'write'
>   args = ("'NoneType' object has no attribute 'write'",)
> >>>
>
>dbgf is declared at the top of the module.  It is opened and closed 
>in do_cmd.  I attempt to write to it in snd_cmd and recv_resp, both 
>of which are called by do_cmd.  Since dbgf is global to all of these 
>functions, I expected its value (the open file object) to 
>persist.  I don't understand why it didn't.  I expect I have 
>misunderstood Python's scoping rules.  Can someone enlighten me?
>
>Thanks and enjoy the holidays.
>
>BGC
>
>"Never trust anything that can think for itself
>if you can't see where it keeps its brain"
>JK Rowling
>
>
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Python - SQL paradigm (Will I need a hammer to make it fit?)

2005-12-15 Thread bob
At 02:14 AM 12/14/2005, Liam Clarke wrote:
>Hi all,
>
>Just contemplating.
>
>If in Python I were organising a data index along the lines of  -
>
>j = {
>
>"k_word1" : ["rec1","rec2","rec3","rec4"],
>...
>"k_wordn" :["recX","rec4"]
>
>}
>
>and I was going to find records that matched by seeing what record
>occurred in the most lists (via set intersections or similar; going to
>have a play see what works faster) selected by searching keywords...
>
>how easily does that translate to a SQL table and query format?

Data modeling looks for relationships between objects. Relationships 
can be 1-1 1-many or many-many. Your case is a many-many
(each keyword may appear in one or more records, and each record may 
contain one or more keywords.) The customary way to represent this in 
a relational database 3 tables. One with one row per keyword, one 
with one row per record and one "junction" or "association" table 
with one row for each keyword-record pair.

KEYWORD TABLE
kid   keyword
1cat
2dog
3mouse
4bird
5banana

RECORD TABLE
rid   record
1rexX
2rec4
3recAB
4rec99
5recFoo

KEYWORD-RECORD TABLE
kid rid
1   1
1   3
1   4
2   2
3   5
4   1
5   3

For processing things like this nothing IMHO beats a relational 
database and SQL. With many databases accessible from Python I 
strongly suggest this approach. SQLite is especially attractive.
[snip] 

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


Re: [Tutor] Input checking [letters or numbers]

2005-12-23 Thread bob
At 10:15 AM 12/23/2005, Panagiotis Atmatzidis wrote:
>Hello,
>
>Can someone provide me with an error checking example about an x
>variable that needs to be number only? I used something like:
>
>  def useridf():
>  print ""
>  print "WARNING: If you don't understand why this must be unique,
>exit and read the manual."

You ask the user to exit but you don't tell him how to do that!

>  print ""
>  userid = input("x : ")
>
>I know that "input" accepts only numbers

How did you "know" that? Try this:
print input("x ; ")
and enter "Hello world"

Truth is input() "accepts" anything and attempts to evaluate it as a 
Python expression. If that fails it raises an exception.

You should use raw_input() instead. This takes any input and returns 
it as a character string.
x = raw_input("x : ")
if x.isdigit(): # ensure input is a number
   y = int(x) # convert to integer
else:
   print 'Boo"

>, but I don't want the program
>to break if someone puts other chars in it. I want to, print "Only
>numbers are accepted." which is easy. But still I can't understand how
>to do the check using if/elif/else statements.

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


Re: [Tutor] Input checking [letters or numbers]

2005-12-23 Thread bob
At 11:16 AM 12/23/2005, Panagiotis Atmatzidis wrote:
>Hello there,
>
>Thank you for the prompt response.
>
>On 12/23/05, bob <[EMAIL PROTECTED]> wrote:
>[snip]
> > print input("x ; ")
> > and enter "Hello world"
>
> >>> x = input("x: ")
>x: hello world
>Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 1
> hello world
>  ^
>SyntaxError: unexpected EOF while parsing
>
>Just did.. and as you can see I get an error. I know because I read so
>in the tutorial I mentioned before.. I mean that it says so.. now I am
>taking the first steps into programming, hence I don't really know if
>there's another reason for input to break upon chars.

Enter "hello world" including the quotes.
input expects a Python expression.
hello world is not a Python expression
"hello world" is
[snip] 

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


Re: [Tutor] Input checking [letters or numbers]

2005-12-23 Thread bob
At 11:28 AM 12/23/2005, Panagiotis Atmatzidis wrote:
>On 12/23/05, Panagiotis Atmatzidis <[EMAIL PROTECTED]> wrote:
> > Hello Dany :-)
> >
> > On 12/23/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
>[...]
> > >
> > >
> > > Hello Bob and Panagiotis,
> > >
> > > It might be good to make this number-reading thing a function, just to
> > > make it easier to reuse (and test!) it.  Let's call this input_number()
> > > for the moment.
> > >
> > > ###
> > > def input_number(prompt):
> > > """Reads an integer from the next line of input."""
> > > while 1:
> > > x = raw_input(prompt)
> > > if x.isdigit():
> > > return int(x)
> > > else:
> > > print 'Boo'
> > > ###
>[...]
> > > I added one more behavior so that input_number continues to ask 
> until it's
> > > satisified by a number.  Hope this helps!
> >
> > Yes, it really helps a lot. Now I can proceed with my script!!
>[...]
>
>Another newbe question! I use "while True: " to evaluate an 
>expression, I see that you used while 1: .. what's the diffrence if any?!

In this case, no difference. True and False are Python boolean 
constants, and also a subset of integer. So one may print True + 1 and see 2.

Conditional statements (while, if, elif) and the if clause of list 
comprehensions and generator expressions expect an expression that 
will be treated as True if not empty and False if empty. From the 
L:angRef: "In the context of Boolean operations, and also when 
expressions are used by control flow statements, the following values 
are interpreted as false: None, numeric zero of all types, empty 
sequences (strings, tuples and lists), and empty mappings 
(dictionaries). All other values are interpreted as true."

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


Re: [Tutor] Problem with os.access function. [semantic error, if check does not work]

2005-12-24 Thread bob
At 05:20 AM 12/24/2005, Panagiotis Atmatzidis wrote:
>Hello,
>
>I am writing a function in order to check if a directory exists. If
>exists the functions must do nothing, otherwise must check the users
>permissions and if it's possible create the dir. Looking at pydoc's
>httpd I found the module "os" and the function "access". From the
>http-doc:
>
>access(...)
>access(path, mode) -> 1 if granted, 0 otherwise
>
>Use the real uid/gid to test for access to a path.  Note that most
>operations will use the effective uid/gid, therefore this routine can
>be used in a suid/sgid environment to test if the invoking user has the
>specified access to the path.  The mode argument can be F_OK to test
>existence, or the inclusive-OR of R_OK, W_OK, and X_OK.
>
>This is my function:
>
>def homedirhandle():
>   path = "/some/dir/" # check the existance of the
>directory
>   mode = 755

should be mode = 0755 (octal representation) for mkdir. For 
access: "The mode argument can be F_OK to test existence, or the 
inclusive-OR of R_OK, W_OK, and X_OK." suggests that only 1 digit is expected.

>   check_path = os.access(path, mode)
>   print check_path
>   if check_path == 'False':

Should be if check_path == False:

Or even simpler if not check_path:

Use print repr(check_path). Then you'd see either True or 'True'. 
That would help you see whether check_path is boolean or string.

>  print ""
>  print "Directory /some/dir does not exist."
>  print "Trying to create the directory."
>  uid = os.geteuid()
>  print "the uid is ", uid
>  if uid == '0':

I think (not having UNIX access at the moment) that this should be if uid == 0:

>   try:
>os.mkdir(path, mode)
>print ""
>print "The directory has been created."
>print ""
>return path
>   except OSError, e:
> print ""
> print >>sys.stderr, "The mkdir command failed:
>%d (%s)" % (e.errno, e.strerror)
> print ""
> print "Exiting"
> sys.exit(1)
>
>  if check_path == '1':

== 1

> print ""
> print "The directory /some/dir has been created."
> print ""
> return path
>  else:
> print "Please create the directory /some/dir manually and
>then re-run vuhalndler."
> print "Exiting"
> sys.exit()
>   else:
>  print ""
>  print "The directory already exists."
>  print ""
>  return path
>
>Now the problem lies at the first check "  if check_path == 'False':
>". It's a semantic error, the program does not really check the dir,
>it just takes for granted that the dir exists. I tried with 1 before
>putting "False" there.. but it did not work so I took the print result
>of check_path and substitute  1 with False. But still nothing :-(
>
>Why does not make the check? I thought that the functions
>functionality was clear.. probably is not.
>
>
>
>--
>Panagiotis
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] is there any tool like "run line or selection" in Pythonwin?

2005-12-25 Thread bob
At 04:30 AM 12/25/2005, linda.s wrote:
>is there any tool like "run line or selection" in Pythonwin?

Shades of Visual FoxPro?

Create a script (I call it testbed.py). Open it in a script window, 
paste the selection there, hit F5. Since this executes in the main 
namespace the results will persist. It is fairly easy to use ctrl-a 
followed by ctrl-v to replace any prior script with the newly copied 
selection. Then you can play with it in the testbed and put back in 
the "real" script when you ar happy with it.

FWIW before discovering this I would copy/paste into immediate 
window, and either string the lines together by putting ; at the end, 
the deleting the return or editing in ... before all continuation 
lines as follows:

Example in script:
a = 3
b = 4
print a+b

Paste in immediate:
 >>> a = 3
b = 4
print a+b

Edit and execute (need to hit enter twice):
 >>> a = 3; b = 4; print a+b

If compound statements are involved I paste then type ... at the 
start of the 2nd line, copy that and paste in front of the remaining 
lines. These operations are fairly quick.

Example 2 in script:
if a == b:
 print 'Winner"
 c = b
 y = z

Paste in immediate:
 >>> if a == b:
 print 'Winner"
 c = b
 y = z

Type ... at left margin of print line and subsequent lines or copy & 
paste, then execute (need to hit enter twice). These operations are 
fairly quick.
 >>> if a == b:
...print 'Winner"
...c = b
...y = z

hth

Since all these approaches execute in the main namespace their 
results will persist. 

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


Re: [Tutor] Printing

2005-12-27 Thread bob
At 08:52 AM 12/26/2005, John Corry wrote:
>Thanks for the prompt reply.  This is exactly what I am looking for.
>However, I have tried the code on the page and I can't get it to work.
>
>import tempfile
>import win32api
>
>filename = tempfile.mktemp (".txt")
>open (filename, "w").write ("This is a test")
>win32api.ShellExecute (
>   0,
>   "print",
>   filename,
>   None,
>   ".",
>   0
>)

Also beware that the file must have an extension associated with an 
application that recognizes the print command. e.g. if the file is 
named foo.doc and .doc is registered as belonging to MS Word, then 
this will open MSword, open the file, print the file and close Word. 
It is the equivalent of right-clicking the file in the explorer and 
then choosing Print from the context menu.


>I am using the Pythoncard code editor and I get the following error:
>
>Traceback (most recent call last):
>   File "c:\python24\jhc.py", line12, in ?
> 0
>pywintypes.error: (2, 'ShellExecute', 'The system cannot find the file
>specified
>.')
>
>I have played about with it and saved it in various places but I can't get
>it to work.  Any suggestions?  Do I need to import other modules?  Do I need
>to use Pythonwin?
>
>Thanks,
>
>John.
>
>-Original Message-
>From: [EMAIL PROTECTED]
>[mailto:[EMAIL PROTECTED] Behalf Of
>Danny Yoo
>Sent: 24 December 2005 19:33
>To: John Corry
>Cc: Tutor
>Subject: Re: [Tutor] Printing
>
>
>
>
> > I have downloaded win32, win32com, Preppy and PIL.  I have had a go at
> > using them but can't get them to work.  At the moment I can't even print
> > the text file.
> >
> > Is there a good helpguide/FAQ page which deals with printing text files
> > or is there simple code which prints a text file?
>
>Hi John,
>
>
>Let's see... ok, found it!  Tim Golden has written a small introduction to
>printing:
>
> http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html
>
>His recommendation is to use the ShellExecute function in win32api to send
>off documents to your printer.
>
>
>
>Best of wishes!
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Extracting data from HTML files

2005-12-28 Thread bob
At 01:26 PM 12/28/2005, [EMAIL PROTECTED] wrote:
>[snip]
>I`m trying to make a python script for extracting certain data from HTML
>filesSay for example the HTML file has the following format:
>Category:Category1
>[...]
>Name:Filename.exe
>[...]
>Description:Description1.
>
>Taking in to account that each HTML file has a load of code in between each
>[...], what I want to do is extract the information for each field.In this
>case what I want to do is the script to read Category1, filename.exe and
>Description1.

Check out BeautifulSoup http://www.crummy.com/software/BeautifulSoup/

>And later on insert this in to a mysql database, or read the
>info and generate a CSV file to make db insertion easier.
>Since all the files are generated by a script each field I want to read
>is,from what I`ve seen, in the same line number so this could make things
>easier.But not all fields are of the same length.
>I`ve read Chapter 8 of Dive in to Python so I`m basing my work on that.
>I also thought regexes might be useful for this but I suck at using regexes
>so that`s another problem.
>Do any of you have an idea of where I could get a good start on this and if
>there`s any modules (like sgmllib.py) that might come in handy for this.
>Thanks!
>
>--
>Lust, ein paar Euro nebenbei zu verdienen? Ohne Kosten, ohne Risiko!
>Satte Provisionen für GMX Partner: http://www.gmx.net/de/go/partner
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Avoiding repetetive pattern match in re module

2006-01-05 Thread bob


At 02:41 AM 1/5/2006, Intercodes wrote:
Hello everyone,
    Iam new to this mailing list as well as
python(uptime-3 weeks).Today I learnt about RE from

http://www.amk.ca/python/howto/regex/.This one was really helpful. I
started working out with few examples on my own. The first one was to
collect all the HTML tags used in an HTML file. I wrote this
code.
-- 
import re
file1=open(raw_input("\nEnter The path of the HTML file:
"),"r")
ans=""
while 1:
    data="">
    if data="">
    break
    ans=ans+data    
Consider a shorter way to grab the entire file:
ans = open(raw_input("\nEnter The path of the HTML file:
"),"r").read()
[snip]

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


Re: [Tutor] string to integer

2006-01-05 Thread bob
At 12:40 PM 1/5/2006, Boyan R. wrote:
>I need program to convert my string in integer.
>I remember in BASIC I used  val(string) command
>Is there a Python equivalent ?
>
>Here is how it should work:
>val(7) = 7
>val(bbab7) = 7
>val(aa7aa) = 7
>val(   7) = 7
>
>This last is most important, currently I don't know how to
>convert string "   7" to integer value 7 in my program
>(those empty spaces are nasty)
>btw, I'm working with random numbers, I took 7 just for example :)

int("7") -> 7
int(" 7") -> 7
int("aa7aa") ->ValueError: invalid literal for int(): aa7aa. You'd 
need to remove the non-digits using replace or re.sub.

>what are chr() values for enter and (empty) space ?
>If anybody have a table with chr() values

Are you asking what numeric value passed to chr() gives Enter (etc)? 
If so consult any ASCII Chart. One is at
http://www.lookuptables.com/. Of course Enter in ASCII is CR. 

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


Re: [Tutor] Landscape Printing

2006-01-09 Thread bob
At 05:48 AM 1/8/2006, John Corry wrote:
>Hi,
>
>My text file is printing out in portrait.  Is there any instruction that I
>can use so that notepad prints it in landscape?

I doubt that you can do this with notepad. Certainly not with 
ShelleExecute. You could do some fancy footwork with opening notepad, 
getting its window's handle, and sending keystrokes to navigate the 
pase setup and print dialogs. Or you'd need an application that can 
have its print setup globally configured, or one that supports 
command line options for printing, or one that you communicate with 
using COM (such as MS Word). 

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


Re: [Tutor] div_t

2006-01-11 Thread bob
At 02:59 PM 1/11/2006, Burge Kurt wrote:
>Hi,
>
>What is the usage of div_t in python?
>
>I have some unsigned integer variables and want to use ;
>
>div_t div_T;
>div_t div_N;
>div_t div_B;

Your question is meaningless to me! Please clarify.

div_t is not a Python constant or built_in.

div_t div_T; is not a Python expression.

Python integers are signed.

Does any of this refer to another lannguage? 

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


Re: [Tutor] Finding the Index of a member of a Tuple

2006-01-11 Thread bob
At 08:31 PM 1/11/2006, Steve Haley wrote:
>Hello everyone,
>
>I need to do something very simple but I'm having trouble finding 
>the way to do it - at least easily.  I have created a tuple and now 
>need to find the position of individual members of that 
>tuple.  Specifically, the tuple is something like: words = ("you", 
>"me", "us", "we", "and", "so", "forth") and I need to be able to 
>name a member, for example, "us" and find what the position (index) 
>of that word is in the tuple.
>
>I would have thought there would be a simple built in function for 
>that but I just went through the built in functions in the Python 
>Library Reference and I didn't find anything.  I could probably 
>figure out how to write a while loop or something to do a sequential 
>search until I found the right member but I really believe there 
>must be an easier way and I'm just not seeing it.  You can probably 
>tell I'm just learning Python so any help would be appreciated.

Unfortunately there is no list method find. Sigh. Here's how I'd do it:

# create a dictionary with each word as key and ordinal as value
words = dict([(n,m) for m,n in enumerate(("you", "me", "us", "we", 
"and", "so", "forth"))])
words["me"] # returns 1 

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


Re: [Tutor] Finding the Index of a member of a Tuple

2006-01-12 Thread bob
At 10:52 PM 1/11/2006, Brian van den Broek wrote:
>[snip]
>
>I assume Bob meant that tuples have no index or find method.

No, Bob is sick and not thinking clearly.

At 11:04 PM 1/11/2006, Terry Carroll wrote:

>Does it have to be a tuple?  If you make it a list, you can use index():
>[snip]

At 03:13 AM 1/12/2006, Kent Johnson wrote:
>[snip]
>If you can use a list instead of a tuple you can use the index() method.

I'm glad there are several of us contributing to this list. I hope to 
think things thru better before responding, but it is also nice to 
see that the dictionary approach stimulated things!

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


Re: [Tutor] __getitem__

2006-01-16 Thread bob
At 12:12 PM 1/16/2006, Christopher Spears wrote:
>I understand that you can use __getitem__ as a hook to
>modify indexing behavoir in a class.  That's why
>__getitem__ not only affects [] but also for loops,
>map calls, list comprehension, etc.  For loops, etc.
>work by indexing a  sequences from zero to a higher
>index until out-of-bounds is reached.  But why does
>this work?
>
> >>> class stepper:
>... def __getitem__(self, i):
>... return self.data[i]
>...
> >>> 'p' in X
>True
>
>What does 'in' have to do with indexing?

What does X have to do with stepper? 

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


Re: [Tutor] Open file error

2006-01-17 Thread bob
At 09:23 AM 1/17/2006, Paul Kraus wrote:
>On Tuesday 17 January 2006 12:11 pm, andy senoaji wrote:
> > I am starting to pull my hair here. There were some postings in the past,
> > similar to my problem, but the response was not clear enough. Sorry if you
> > thingk I am reposting this.
> >
> > I am trying to run (on an XP box) a simple open file using this:
> > f = open(r'C:\Test.txt', 'r')Newbie here but shouldn't it be.
>
>Newbie Here
>
>f = open( r'C:\\Test.txt','r')
>
>I think you are escaping the T with \T.

More specifically you show us  f = open(r'C:\Test.txt', 'r')
but the traceback shows the statement to be f = open('Test.txt', 'r')

Something is being lost between these 2 items.

When I try f = open( r'C:\Test.txt','r')
The traceback reports IOError: [Errno 2] No such file or directory: 
'c:\\test.txt'
Note the \\
Your traceback reports IOError: [Errno 2] No such file or directory: 
'c:\test.txt' confirming the Paul's diagnosis.
Are you using IDLE? Are you running a script vs trying a command interactively? 

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


Re: [Tutor] namespace confusion

2006-01-18 Thread bob


At 02:25 PM 1/18/2006, Christopher Spears wrote:
Let's say I have two
classes:
>>> class super:
... def hello(self):
... self.data1 =
'spam'
...
>>> class sub(super):
... def hola(self):
... self.data2 =
'eggs'
...
Now let's look in the classes' namespaces using
__dict__:
>>> sub.__dict__
{'__module__': '__main__', '__doc__': None, 'hola':
}
>>> super.__dict__
{'__module__': '__main__', 'hello': 
0x4039548c>, '__doc__': None}
I was first confused why 'hello' did not appear in sub
as well.  Then I read about dir():
>>> dir(sub)
['__doc__', '__module__', 'hello', 'hola']
>>> dir(super)
['__doc__', '__module__', 'hello']
The above result makes more sense to me.  Why doesn't
__dict__ give the same response as dir()?  How come I
don't see super in sub's namespace?
 From help under dir(): 
"With an argument, attempts to return a list of valid attributes for
that object. This information is gleaned from the object's
__dict__ attribute, if defined, and from the class or type
object. The list is not necessarily complete. ... If the object is a type
or class object, the list contains the names of its attributes, and
recursively of the attributes of its bases.:

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


Re: [Tutor] I'm puzzled

2006-01-22 Thread bob
At 03:46 PM 1/22/2006, Vincent Zee wrote:
>Why will this little program crash when you enter the enter key?

Thank you for including the "traceback" message in your 2nd post.

Index error means you tried to reference an element of a sequence 
that is not there. a is the empty string when you just hit enter to 
the raw_input request. It therefore has no elements, so a[0] raises 
the exception.

To avoid this test first for len(a) > 0.

>while True:
> a = raw_input('number? ')
> if a.isdigit():
> print 'isdigit'
> elif a[0] == '-' and a[1:].isdigit():
> print '- + isdigit'
> elif a == 'q':
> break
> else:
> print 'no digit'

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


Re: [Tutor] PLZ REPLY SOON

2006-01-23 Thread bob
At 10:24 PM 1/22/2006, Shalini R wrote:
>Hi sir,
>  I'm new to python & postgres as I've created a form in html & a
>table in postgres. There is a field in form which will take multiple
>value

My guess is that each checkbox needs its own name, rather than all of 
them using arrFacility. Give that a try.

>the problem which i'm facing is i'm getting single value but
>when i want multiple values to be inserted to postgres table it is
>not happening
>the dtml script is
>
>
>
>
>Eno
>EmpNamename="txtEmpName">
>Facility you want 
>HRA
>Travel
>Food
>value="Accomodation">Accomodation
>
>
>
>
>State 
>Delhi
>Harayana
>UP
>Kerala
>J&K
>
>
>
>
>
>
>
>
>
>
>--
>python script
>
>
>import psycopg
>import sys
>def add(REQUEST):
> try:
> con=psycopg.connect("dbname=mission2007 user=
>postgres")
> cur=con.cursor()
> d=[]
> d.append(REQUEST.get("txtEmpName"))
> d.append(REQUEST.get("arrFacility"))
> d.append(REQUEST.get("txtState"))
> sql1="select max(eno) from empdetail"
> cur.execute(sql1)
> eno=cur.fetchone()
> sql="insert into empdetail (empname,facility,state)
>values('"+REQUEST.get("txtEmpName")+"','"+REQUEST.get("arrFacility")+"
>','"+REQUEST.get("txtState")+"')"
> return sql
> cur.execute(sql)
> con.commit()
> cur.close()
> con.close()
> return "You had successfully entered data"
>
>
>
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Accuracy of time.sleep()

2004-12-04 Thread Bob Gailer
At 07:24 AM 12/4/2004, Dave S wrote:
OK I may be pushing it,  ;-)
I need a script to sleep from any point to 8:05AM when in needs to re-start.
[snip]
If you're running on a version of windows that supports the AT command that 
gives you another way to do this.
At a DOS prompt try AT. If you get something other than a command 
not found kind of error then we can do something. Let us know.

Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple RPN calculator

2004-12-05 Thread Bob Gailer
At 04:45 PM 12/4/2004, Max Noel wrote:
On Dec 4, 2004, at 23:30, Alan Gauld wrote:
to make it request for input(s) of say a simple math like  "1 2 3 4
5 + - * /".
Look at raw_input()
But if you are that much of a beginner you need to take several
steps back and try one of the tutorials, they all cover raw_input
fairly early on...
And finally doesn't RPN put the operators first? Or is it me thats
getting confused fromtoo much Lisping recently?...
Nope, RPN calculators (such as the HP48GX, IMHO the best 
calculator ever made) require you to input the operands first, then the 
operators. It's both easier to implement and more intuitive (not to 
mention way faster to both input and compute) once you've gotten the hang 
of it.
You can probably do a very basic RPN calculator in less than a 
hundred lines of code, using raw_input() and a stack (well, a list's 
append() and pop() methods).
For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as input and 
prints -0.0481481 8 lines of Python. That indeed is less than 100. Took 
about 7 minutes to code and test.

Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Can I see it?

2004-12-05 Thread Bob Gailer
At 03:36 AM 12/5/2004, you wrote:
Hi Bob,
That is what I am looking for! A simple RPN calculator program!
Can I see what you have please?
That depends. Are you are working on a homework assignment? I ask because 
when we see several posts of a similar question we suspect it is an 
assignment given to a class, and our hope is to support education with 
guidance rather than answers.

Assuming for the moment that this is homework I'd like to see what you have 
done so far, and where you are stuck. Then I'll give some pointers.

Hints: my program uses lists, a dictionary, and imports a module named 
operators

Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Can I see it?

2004-12-06 Thread Bob Gailer
At 02:06 PM 12/5/2004, Just Incase wrote:
Hi Bob,
Yea, it is a homework and I would also like to do something on it to get 
familiar with the program, so all I am asking for is if there are the 
pionters to help me. Like I said I am new to python/programming but I have 
limited time to turn-in the assignment as all these while I have been 
trying to study the tutorials I thought would help and I guess I was not 
looking in the right place.

Here is what I have been trying to use:
Any help is welcome. Thank you.
Exactly what help do you want? I don't want to read all your code in 
detail. What do you need next?
Also please reply to all so this gets back to the tutor list.

#!/usr/bin/env python
# Reverse Polish Notation Calculator
# Justice
import cmd, sys
class rpn_calc(cmd.Cmd):
"""RPN calculator"""
def __init__(self, stacksize=4):
self.stack = [0]*stacksize
self.stacksize = len(self.stack)
self.lastregister = self.stacksize-1
self.intro='Simple RPN Calculator\nJustice 29. Nov 2004'
self.lastx = 0
self.operations = { '+': self.do_add,
'-': self.do_subtract,
'*': self.do_multiply,
'/': self.do_divide, }
# Helper functions
def _stacklift(self, new_x):
"""Lift stack by one entry, last register is lost"""
del self.stack[self.lastregister]
self.stack.insert(0, new_x)
def _stackdrop(self, new_x):
"""Drop stack by one entry, losing Y register entry, last register
is doubled"""
self.stack.append(self.stack[self.lastregister])
del self.stack[0]
self.stack[0]=new_x
# Catch numbers and operators
def default(self, entry):
"""Catch numbers and operators and process them. If entry is
neither number nor operator, ignore and pass on to cmd
loop."""
# Catch numbers
try:
number = float(entry)
self.lastx = self.stack[0]
self._stacklift(number)
except ValueError:
pass
# Catch operations
if entry in self.operations:
operation = self.operations[entry]
operation()
# Show X register after each command
def postcmd(self, *dummy):
"""Display the contents of the X register after each
command"""
print " %f" % self.stack[0]
# Calculator commands
def do_add(self, dummy=None):
result = self.stack[1] + self.stack[0]
self._stackdrop(result)
def do_clrx(self, rest):
"""Clear X register"""
self.stack[0] = 0
def do_divide(self, dummy=None):
try:
result = self.stack[1] / self.stack[0]
self._stackdrop(result)
except ZeroDivisionError:
print "*** Division by Zero Error ***"
def do_enter(self, dummy):
"""Perform a stack lift; last register value is lost,
first (X) register value is pushed into the second (Y)
register"""
self._stacklift(self.stack[0])
def emptyline(self, dummy=None):
"""An empty line is treated like hitting the ENTER key"""
self.do_enter(None)
def do_lastx(self, dummy):
"""Restore X register value from before the operation in the
X register, performing a stack lift"""
self._stacklift(self.lastx)
def do_multiply(self, dummy=None):
try:
result = self.stack[1] * self.stack[0]
self._stackdrop(result)
except OverflowError:
print '*** Overflow Error ***'
def do_print(self, rest):
"""Print stack. Mostly used for debugging"""
for i in range(self.stacksize-1, -1, -1):
print 'Reg %s: %f' % (i, self.stack[i])
def do_quit(self, dummy):
sys.exit()
def do_rdown(self, dummy):
"""Roll down stack"""
self.stack.append(self.stack[0])
del self.stack[0]
def do_rup(self, dummy):
"""Roll up stack"""
self.stack.insert(0, self.stack[self.lastregister])
del self.stack[self.lastregister+1]
def do_subtract(self, dummy=None):
result = self.stack[1] - self.stack[0]
self._stackdrop(result)
def do_xy(self, dummy):
"""Swap X and Y registers"""
self.stack[0], self.stack[1] = self.stack[1], self.stack[0]
# Help texts
def help_add(self):
print 'Add X and Y register. Use "+" key or "add&q

Re: [Tutor] Printing two elements in a list

2004-12-07 Thread Bob Gailer
At 08:22 AM 12/7/2004, kumar s wrote:
Dear group,
 I have two lists names x and seq.
I am trying to find element of x in element of seq. I
find them. However, I want to print element in seq
that contains element of x and also the next element
in seq.
So I tried this piece of code and get and error that
str and int cannot be concatenated
>>> for ele1 in x:
for ele2 in seq:
if ele1 in ele2:
print (seq[ele1+1])
The problem here is that ele1 is a string, not an index into the list. 
There are a couple ways to fix this.

match = False
for ele1 in x:
for ele2 in seq:
if match:
print ele2
match = False
if ele1 in ele2:
print ele2
match = True
OR
for ele1 in x:
for index, ele2 in enumerate(seq):
if ele1 in ele2:
print ele2, seq[index+1]
[snip]
Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-08 Thread Bob Gailer
At 11:27 AM 12/8/2004, Dick Moores wrote:
My thanks to both Max and Kent. So Python tries, and fails, to see 2() as 
a function!

I also got some help from <http://www.pcwebopedia.com/TERM/c/call.html>
Note that SOME languages use () for call. There are other call constructs, 
such as:

DO function WITH parameters (FoxPro, similar in COBOL)
function parameter   or   parameter1 function parameter2 (APL)
Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-08 Thread Bob Gailer
At 12:39 PM 12/8/2004, Bob Gailer wrote:
At 11:27 AM 12/8/2004, Dick Moores wrote:
My thanks to both Max and Kent. So Python tries, and fails, to see 2() as 
a function!

I also got some help from <http://www.pcwebopedia.com/TERM/c/call.html>
Note that SOME languages use () for call. There are other call constructs, 
such as:

DO function WITH parameters (FoxPro, similar in COBOL)
function parameter   or   parameter1 function parameter2 (APL)
I should add the Python builtin function apply: apply(function, 
parameters...)
Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help matching elements from two lists and printing them

2004-12-08 Thread Bob Gailer
At 02:51 PM 12/8/2004, kumar s wrote:
Dear group,
 I have two tables:
First table: spot_cor:
432 117
499 631
10  0
326 83
62  197
0   0
37  551

Second table: spot_int
0   0   98
1   0   5470
2   0   113
3   0   5240
4   0   82.5
5   0   92
6   0   5012
7   0   111
8   0   4612
9   0   115
10  0   4676.5

I stored these two tables as lists:
>>> spot_cor[0:5]
['432\t117', '499\t631', 10\t0', '326\t83', '62\t197']
Note there is no ' before the 10. That won't fly'
>>> spot_int[0:5]
['  0\t  0\t18.9', '  1\t  0\t649.4', '  10\t
0\t37.3', '  3\t  0\t901.6', '  4\t  0\t14.9']
It would be a lot easier to work with if the lists looked like (assumes all 
data are numeric):
[(432,117), (499,631), (10,0), (326,83), (62,197)]
[(0,0,18.9), (1,0,649.4), (10,0,37.3), (3,0,901.6), (4,0,14.9)]

What is the source for this data? Is it a tab-delimited file? If so the CSV 
module can help make this translation.

I also assume that you want the first 2 elements of a spot_int element to 
match a spot_cor element.

Then (for the subset of data you've provided):
>>> for ele1 in spot_cor:
...   for ele2 in spot_int:
... if ele1 == ele2[:2]:
...     print "%8s %8s %8s" % ele2
...
  100 37.3
I want to write all the three columns of spot_int.
[snip]
Hope that helps.
Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple RPN calculator

2004-12-08 Thread Bob Gailer
At 06:05 AM 12/6/2004, you wrote:
Bob Gailer wrote:
> For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as input
> and prints -0.0481481 8 lines of Python. That indeed is less than
> 100. Took about 7 minutes to code and test.
I'm quite interested in seeing the sourcecode for that.
I've made it interactive (enter an operand or operator and hit enter); it 
displays the top of the stack. I added . ^ and %. No error checking.

import operator as op
def rpn(o,stack = [],d = {'*':op.mul, '+':op.add, '/':op.truediv, 
'%':op.mod, '-':op.sub, '^':op.pow, '.':lambda x,y:x+.1*y}):
  if o in d: stack[-2:] = [d[o](stack[-2], stack[-1])]
  elif o: stack.append(float(o)) # could bomb here if input not floatable!
  else: return 1
  print stack[-1]
while 1:
  if rpn(raw_input('>')): break

Let me know what you think.
Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell  

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Difference between for i in range(len(object)) and for i in object

2004-12-09 Thread Bob Gailer
At 09:50 AM 12/9/2004, kumar s wrote:
[snip]
Personally I am getting weary of a lot of requests that to me seem to come 
from a lack of understanding of Python.. Would you be willing to take a 
good tutorial so you understand basic Python concepts and apply them to 
your code.

I also despair that you don't seem to benefit from some of our suggestions.
Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Difference between for i in range(len(object)) andfor i in object

2004-12-12 Thread Bob Gailer
At 08:27 AM 12/12/2004, kumar s wrote:
Thank you for clearing up some mist here.  In fact I was depressed by that 
e-mail
I appreciate Alan's response and yours. I forgot that this was the Tutor 
list, as I see so many Python e-mails it is easy to get confused. Please 
resume seeing this list and me as resources. I regret my comments that led 
to your depression.

because there are not many tutorials that clearly explains the issues that
one faces while trying to code in python.
So what can we do as a community to provide tutorials that help students 
like you to more easily "get it". Can you give us some ideas as to what is 
missing? Also I 'd be interested in knowing a bit about your academic 
background and field of study. Would you give us a brief CV?

I taught programming for the Boeing Company. I always wondered "what are 
these students doing here? Why don't they just read the book?" That's how I 
learned almost everything I know about programming. So it can be hard for 
me to understand your struggle.

Nuf said for now...
[snip]
Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Leading zero for hex numbers

2004-12-15 Thread Bob Gailer
At 06:47 PM 12/15/2004, Tony Cappellini wrote:
I'm trying to get Python to automatically print a leading 0 for hex
numbers, but it only seems to work for for decimal numbers.
Oh? print "%0d" % 12345 gives me 12345 - no leading 0
print "0x%0X" % 12345
displays 0x3039
which it should
instead of 0x03039
and print "0x%05X" % 12345 displays 0x03039
The Python docs state
The conversion will be zero padded for numeric values, when a 0 is used as
a flag between the % and the conversion type.
If you continue in the documentation right after 3 Conversion flags comes 4 
Minimum field width

Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-15 Thread Bob Gailer
At 09:14 PM 12/15/2004, Tim Peters wrote:
[Brian van den Broek]
> in Marc's check_range thread, I had proposed:
>
> def check_in_range(value):
>
> in_range = False
> if 9 < value < 90:
> in_range = True
> return in_range
>
> and DogWalker suggested the better:
>
> def check_in_range(value):
> return 9 < value < 90
>
> As I mentioned, I feel as though I have a mental block getting in the
> way of coming up with code in the smoother fashion of the second snippet
> above.
Don't feel frustrated -- using Boolean expressions idiomatically is
very much a learned skill.  So is adding integers, but *that* got
drilled into you over years, and years, and years.  It won't take
quite as long to sling bools .
The worst abuse is one you're perhaps not prone to:  having a Boolean
expression e, and then writing
if e == True:
instead of
if e:
For some reason, that's extremely common in code written by newcomers
to Pascal.
Not to mention coding examples provided by Microsoft in some help topics!
[snip]
Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on "import foobar" vs "from foobar import *"

2010-01-09 Thread bob gailer

Eric Pavey wrote:
I should add (that as I understand it), when you do a 'from foo import 
blah', or 'from foo import *', this is doing a /copy/ (effectively) of 
that module's attributes into the current namespace.
Not a copy (which means duplicating the attribute) but a new reference 
to the original attribute. Example

>>> import sys
>>> from sys import modules
>>> sys.modules is modules
True
>>> m = dict(sys.modules) # create a copy
>>> m is modules
False

--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with random.randint

2010-02-02 Thread bob gailer

David wrote:

Hello list,

I thought this was easy even for me, but I was wrong, I guess.
Here is what I want to do: take two random numbers between 1 and 99, 
and put them into a list. 

[snip]

Or you can use list comprehension:

terms = [random.randint(1, 99) for i in range(2)]

or if you seek terseness:

terms = [random.randint(1, 99) for i in 'ab']


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] help with random.randint (cont. -- now: pseudo code)

2010-02-02 Thread bob gailer

David wrote:

[snip]


My suggestion (untested):

MAX = 12
NQ = 20 # of questions to ask

# create a 2 dimensional array of 1's
row = [1]*MAX
pool = [row[:] for i in range(MAX)]

incorrect = [] # store incorrectly answered combos here

def askQuestions():  # generate and ask questions:
 for i in range(NQ):
   while 1: # loop till we get an unused combo
 x, y = [random.randint(1,MAX) for i in 'ab']
 if mtable[x][y] == 1: # combo is available
   break
   askQuestion(x,y)
   # indicate asked
   mtable[x][y] = 0
   mtable[y][x] = 0
 showStats()

def askQuestion(x,y):
 solution = x*y
 # take answer from user
 ok =  user answer == solution
 if ok:
   correct += 1
 else:
   incorrect.append((x,y))
 return ok

def askFaultyAnswers():
 answer = raw_input("Try again the incorrect questions? (y/n) ")
 if answer == "y":
   correct = 0
   for x,y in incorrect:
 ok = askQuestion(x,y)
 # could use ok to remove combo from incorrect list.
 showStats()

askQuestions()
askFaultyAnswers()
print "good-bye!"






I think it is sensible to

* first create all possible solutions, then
* kick out doublettes, and only then
* ask questions

I have some questions though:

Is the overall structure and flow of this program okay? What are the 
main problems you can spot immediately


Calculating kicking randomizing is overkill. My code uses a 2 dimension 
array to track which x,y combos are available.


break is only valid within a loop.

Recursively calling askQuestions is not a good idea. Save recursion for 
when it is is meaningful. Use a loop instead.


There is no need for an incorrect counter. we can calculate it later 
(incorrect = NQ -correct)




In the very end I would like to take this code as a basis for a 
wxPython program. Are there any structural requirements I am violating 
here?


Not that I can see. It is common practice to separate logic from display.


If I want to limit the number of questions asked, say to 20, would I 
operate with slicing methods on the randomised pool?


My solution does not use a randomized pool. Just a loop over range(NQ)


How would you go about showing stats for the second run (i.e. the 
FaultyAnswers)? Right now I am thinking of setting the global 
variables correct and incorrect to 0 from _within_ askFaultyAnswers; 
then I would run showStats() also from _within_ askFaultyAnswers. Good 
idea?


Yes indeed. That is what I did before reading your comment! Great minds 
think alike.


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


  1   2   3   4   5   6   7   8   9   10   >