Re: [Tutor] String and integer

2008-10-21 Thread Jens Frid
Thank you all!Very informative and much appreciated!

Regards,
Jens

On Tue, Oct 21, 2008 at 1:33 AM, wesley chun <[EMAIL PROTECTED]> wrote:

> >> def nr():
> >>nr1 = input('Enter value: ')
> >>print str(nr1).strip('nr0')
> >>
> >> The user input is always on the form "nr08756" and i'd like to take out
> >> the "nr0" and then print the result.
> >> I can see that there is a problem with a variable looking like "pn0123"
> >> because i get: NameError: global name 'nr0123' is not defined.
> >>
> >> What is the right way to do this?
> >
> > raw_input() rather than input(). input evaluate whatever is entered;
> > raw_input returns as a string whatever is entered.
> >
> > In Python 3 raw_input will be renamed input and the old input will go
> away.
>
>
> everything that bob said... and more.  :-)
>
> definitely never ever use input()... it is absolutely unnecessary and
> a potential security hazard, hence the reason why its functionality
> will be completely removed in 3.0. for now, as bob has suggested, use
> raw_input() in the remaining 2.x releases then switch to input() for
> 3.x.
>
> with regards to the rest of your query, if you are certain that the
> first few chars of the input is 'nr0', you can just so nr1[3:] to get
> the rest. if you want to play it safe, throw in a "if
> nr1.startswith('nr0')" beforehand.
>
> finally, be careful with strip(). you are not stripping just the "nr0"
> with strip('nr0')... you are removing all 'n's, 'r's, and '0's from
> your string, i.e.
>
> >>> 'nr07890'.strip('nr0')
> '789'
>
> this is the reason why i suggested nr1[3:] instead... it chops off the
> 1st 3 chars and takes the remainer.
>
> hope this helps!
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>http://corepython.com
>
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to compute performance of python program

2008-10-21 Thread rajasekhar mamilla
Hi tutors,

Iam relatively new to python.

I  developed a project in python,now i want to know the performance of my
code.

Can i know how much time each python file takes or each program or each loop
takes to get executed.

Please help me if any such ways are available or any other  ways using which
i can find how efficient is my program.

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


Re: [Tutor] finding numbers in range of of numbers

2008-10-21 Thread Alan Gauld

"Srinivas Iyyer" <[EMAIL PROTECTED]> wrote


[[10,45],[14,23],[39,73],[92,135]]

I want to identify if any of the items in this list are in range of 
[5,100]


Sorry, I have no idea what you mean by that. Can you give
an example of passing and failing tests?

For example do any/all of the elements in your sample
list pass the test? If so why?

Often if you think carefullly and specifically about your
requirement the solution will become apparent. And if
you don't you are open to ambiguity and confusion.

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



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


Re: [Tutor] decision structures

2008-10-21 Thread Alan Gauld

"Brummert_Brandon" <[EMAIL PROTECTED]> wrote


Hello.  I am working with python for computer science this semester.
I am having a difficult time on one of my lab assignments


We won't do your homework for you but we can offer specific
help for specific queries. But you need to help us help you.


.  It is in the python programming book in chapter 7


Which Python programming book - there are literally dozens?!


I am being asked to write a program in that accepts a date
in the form month/date/year and outputs whether the date
is valid.  For example, 5/24/1962 is valid but 9/31/2000 is
not because September only has 30 days.


Since the exercise is around decision structures I assume
that using the standard Python date handling modules is
not allowed/acceptable?


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


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


Re: [Tutor] How to compute performance of python program

2008-10-21 Thread Alan Gauld


"rajasekhar mamilla" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

Hi tutors,

Iam relatively new to python.

I  developed a project in python,now i want to know the performance 
of my

code.


Look at the timeit command and the profiling module.

Very simple profile example here:

http://effbot.org/librarybook/profile.htm

Between them they should give you all the information you need.

HTH


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



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


Re: [Tutor] auto referer handler/opener for urlib2?

2008-10-21 Thread Kent Johnson
On Tue, Oct 21, 2008 at 12:05 AM, xbmuncher <[EMAIL PROTECTED]> wrote:
> I was reading about urllib2 openers.. Can I make any kind of def or function
> and make the urllib2 "urlopen" function run through this function first
> before opening a url? For example, something like a reporthook function.
> What I want to do is this:
>
> def autoReferer(handle):
> if handle.lastRequest.url != None:
> handle.addheader('referer' : handle.lastRequest.url)
>
>
> How can make this auto referer functionality with urllib2?

You can subclass BaseHandler with a class that has a
http_request(self, request) method. Add an instance of your handler to
the OpenerDirector. http_request() will be called with the request
object as its parameter and returns the request object as its result.
See the docs for BaseHandler.protocol_request (just after this link)
http://docs.python.org/library/urllib2.html#urllib2.BaseHandler.http_error_nnn

and look at the implementation of HTTPCookieProcessor for an example.

Note you must have an implementation of _request() for each
protocol you wish to handle, e.g. http and https.

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


Re: [Tutor] finding numbers in range of of numbers

2008-10-21 Thread Richard Lovely
Guessing you mean [5,100] as the inclusive interval notation, so all
but the last element of the example pass?

if any(True for x, y in listoflists if 5 <= x and y <= 100):
   #do stuff

does this do it for you?

Or if you want to know if any elements of the lists within the larger
list are within the range, and the sublists always have two elements
you could do:

if any(True for x,y in listoflists if 5<= x <=100 and 5<= y <=100):
#do stuff

otherwise, for a list of arbirtary length lists:

from itertools import chain
if any(True for x in chain(*listoflists) if 5<= x <=100):
#do stuff

You can be slightly faster (but less readable) by changing the
if any(...):
to
if [...]:

This is probably more pythonic, as well.

(There might be a better way, but I like itertools).

Hope something in here was helpful...

On 20/10/2008, Srinivas Iyyer <[EMAIL PROTECTED]> wrote:
> dear group,
> a simple question that often challenges me.
>
> I have
>
> I have a list of list:
>
> [[10,45],[14,23],[39,73],[92,135]]
>
> I want to identify if any of the items in this list are in range of [5,100]
>
> These numbers are large in original data, I will be using xrange for memory 
> issues.
>
>  thank you.
> srini
>
> __
> 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
>


-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding numbers in range of of numbers

2008-10-21 Thread Kent Johnson
On Tue, Oct 21, 2008 at 8:47 AM, Richard Lovely
<[EMAIL PROTECTED]> wrote:
> Guessing you mean [5,100] as the inclusive interval notation, so all
> but the last element of the example pass?
>
> if any(True for x, y in listoflists if 5 <= x and y <= 100):
>   #do stuff

or
if any((5 <= x and y <= 100) for x, y in listoflists):

> You can be slightly faster (but less readable) by changing the
> if any(...):
> to
> if [...]:

Why faster? any() will short-circuit - it will stop processing as soon
as it finds a True item. It also avoids building the entire list. I
would expect it to be faster.

Of course, if you really care about speed you should test, not guess.

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


Re: [Tutor] finding numbers in range of of numbers

2008-10-21 Thread Srinivas Iyyer
Dear Alan and tutors,

I apologize for careless description of my problem that lead to confusion. 
the problem arises due to large range of numbers and range has direction (both 
ascending and descending). 

I am giving an example from my real problem.

What I want to do:
 I want to check if a[.][1] and a[.][2] are 'within the range' of any element 
of b[.][1] or b[.][2]. (here '.' means any sub-element of list b.

a[.][1] and a[.][2] or b[.][1] b[.][2] can be either ascending or descending 
order
Ascending example from list a and b:
'xa','1511255', '1511279'
'xb','7516599','7516623'
'G1','1511200','1511325'
'G2','7516500','7516625'

descending order from list a and b:
'xc','98356290','98356266'
'G3','98356335','98356126'

a = [['xa','1511255', 
'1511279'],['xb','7516599','7516623'],['xc','98356290','98356266']]

b = 
[['G1','1511200','1511325'],['G2','7516500','7516625'],['G3','98356335','98356126']]

>>> for item1 in a:
... i1st = int(item1[1])
... i1en = int(item1[2])
... for item2 in b:
... i21 = int(item2[1])
... i22 = int(item2[2])
... if i1st and i1en in xrange(i21,i22):
... print "\t".join(item1)+'\t'+"\t".join(item2)
... if i1st and i1en in xrange(i22,i21):
... print "\t".join(item1)+'\t'+"\t".join(item2)
...
xa  1511255 1511279 G1  1511200 1511325
xb  7516599 7516623 G2  7516500 7516625
xc  9835629098356266G3  9835633598356126



Issue 1:  
a. Range of numbers is too high and xrange is also too slow.
   I used xrange instead of range - a slow process

Issue 2: 
Is this is a correct way to tackle this kind of problem. 


Issue 3: 
I have 200K elements in a anb b lists. this code has been running for last 18 
hours and only 800 elements of 200K have been evaluated. 

Could tutors help me with 3 issues. 
Thank you. 


srini


--- On Tue, 10/21/08, Alan Gauld <[EMAIL PROTECTED]> wrote:

> From: Alan Gauld <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] finding numbers in range of of numbers
> To: tutor@python.org
> Date: Tuesday, October 21, 2008, 5:10 AM
> "Srinivas Iyyer" <[EMAIL PROTECTED]>
> wrote
> 
> > [[10,45],[14,23],[39,73],[92,135]]
> >
> > I want to identify if any of the items in this list
> are in range of 
> > [5,100]
> 
> Sorry, I have no idea what you mean by that. Can you give
> an example of passing and failing tests?
> 
> For example do any/all of the elements in your sample
> list pass the test? If so why?
> 
> Often if you think carefullly and specifically about your
> requirement the solution will become apparent. And if
> you don't you are open to ambiguity and confusion.
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


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


Re: [Tutor] decision structures

2008-10-21 Thread bob gailer
Please reply to the tutor list, not just to me. We all learn and many of 
us can help.


Brummert_Brandon wrote:

This is what I have so far.  I am still confused by the string.split  setup.  
Thank you.


# dateCheck.py
# A program that accepts a date in the form month/day/year and outputs whether 
date is valid.
# Brandon Brummert, October 20, 2008

import string
def isLeapYear(leap):
if 0 == year % 400:
return True
elif 0 == year % 100:
return False
elif 0 == year % 4:
return True
else:
return False

def daysInMonth (date):
if 1 or 3 or 5 or 7 or 8 or 10 or 12:
return 31
elif 4 or 6 or 9 or 11:
return 30
elif 2:
return leap
def main():
currentdate= input ("What is the date (mm/dd/)?:")
month, date, year= string.split(currentdate)
print month/date/year
main()



  
Thank you. That is half of the input I'm seeking. The other half is: 
what happens when you run the program?

I'd expect you see a prompt:

What is the date (mm/dd/)?:

What do you enter at this prompt?

What happens next? You should see an exception (error). What is it? Why 
do you think it means and why did it happen?


Read the documentation for input().

As an aside - your program shows very little understanding of Python. 
Have you written other programs that ran the way you expected, or is 
this your first try?


Since it is homework we don't write the program for you. I'm trying to 
nudge you in the right direction, and would appreciate all you can give it.


Did you read the documentation for split?

month/date/year

is an expression. What does the / mean in an expression?

At the Python interpreter prompt >>> enter

if 1 or 3 or 5 or 7 or 8 or 10 or 12:
 print True

What happens? Why? Then try

if 1:
 print True

You are trying to compare date to numbers yet date does not appear in 
the if statement!


I have mentioned lists twice yet you have not said anything about them. 
Do you know what a list is and how it can be used?


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


When we take the time to be aware of our feelings and 
needs we have more satisfying interatctions with others.


Nonviolent Communication provides tools for this awareness.

As a coach and trainer I can assist you in learning this process.

What is YOUR biggest relationship challenge?

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


Re: [Tutor] finding numbers in range of of numbers

2008-10-21 Thread bob gailer




Srinivas Iyyer wrote:

  Dear Alan and tutors,

I apologize for careless description of my problem that lead to confusion. 
the problem arises due to large range of numbers and range has direction (both ascending and descending). 

I am giving an example from my real problem.

What I want to do:
 I want to check if a[.][1] and a[.][2] are 'within the range' of any element of b[.][1] or b[.][2]. (here '.' means any sub-element of list b.

a[.][1] and a[.][2] or b[.][1] b[.][2] can be either ascending or descending order
Ascending example from list a and b:
'xa','1511255', '1511279'
'xb','7516599','7516623'
'G1','1511200','1511325'
'G2','7516500','7516625'

descending order from list a and b:
'xc','98356290','98356266'
'G3','98356335','98356126'

a = [['xa','1511255', '1511279'],['xb','7516599','7516623'],['xc','98356290','98356266']]

b = [['G1','1511200','1511325'],['G2','7516500','7516625'],['G3','98356335','98356126']]

  
  

  
for item1 in a:

  

  
  ... i1st = int(item1[1])
... i1en = int(item1[2])
... for item2 in b:
... i21 = int(item2[1])
... i22 = int(item2[2])
... if i1st and i1en in xrange(i21,i22):
... print "\t".join(item1)+'\t'+"\t".join(item2)
... if i1st and i1en in xrange(i22,i21):
... print "\t".join(item1)+'\t'+"\t".join(item2)
...
xa  1511255 1511279 G1  1511200 1511325
xb  7516599 7516623 G2  7516500 7516625
xc  9835629098356266G3  9835i633598356126



Issue 1:  
a. Range of numbers is too high and xrange is also too slow.
   I used xrange instead of range - a slow process
  


You do not need range or xrange!


  
Issue 2: 
Is this is a correct way to tackle this kind of problem. 
  


Correct in that is solves the problem but is very inefficient.

I would make a copy of each list; take a pass thru each copy, convert
the strings to integers and reverse the descending pairs.
a1 = [['xa', 1511255, 1511279],['xb', 7516599, 7516623],['xc', 98356266, 98356290]]

b1 = [['G1', 1511200, 1511325],['G2', 7516500, 7516625],['G3', 98356126, 98356335]]

Then compare lower and upper limits (no need for range):

for a2 in a1:
  for b2 in b1:
    if a2[1] >= b2[1] and a2[2] < b2[2]: 
    print the matched result 
    break
  else:
    print the unmatched result.

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

When we take the time to be aware of our feelings and 
needs we have more satisfying interatctions with others.

Nonviolent Communication provides tools for this awareness.

As a coach and trainer I can assist you in learning this process.

What is YOUR biggest relationship challenge?



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


Re: [Tutor] finding numbers in range of of numbers

2008-10-21 Thread ALAN GAULD


a = [['xa','1511255', 
'1511279'],['xb','7516599','7516623'],['xc','98356290','98356266']]

b = 
[['G1','1511200','1511325'],['G2','7516500','7516625'],['G3','98356335','98356126']]

>>> for item1 in a:
... i1st = int(item1[1])
... i1en = int(item1[2])
... for item2 in b:
... i21 = int(item2[1])
... i22 = int(item2[2])
... if i1st and i1en in xrange(i21,i22):
... print "\t".join(item1)+'\t'+"\t".join(item2)
... if i1st and i1en in xrange(i22,i21):
... print "\t".join(item1)+'\t'+"\t".join(item2)


I would rewrite the 4 lines above to remove the 'in' test - which is basically
iterating over the range.

if i1st: # is this really the logic you want? it seems slightly 
suspicious to me
   if i21 < i1en < i22:
 # i21 is within the range.

That should save one iteration of the range for each inner loop. 
(One iteration is always of an empty list depending on which of i21,i22 is 
greater)

> Issue 1:  
> a. Range of numbers is too high and xrange is also too slow.
>I used xrange instead of range - a slow process


My solution removes the use of xrange.

> Issue 2: 
> Is this is a correct way to tackle this kind of problem. 

If it works then in a sense its correct. But I think checking the range 
boundaries is easier and should be faster

> Issue 3: 
> I have 200K elements in a anb b lists. this code has been running for 
> last 18 hours and only 800 elements of 200K have been evaluated. 

Which is a repeat of issue 1... I don't know how much my proposed 
solution will make but it should be a bit faster.

Dunno if that will help,

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


Re: [Tutor] finding numbers in range of of numbers

2008-10-21 Thread Kent Johnson
On Tue, Oct 21, 2008 at 10:43 AM, bob gailer <[EMAIL PROTECTED]> wrote:

> I would make a copy of each list; take a pass thru each copy, convert the
> strings to integers and reverse the descending pairs.
>
> a1 = [['xa', 1511255, 1511279],['xb', 7516599, 7516623],['xc', 98356266,
> 98356290]]
>
> b1 = [['G1', 1511200, 1511325],['G2', 7516500, 7516625],['G3', 98356126,
> 98356335]]
>
> Then compare lower and upper limits (no need for range):
>
> for a2 in a1:
>   for b2 in b1:
> if a2[1] >= b2[1] and a2[2] < b2[2]:
> print the matched result
> break
>   else:
> print the unmatched result.

If you sort  b1 by the second value then you can cut down on the
amount of the list you have to search:
if a2[1] > b2[2]:
  break

Apparently the clever way to do this is to use an interval tree:
http://en.wikipedia.org/wiki/Interval_tree

The bx-python project http://bx-python.trac.bx.psu.edu/ seems to have
an implementation here:
http://bx-python.trac.bx.psu.edu/browser/trunk/lib/bx/intervals/operations/quicksect.py

Also this method that you could use fairly easily:
http://www.bx.psu.edu/projects/bx-python/apidocs/lib/bx.intervals.intersection.Intersecter-class.html

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


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

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

Thanks Tim.


Send instant messages to your online friends http://uk.messenger.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Providing Solutions for all the Common Questions

2008-10-21 Thread Calvin Spealman
There was a discussion in the #python channel over at freenode about the
common questions we seem to field daily. These often revolve around problems
a lot of people need solutions for, and for which we have specific answers
to we always give. A lot of times this leads to teeth grinding as we try to
convince people about our advice. Why else are they asking if they then
argue with the answers they get? This takes a lot of time and energy, so a
number of us are starting a project to produce tutorials, guides,
and explanations to back up a lot of these solutions.
For example, a lot of people look to write an irc bot when they learn
Python, and often they either plan or are suggested to use Twisted. A
tutorial specifically for this need is being written.

We've decided to come here to organize this, as it seems to fit.

So there are some organizational issues to approach. I thought AppEngine
would be a good place to host everything, so I've already registered
pythonguides.appspot.com and plan to throw up a basic Wiki to start. Going
forward there are some things I want to implement there to support our
specific needs. For now, its just a free host.

One other initial need is to collect the problems we need to provide our
solutions for. So, what do we people ask over and over?

-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://techblog.ironfroggy.com/
Follow me if you're into that sort of thing:
http://www.twitter.com/ironfroggy
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


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

2008-10-21 Thread Tim Golden

Tim Brown wrote:

Hi,
I'm trying to create and append unicode strings to a utf-16 text file.
The best I could come up with was to use codecs.open() with an 
encoding of 'utf-16' but when I do an append I get another UTF16 BOM 
put into the file which other programs do not expect to see :-(

Is there some way to stop codecs from doing this or is there a better
way to create and add data to a utf-16 text file?



Well, there's nothing to stop you opening it "raw", as it were,
and just appending unicode encoded as utf16.


s = u"The cat sat on the mat"
f = open ("utf16.txt", "wb")
for word in s.split ():
 f.write (word.encode ("utf16") + " ")

f.close ()



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


Re: [Tutor] Providing Solutions for all the Common Questions

2008-10-21 Thread vishwajeet singh
That seems to be nice idea.
we can look into mailing archives and pick problems from there.

Congratulations and thanks for nice initiative.

keep the good work

On Tue, Oct 21, 2008 at 10:06 AM, Calvin Spealman <[EMAIL PROTECTED]>wrote:

> There was a discussion in the #python channel over at freenode about the
> common questions we seem to field daily. These often revolve around problems
> a lot of people need solutions for, and for which we have specific answers
> to we always give. A lot of times this leads to teeth grinding as we try to
> convince people about our advice. Why else are they asking if they then
> argue with the answers they get? This takes a lot of time and energy, so a
> number of us are starting a project to produce tutorials, guides,
> and explanations to back up a lot of these solutions.
> For example, a lot of people look to write an irc bot when they learn
> Python, and often they either plan or are suggested to use Twisted. A
> tutorial specifically for this need is being written.
>
> We've decided to come here to organize this, as it seems to fit.
>
> So there are some organizational issues to approach. I thought AppEngine
> would be a good place to host everything, so I've already registered
> pythonguides.appspot.com and plan to throw up a basic Wiki to start. Going
> forward there are some things I want to implement there to support our
> specific needs. For now, its just a free host.
>
> One other initial need is to collect the problems we need to provide our
> solutions for. So, what do we people ask over and over?
>
> --
> Read my blog! I depend on your acceptance of my opinion! I am interesting!
> http://techblog.ironfroggy.com/
> Follow me if you're into that sort of thing:
> http://www.twitter.com/ironfroggy
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Cheers,
Vishwajeet
http://www.singhvishwajeet.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Providing Solutions for all the Common Questions

2008-10-21 Thread Hansen, Mike
 

> -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED] On 
> Behalf Of Calvin Spealman
> Sent: Tuesday, October 21, 2008 8:07 AM
> To: tutor@python.org
> Subject: [Tutor] Providing Solutions for all the Common Questions
> 
> There was a discussion in the #python channel over at 
> freenode about the common questions we seem to field daily. 
> These often revolve around problems a lot of people need 
> solutions for, and for which we have specific answers to we 
> always give. A lot of times this leads to teeth grinding as 
> we try to convince people about our advice. Why else are they 
> asking if they then argue with the answers they get? This 
> takes a lot of time and energy, so a number of us are 
> starting a project to produce tutorials, guides, and 
> explanations to back up a lot of these solutions.
> 
> For example, a lot of people look to write an irc bot when 
> they learn Python, and often they either plan or are 
> suggested to use Twisted. A tutorial specifically for this 
> need is being written.
> 
> We've decided to come here to organize this, as it seems to fit. 
> 
> 
> So there are some organizational issues to approach. I 
> thought AppEngine would be a good place to host everything, 
> so I've already registered pythonguides.appspot.com and plan 
> to throw up a basic Wiki to start. Going forward there are 
> some things I want to implement there to support our specific 
> needs. For now, its just a free host.
> 
> One other initial need is to collect the problems we need to 
> provide our solutions for. So, what do we people ask over and over?
> 
> -- 
> Read my blog! I depend on your acceptance of my opinion! I am 
> interesting!
> http://techblog.ironfroggy.com/
> Follow me if you're into that sort of thing: 
> http://www.twitter.com/ironfroggy

A long time ago in a Python galaxy far far away, a tutor FAQ was written. It 
has been bounced around. I found it at http://effbot.org/pyfaq/tutor-index.htm. 
Some of these entries could use some updating. A basic wiki for these FAQs 
would be great.

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


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

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

IIRC the UTF-16BE and UTF-16LE codecs don't use BOMs.

You could also convert the unicode strings to str yourself and open
the file as plain text.

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


Re: [Tutor] Providing Solutions for all the Common Questions

2008-10-21 Thread Kent Johnson
On Tue, Oct 21, 2008 at 10:06 AM, Calvin Spealman <[EMAIL PROTECTED]> wrote:
> There was a discussion in the #python channel over at freenode about the
> common questions we seem to field daily.
> We've decided to come here to organize this, as it seems to fit.

Welcome. Please subscribe to the list if you want to use it as a
discussion forum!

> One other initial need is to collect the problems we need to provide our
> solutions for. So, what do we people ask over and over?

A previous effort on this list led to
http://effbot.org/pyfaq/tutor-index.htm

My own Kent's Korner articles are to some extent an attempt to write
up answers to questions that I am tired of answering:
http://personalpages.tds.net/~kent37/kk/index.html

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


Re: [Tutor] Providing Solutions for all the Common Questions

2008-10-21 Thread Scott Nelson
To throw out an idea...

http://www.showmedo.com/ is a site that believes that learning-by-watching
is a very effective way to teach people new skills.  So, they host lots of
(user-generated) screencasts (usually 5-10 minutes) that show people how to
do things.  Because the site is Python focused, there are 350+ videos on
learning Python (150+ beginner oriented vids).  Would it be helpful to take
the most common questions and create screencasts that demonstre the answers
to common questions, post them to ShowMeDo and get a collection of links
togeher?  Just a thought...
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python 2.4 threading

2008-10-21 Thread Ertl, John C CIV 63134
Classification: UNCLASSIFIED 
Caveat (s): FOUO

All,

I have a program that basically loops through two loops and I wanted to speedup 
the stuff inside the second loop so I thought threading would be a good idea 
but I am having a hard time getting it to work.  All of the examples I have 
seen that use a Queu have had the threaded stuff inside its own class.  I have 
tired that but I am not getting it.

Could anyone give me some hints on how I might set this up.  Below is an 
outline of my current program.  What do I need to do to thread the inside loop.

Many of the functions depicted below inherit function from other modules.

class weather(a bunch of stuff)

 def 1

 def 2

 def3

 defetc


weax = weather()

.stuff.

for each in outsideloop:

def1
defn

for each in insideloop:

def1
def2
defn


I have tried to take the inside loop and make it a class but there are so many 
functions , some inherited that are used on the inside and outside loop that I 
am getting errors all over the place.  Is it possible to thread without it 
being its own class?  

Thanks for the ideas and help.


John Ertl
Meteorologist

FNMOC
7 Grace Hopper Ave.
Monterey, CA 93943
(831) 656-5704
[EMAIL PROTECTED]

Classification: UNCLASSIFIED 
Caveat (s): FOUO
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


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

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

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

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

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

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


Re: [Tutor] finding numbers in range of of numbers

2008-10-21 Thread Richard Lovely
I felt I need to appolgise for my first post in this thread...

I don't have internet access, and I've yet to find a public computer
with Python, so I'm unable to test any code I write.  I'm going have
to discpline myself not to post to here unless its: a) a problem of my
own, or b) an answer that doesn't contain code...

I also have nothing like the experience of some of you guys, who I'm
pretty much in awe of...

If I'm tempted again, I might have to remove myself from the list.

I'm just glad my session timed out before I was able to send the
other, more useless message.  (it's done that twice now, and I suppose
I should count myself as lucky...)

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 2.4 threading

2008-10-21 Thread Kent Johnson
On Tue, Oct 21, 2008 at 1:04 PM, Ertl, John C CIV 63134
<[EMAIL PROTECTED]> wrote:
> Classification: UNCLASSIFIED
> Caveat (s): FOUO
>
> All,
>
> I have a program that basically loops through two loops and I wanted to
> speedup the stuff inside the second loop so I thought threading would be a
> good idea but I am having a hard time getting it to work.  All of the
> examples I have seen that use a Queu have had the threaded stuff inside its
> own class.  I have tired that but I am not getting it.

You don't need a class to use threading. This example uses ordinary functions:
http://blog.doughellmann.com/2007/04/pymotw-queue.html

However if your program is compute-bound threading won't help.

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


Re: [Tutor] finding numbers in range of of numbers

2008-10-21 Thread Kent Johnson
On Tue, Oct 21, 2008 at 2:26 PM, Richard Lovely
<[EMAIL PROTECTED]> wrote:
> I felt I need to appolgise for my first post in this thread...

I don't know why...

> I don't have internet access, and I've yet to find a public computer
> with Python, so I'm unable to test any code I write.  I'm going have
> to discpline myself not to post to here unless its: a) a problem of my
> own, or b) an answer that doesn't contain code...
>
> I also have nothing like the experience of some of you guys, who I'm
> pretty much in awe of...

We all were beginners once. Doing your best to answer questions is a
good way to learn. Generally the really boneheaded answers are
corrected so you don't have to worry about making a mistake.

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


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

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

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

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

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

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

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


Re: [Tutor] how to see a number as two bytes

2008-10-21 Thread shawn bright
Thanks for all your help on this, gents.
found what works.
shawn

On Mon, Oct 20, 2008 at 6:06 PM, Alan Gauld <[EMAIL PROTECTED]>wrote:

> "shawn bright" <[EMAIL PROTECTED]> wrote
>
>  i have a script that needs to send a number as two bytes.
>> how would i be able to see a number expressed as a hi byte and a lo byte?
>>
>
> One way is to use the struct module.
> It has the advantage of allowing selection of big endian(>) or little
> endian(<) representation etc. The H symbol can be used for a short
> integer - ie 2 bytes...
>
> eg
>
>  import struct
 b = struct.pack(">H", 279)
 b

>>> '\x01\x17'
>
>> b = struct.pack(">>> b

>>> '\x17\x01'
>
>>

> Note that Python will print bytes with printable representations as
> the character form but the data is still two bytes.
>
> eg
>
>> struct.pack("H", 33)

>>> '!\x00'
>
>> chr(33)

>>> '!'
>
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decision structures

2008-10-21 Thread bob gailer




Perhaps someone else will help you. I won't offer anything more until
you respond to a lot more of my questions and comments.

AND PLEASE reply to tutor@python.org as well as whoever responds to you.

Brummert_Brandon wrote:

  I have written other programs for the assignment.  Here is a program that I just did so far for and it runs and works correctly.  I have very little knowledge of computer science because I am an education major in a room filled with computer science majors.  However, I have yet to figure out the problem that I have been working on previously.  The first one below is what I just finished today but I am still stuck on the date one.

# easterDate2.py
# A program that calculates the date of Easter from 1900-2099.
# Brandon Brummert, October 21, 2008


def main():
print "Calculates the Date of Easter"
year = input("What year would like to know the date for easter? ")
if year < 1900:
print "This program only works for the years 1900 to 2099"
if year > 2099:
print "This program only works for the years 1900 to 2099"
if year >=1900:
a = year % 19
b = year % 4
c = year % 7
d = (19*a + 24) % 30
e = (2*b + 4*c + 6*d + 5) % 7
k = 22 + d + e
if year == 1954 or year == 1981 or year == 2049 or year == 2076:
k = (22 + d + e) - 31 - 7
if k <= 31:
print "Easter is March", k
if k > 31:
k = (22 + d + e) - 31
print "Easter is April", k



main()



here is the one that I am still stuck on.  not much has changed since last time.

# dateCheck.py
# A program that accepts a date in the form month/day/year and outputs whether date is valid.
# Brandon Brummert, October 20, 2008

import string
def isLeapYear(leap):
if 0 == year % 400:
return True
elif 0 == year % 100:
return False
elif 0 == year % 4:
return True
else:
return False

def daysInMonth (date):
if 1 or 3 or 5 or 7 or 8 or 10 or 12:
return 31
elif 4 or 6 or 9 or 11:
return 30
elif 2:
return leap
def main():
currentdate= input ("What is the date (mm/dd/)?:")
month, date, year= string.split(currentdate)
print month/date/year
main()







From: bob gailer [[EMAIL PROTECTED]]
Sent: Tuesday, October 21, 2008 10:25 AM
To: Brummert_Brandon; tutorpythonmailinglist Python
Subject: Re: [Tutor] decision structures

Please reply to the tutor list, not just to me. We all learn and many of
us can help.

Brummert_Brandon wrote:
  
  
This is what I have so far.  I am still confused by the string.split  setup.  Thank you.


# dateCheck.py
# A program that accepts a date in the form month/day/year and outputs whether date is valid.
# Brandon Brummert, October 20, 2008

import string
def isLeapYear(leap):
if 0 == year % 400:
return True
elif 0 == year % 100:
return False
elif 0 == year % 4:
return True
else:
return False

def daysInMonth (date):
if 1 or 3 or 5 or 7 or 8 or 10 or 12:
return 31
elif 4 or 6 or 9 or 11:
return 30
elif 2:
return leap
def main():
currentdate= input ("What is the date (mm/dd/)?:")
month, date, year= string.split(currentdate)
print month/date/year
main()





  
  Thank you. That is half of the input I'm seeking. The other half is:
what happens when you run the program?
I'd expect you see a prompt:

What is the date (mm/dd/)?:

What do you enter at this prompt?

What happens next? You should see an exception (error). What is it? Why
do you think it means and why did it happen?

Read the documentation for input().

As an aside - your program shows very little understanding of Python.
Have you written other programs that ran the way you expected, or is
this your first try?

Since it is homework we don't write the program for you. I'm trying to
nudge you in the right direction, and would appreciate all you can give it.

Did you read the documentation for split?

month/date/year

is an _expression_. What does the / mean in an _expression_?

At the Python interpreter prompt >>> enter

if 1 or 3 or 5 or 7 or 8 or 10 or 12:
  print True

What happens? Why? Then try

if 1:
  print True

You are trying to compare date to numbers yet date does not appear in
the if statement!

I have mentioned lists twice yet you have not said anything about them.
Do you know what a list is and how it can be used?

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

When we take the time to be aware of our feelings and
needs we have more satisfying interatctions with others.

Nonviolent Communication provides tools for this awareness.

As a coach and trainer I can assist you in learning this process.

What is YOUR biggest relationship challenge?

  



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

When we take the time to be aware of our feelings and 
needs we have more sati

Re: [Tutor] Multiple lists from single list with nested lists

2008-10-21 Thread Sander Sweers
On Tue, Oct 21, 2008 at 01:36, Kent Johnson <[EMAIL PROTECTED]> wrote:
>> somelist = ['Test1', 'Text2', ['1', '2'], 'Text3']
>> templist = []
>> for x in range(len(somelist[2])):
>>templist.append([somelist[0], somelist[1], somelist[2][x], somelist[3]])
>
> Is it always just the third item that is a list? If so I think your
> solution is not too bad.

The actual list is 12 items long (python lenght) and the 6, 7 and 8th
item should be lists after I split them. A sanitized example:

['SOMENAME', '1234567890', '"TEXT1"', 'TEXT2', '59', '',
'10/03;10/15', '10/09;10/20', '1;70', '', '', '']

> or use a list comprehension:
> templist = [ somelist[0:2] + [x] + somelist[3:] for x in somelist ]

This did not work but the below did ;-)
templist = [ somelist[:1] + [x] + somelist[3:] for x in somelist[2] ]

It gave me some great pointers on how to handle this.

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


Re: [Tutor] decision structures

2008-10-21 Thread christopher . henk
> Perhaps someone else will help you. I won't offer anything more until 
you respond to a lot more of my questions and comments.
> 

Read what Bob has written back to you and try it or ask questions related 
to it if you don't understand something he said.

> AND PLEASE reply to tutor@python.org as well as whoever responds to you.
> 
> Brummert_Brandon wrote: 
> here is the one that I am still stuck on.  not much has changed since 
last time.

> def main():
> currentdate= input ("What is the date (mm/dd/)?:")

Try printing out the value of currentdate here and see what you get. Bob 
has mentioned that you may have some issues with your result and gave a 
suggestion on how to fix it.  It has also been mentioned several times in 
other current threads on the list, since it is a common point of 
confusion.

Also, one of the nice things about Python is you can use the interactive 
interpreter to see what you would get as a response to your code.
Try starting up Python and just typing in the line:
input ("Type something here:")

and then enter a date.

What do you get as an answer?
Is it what you expected?

try is again with typing different things in and see what answers you get.

What is different between what the user is typing in this program and your 
previous program and what you are doing with that input?

Once you get past this point we can address the rest of the program. 

The people on the list are very happy to help but will not do the work for 
you.  You need to read what the responses are and work with the tutors.

hope that helps get you started,

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


Re: [Tutor] how to see a number as two bytes

2008-10-21 Thread Luke Paireepinart
Nice mention of the struct module, Alan.  I had forgotten about it and
I just finished an app that really could've been simplified by it.  I
might retool it to use struct when I have to revisit it for the next
part of my class assignment.

On Tue, Oct 21, 2008 at 3:34 PM, shawn bright <[EMAIL PROTECTED]> wrote:
> Thanks for all your help on this, gents.
> found what works.
> shawn
>
> On Mon, Oct 20, 2008 at 6:06 PM, Alan Gauld <[EMAIL PROTECTED]>
> wrote:
>>
>> "shawn bright" <[EMAIL PROTECTED]> wrote
>>
>>> i have a script that needs to send a number as two bytes.
>>> how would i be able to see a number expressed as a hi byte and a lo byte?
>>
>> One way is to use the struct module.
>> It has the advantage of allowing selection of big endian(>) or little
>> endian(<) representation etc. The H symbol can be used for a short
>> integer - ie 2 bytes...
>>
>> eg
>>
> import struct
> b = struct.pack(">H", 279)
> b
>>
>> '\x01\x17'
>
> b = struct.pack(" b
>>
>> '\x17\x01'
>
>>
>> Note that Python will print bytes with printable representations as
>> the character form but the data is still two bytes.
>>
>> eg
>
> struct.pack("H", 33)
>>
>> '!\x00'
>
> chr(33)
>>
>> '!'
>>
>>
>> HTH,
>>
>> --
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.freenetpages.co.uk/hp/alan.gauld
>>
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>
>
> ___
> 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] Multiple lists from single list with nested lists

2008-10-21 Thread Kent Johnson
On Tue, Oct 21, 2008 at 5:09 PM, Sander Sweers <[EMAIL PROTECTED]> wrote:

> This did not work but the below did ;-)
> templist = [ somelist[:1] + [x] + somelist[3:] for x in somelist[2] ]

somelist[:1] doesn't include somelist[1] so I think you are missing
one element of your original list.

List slices like [0:2] or [:1] are up-to-but-not-including the second index.

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


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

2008-10-21 Thread Mark Tolonen


"Tim Golden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

Tim Brown wrote:

Hi,
I'm trying to create and append unicode strings to a utf-16 text file.
The best I could come up with was to use codecs.open() with an encoding 
of 'utf-16' but when I do an append I get another UTF16 BOM put into the 
file which other programs do not expect to see :-(

Is there some way to stop codecs from doing this or is there a better
way to create and add data to a utf-16 text file?



Well, there's nothing to stop you opening it "raw", as it were,
and just appending unicode encoded as utf16.


s = u"The cat sat on the mat"
f = open ("utf16.txt", "wb")
for word in s.split ():
 f.write (word.encode ("utf16") + " ")

f.close ()



TJG


Result: The@揾愀琀 sat@濾渀 the@淾愀琀 

word.encode('utf16') adds a BOM every time, and the space wasn't encoded.

utf-16-le and utf-16-be don't add the BOM.  This works:

import codecs
s = u"The cat sat on the mat"
f = codecs.open("utf16.txt","wb","utf-16-le")
f.write(u'\ufeff') # if you want the BOM
for word in s.split ():
   f.write (word + u' ')
f.close()

-Mark


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


[Tutor] (no subject)

2008-10-21 Thread amit sethi
Hi can any body give me an example as to how i can use Incremental Parser in
xml.sax

-- 
A-M-I-T S|S
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor