Re: [Tutor] lib2to3 fixers

2010-06-12 Thread Steven D'Aprano
On Sat, 12 Jun 2010 05:27:39 am Zubin Mithra wrote:
> Hey everyone,
>
> I just discovered that the following construct does not work in Py3k.
>
> >>> string.maketrans('-', '_')

Like the error message says, you have to use bytes, which I grant is 
counter-intuitive, but it does work:


>>> table = string.maketrans(b'-', b'_')
>>> 'abc-def'.translate(table)
'abc_def'


(Perhaps it shouldn't though... it seems to be an undocumented feature.)



> However, the following works,
>
> >>> str.maketrans('-', '_')
>
> When i try to convert a python module containing the above construct,
> it does not get modified in a way such that it could run on Python
> 3.0

I think this should be reported as a bug/feature request on the bug 
tracker. Having 2to3 be as extensive as possible is a high priority to 
the Python development team.

http://bugs.python.org/


> 1. replace string.maketrans() with a function which is compatible in
> both Python 2.x and 3.0 ; as of now I`m unaware of such a construct.

That at least is easy.

def maketrans(a, b):
try:
return string.translate(a, b)
except TypeError:
return str.translate(a, b)



> 2. write a fixer for doing this which I could use. I could`nt find
> any good tutorials out there on writing fixers, i`d be grateful if
> you could point me to any.

For that you probably need to ask on the main Python mailing list or 
newsgroup:

comp.lang.python
http://mail.python.org/mailman/listinfo/python-list




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


Re: [Tutor] Better construct? (was no subject)

2010-06-12 Thread Luke Paireepinart
>
>> ## Can someone suggest a pythonesque way of doing this?
>>
>>
>> def getid():
>>    response  = raw_input('prompt')
>>    if response not in [ "", "y", "Y", "yes"] :
>>        getid()    # ouch
>>    print "continue working"
>>    # do more stuff
>>    # do more stuff
>>
This seems like really strange behavior.  If the response is wrong,
you will then have another instance of getid, then if they get the
response correct, you will execute your code twice!  Was that really
your intent?
I think what you really want is:
def getid():
valid = False
while not valid:
response = raw_input('prompt')
valid = response.strip().lower() in ["", "y", "yes"]

>One improvement - response.lower().startswith("yes") will cover all your cases.

Am I misunderstanding? They appear to have different behaviors.
>>> x = ""
>>> y = ["", "y", "Y", "yes"]
>>> x not in y
False
>>> x.lower().startswith('yes')
False
>>> x = "yes"
>>> x not in y
False
>>> x.lower().startswith('yes')
True
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python a substitute/alternative for PhP?

2010-06-12 Thread Eldon Londe Mello Junior

Hi there,

Just would like to thanks all of those who provided me with some insight about 
which ways to go about programming. I'll consider every single piece of advice. 
I would also like to apologize for I didn't mean to hijack no thread, that was 
just so stupid of me.

As I'm finishing my PhP course by Monday now I feel comfortable enough to delve 
into Python which means you'll probably be hearing from me soon,

Cheers for the English speakers and saludos a José Del Toro!

Eldon.
  
_
Your E-mail and More On-the-Go. Get Windows Live Hotmail Free.
https://signup.live.com/signup.aspx?id=60969___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] OT: Great find!

2010-06-12 Thread Eike Welk
On Saturday June 12 2010 20:22:03 Wayne Werner wrote:
> I want to do something like this:
> http://www.kulturblog.com/2007/11/marshie-attacks-halloween-interactive-dri
> veway-activity/

Great find! That's a very nice idea!


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


Re: [Tutor] Better construct? (was no subject)

2010-06-12 Thread bob gailer

On 6/12/2010 3:59 PM, Alan Gauld wrote:


"bob gailer"  wrote

You can collect functions in a sequence, then iterate over it. This 
allows for easy expansion (when you decide to add another function).


funcs = (dosomething(), dosomethingelse())


I suspect Bob meant to leave off the (). 


Yep. Thank you for the correction.

--
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] Problems with Importing into the Python Shell

2010-06-12 Thread Alan Gauld


"Andrew Martin"  wrote

am having some trouble. First off, I do not understand how to import 
things
into the python shell. I have a script I saved as chap03.py, but 
when I try

to import it into the python shell i get an error like this:


from chap03 import *


Traceback (most recent call last):
 File "", line 1, in 
   from chap03 import *
 File "C:/Python26\chap03.py", line 2
   print param param
   ^
SyntaxError: invalid syntax


OK, First things first. You have imported the file correctly.
Thats why you are getting the error.
Now read the error. It says there is a syntax error, which
there is. Can you see what you have done wrong in the
print statement. The little caret symbol is giving you
a big clue...

Finally, its considered bad style to use from foo import *
It can lerad to difficult to debug problems where two files
have things with the same name.
It is better to use

import foo

and then use foo.name to access things.
It is more typing but much safer and more reliable.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Tutor Digest, Vol 76, Issue 31

2010-06-12 Thread Alan Gauld

Please do not send the entire digest when replying rto a single
email. Use your editor to remove the redundant material.


"saurabh agrawal"  wrote

You can use method name count in list also for getting the repeats.

#!/usr/bin/python

li=[1,2,3,1,4,5,7,3,4,1]
for i in range(len(li)):
print li[i], li.count(li[i])

cheers,

Saurabh



--- On Fri, 11/6/10, tutor-requ...@python.org 
 wrote:


From: tutor-requ...@python.org 
Subject: Tutor Digest, Vol 76, Issue 31
To: tutor@python.org
Date: Friday, 11 June, 2010, 8:19 PM

... 



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


Re: [Tutor] Adding line numbers to a Python Script

2010-06-12 Thread Alan Gauld


"Sudip Bhattacharya"  wrote


for line in fileinput.input(inplace = true)(2)
  line = line.rstrip()(3)
  num=fileinput.lineno()..(4)
  print '%-40s #%2i' %(line,num).(5)

Line (3) - Are we stripping the entire line of code first, inserting 
the
code at the end (line (5)) and then placing it back at the same 
place ?


Fire up the python interpreter and type:


help("".strip)


See if you understand what it says. If not come back here and ask 
again.
Python's help fuinction is very powerful, learn to use it for fast 
answers.


Line (5) - What does the individual characters in the expression 
"Print

'%-40s #%2i' %(line,num)" mean ?


These are formatting characters. If you read the Simple Sequences
topic in my tutor you will get some easier examples to try.

Then read the Python documentation - search for format string...


- '-40s' : is this the space [what does "-40s" mean] that we are
creating post - which the line nos is inserted "#%2i" ?


Again fitre up the Python interpreter and try it out.


"%-40s" % "Some string here"


Now try again with a different number, Try missing out the minus sign.
Can you see what the different bits do?

Now go read the documentation again. Try some different data types.
Experiment. Its the best way to really understand.


- What does '%2" mean ? - Is that 2 cursor spaces of width ?


Close but again Read the docs, try it, experiment. See for yourself.


"%2i" %  7


HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Better construct? (was no subject)

2010-06-12 Thread Alan Gauld


"bob gailer"  wrote

You can collect functions in a sequence, then iterate over it. This 
allows for easy expansion (when you decide to add another function).


funcs = (dosomething(), dosomethingelse())


I suspect Bob meant to leave off the (). You would normally just
use the function name. (Unless these are factory functions
returning another function but I don't think that was the intent! :-)

funcs = (doSomething, doSomethingElse)


for func in funcs:
  getid()
  func()


HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] New to Programming

2010-06-12 Thread Alan Gauld


"Kaushal Shriyan"  wrote

I am absolutely new to programming language. Dont have any 
programming

experience. Can some one guide me please. is python a good start for
novice.


Yes, it is one of the best languages for an absolute beginner.
It may be all the language you ever need but even if you branch
out to others the principles you learn in Python will translate 
easily.


There are a bunch of tutorials for absiolute beginners listed
on the Python web site (including mine)

Try here (or follow my .sig):

http://wiki.python.org/moin/BeginnersGuide/NonProgrammers


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Python a substitute/alternative for PhP?

2010-06-12 Thread Alan Gauld

"Eldon Londe Mello Junior"  wrote

First, please don't hijack an existing thread,
this message appears under a thread about Zope DB!
Always post a new message to start a new thread.
It will get more readers and not confuse readers using
threaded mail/newsreaders.


However, I've been reading a lot about programming
languages and stuff in order to make the best choice
as I don't want to spend much time learning unnecessary
things I won't need in the future.


I'm not sure what you think the "unnecessary things" are
but programming languages come and go and as a professional
programmers you can expect to have to learn at least a
dozen before you are done, probably more like two dozen.
So don't think you will pick a single language and never
have to learn another.

As a minimum you will probably need to know:
a) A general purpose language - Java, python, C++, Visual Basic, 
etc...

b) SQL
c) Javascript
d) An OS shell language(DOS batch/WSH or a Linux shell(bash/csh or 
Korn)


Very few modern applications have less than those 4 language groups
embedded within them somewhere. The minimum I've ever seen in
a professional project is 3. The maximum was 12 - but it was a big 
project.



opensource-solutions professional programmer.


Caveat: There is not a lot of money in that market. People use
Opensource because they expect it to be cheap. That means
they won't pay the programmer as much either... At lerast thats
my experience. There is much more money to be had programming
Oracle or DB2 apps than creating MySql apps...


beginners start with PhP and stick with it or go for JAVA
or MS proprietary languages. Actually, you can only
learn python on your own around here as no college
or private institutes offer python courses.


Pyton didn't even exist when I started, but neither did Java
or C++ or VB... And in twenty years time possibly none of
these languages will be in vogue and we will all be using
periwinkle gizzard or whatever the latest craze is called...


FINAL QUESTION> Is Python a substitute for PHP?


It can do similar things but it does it differently, especially for 
the

web. Although you can write standalone PHP programs it is
usually used on the Web. Most serious webv developers
combine Python with a web framework like Django or
Pylons or whatever. Arguably Python + Framework is superior
to PHP - but less widely supported on ISP servers.


I mean, can I start learning python by trying to do the
things I've learned with PHP?


You can, but the web elements will be very different.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Tutor Digest, Vol 76, Issue 31

2010-06-12 Thread saurabh agrawal
Hi,

You can use method name count in list also for getting the repeats.

#!/usr/bin/python

li=[1,2,3,1,4,5,7,3,4,1]
for i in range(len(li)):
    print li[i], li.count(li[i])

cheers,

Saurabh



--- On Fri, 11/6/10, tutor-requ...@python.org  wrote:

From: tutor-requ...@python.org 
Subject: Tutor Digest, Vol 76, Issue 31
To: tutor@python.org
Date: Friday, 11 June, 2010, 8:19 PM

Send Tutor mailing list submissions to
    tutor@python.org

To subscribe or unsubscribe via the World Wide Web, visit
    http://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
    tutor-requ...@python.org

You can reach the person managing the list at
    tutor-ow...@python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

   1. Looking for duplicates within a list (Ken G.)
   2. Re: Looking for duplicates within a list (Alex Hall)
   3. Re: Looking for duplicates within a list (Ken G.)
   4. Re: Looking for duplicates within a list (Ken G.)
   5. Re: Looking for duplicates within a list (Sander Sweers)
   6. Re: Looking for duplicates within a list (Jose Amoreira)


--

Message: 1
Date: Fri, 11 Jun 2010 09:57:34 -0400
From: "Ken G." 
To: tutor@python.org
Subject: [Tutor] Looking for duplicates within a list
Message-ID: <4c1240ce.7050...@insightbb.com>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

I have been working on this problem for several days and I am not making 
any progress.  I have a group of 18 number, in ascending order, within a 
list.  They ranged from 1 to 39.  Some numbers are duplicated as much as 
three times or as few as none.

I started with one list containing the numbers.  For example, they are 
listed as like below:

a = [1, 2, 3, 3, 4]

I started off with using a loop:

    for j in range (0, 5):
    x = a[0] # for example, 1

How would I compare '1' with 2, 3, 3, 4? 

Do I need another duplicated list such as b = a and compare a[0] with 
either b[0], b[1], b[2], b[3], b[4]?

Or do I compare a[0] with a[1], a[2], a[3], a[4]?

In any event, if a number is listed more than once, I would like to know 
how many times, such as 2 or 3 times.  For example, '3' is listed twice 
within a list.

TIA,

Ken










--

Message: 2
Date: Fri, 11 Jun 2010 10:20:20 -0400
From: Alex Hall 
To: "Ken G." 
Cc: tutor@python.org
Subject: Re: [Tutor] Looking for duplicates within a list
Message-ID:
    
Content-Type: text/plain; charset=ISO-8859-1

On 6/11/10, Ken G.  wrote:
> I have been working on this problem for several days and I am not making
> any progress.  I have a group of 18 number, in ascending order, within a
> list.  They ranged from 1 to 39.  Some numbers are duplicated as much as
> three times or as few as none.
FYI, Python's "set" data type will let you have a list and never have
a repeat. I know that is not your goal now, but if you want to remove
duplicates, it seems like a good choice.
>
> I started with one list containing the numbers.  For example, they are
> listed as like below:
>
> a = [1, 2, 3, 3, 4]
>
> I started off with using a loop:
>
>     for j in range (0, 5):
>     x = a[0] # for example, 1
>
> How would I compare '1' with 2, 3, 3, 4?
>
> Do I need another duplicated list such as b = a and compare a[0] with
> either b[0], b[1], b[2], b[3], b[4]?
>
> Or do I compare a[0] with a[1], a[2], a[3], a[4]?
A couple points here. First, you will want to make life easier by
saying range(0, len(a)) so that the loop will work no matter the size
of a.
Second, for comparing a list to itself, here is a rather inefficient,
though simple, way:

for i in range(0, len(a)):
 x=a[i]
 for j in range(0, len(a)):
  y=a[j]
  if(x==y and i!=j): #match since a[i]==a[j] and i and j are not the
same index of a
>
> In any event, if a number is listed more than once, I would like to know
> how many times, such as 2 or 3 times.  For example, '3' is listed twice
> within a list.
Do not quote me here, but I think sets may be able to tell you that as well.
>
> TIA,
>
> Ken
>
>
>
>
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap


--

Message: 3
Date: Fri, 11 Jun 2010 10:31:58 -0400
From: "Ken G." 
To: vnbang2...@yahoo.com, tutor@python.org
Subject: Re: [Tutor] Looking for duplicates within a list
Message-ID: <4c1248de.6090...@insightbb.com>
Content-Type: text/plain; charset="iso-8859-1"; Format="flowed"

vijay wrote:
> Check out this code
>  l= [1, 2, 3, 3, 4]
>  d={}
>  for item in l:
>      d.setdefaut(item,0)
>      d[item] +=1
> print d
> {1: 1, 2: 1, 3: 2, 4: 1}
>
>
> with regard's
> vijay
>
>
Thanks.  Ve

[Tutor] Linux webcam libraries?

2010-06-12 Thread Wayne Werner
Hi,

I want to do something like this:
http://www.kulturblog.com/2007/11/marshie-attacks-halloween-interactive-driveway-activity/

I want to be able to grab a webcam image via python. So I'm curious if
anyone has had any experience/luck in this particular area and/or knows of
any libraries I should take a look at. I know my webcam definitely works
under linux because I can use the cheese program and see the image...

Anyway, any information will be very welcome!

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


Re: [Tutor] Python a substitute/alternative for PhP?

2010-06-12 Thread Juan Jose Del Toro
2010/6/11 Alex Hall 

> Personally, I would learn Python. My college does not offer Python
> either, so I had to learn what I know on my own(of course, by that I
> mean constantly pestering this and other of the amazing Python email
> lists). PHP is fine in itself, but, after using it, Java, and intros
> to a few other languages, nothing has been able to beat Python's ease
> of use, massive extensibility (there is a package to let you do just
> about anything you want), and support community. It is a great
> language and, especially if you plan to stick with desktop
> applications, I think it is much easier than a language like C++ or
> Java. Your life will be even easier than mine since you are going to
> be on Linux; I believe most Linux distros come with Python, while
> Windows does not, so what you make can be distributed as scripts while
> I have to use a program like py2exe and package the entire Python
> interpreter.
> Anyway, just my thoughts. Note that I am still in college for my
> computer science degree and am in no way a professional programmer,
> just someone who has waded in several languages and found Python to be
> the only one worth diving into all the way.
>
> On 6/11/10, Eldon Londe Mello Junior  wrote:
> >
> > Hi there,
> >
> > If you care to listen to my story and fully help me out, just keep on
> > reading }else{ move to the final question :)
> >
> > I'm just finishing an introductory course on PhP and MySQL (HTML, CSS and
> > Javascript basics included). That's a typical first step to novice
> > programmers in Brazil.
> >
> > However, I've been reading a lot about programming languages and stuff in
> > order to make the best choice as I don't want to spend much time learning
> > unnecessary things I won't need in the future.
> >
> > Thus, I decided I want to be a contributor for the GNU/LINUX community
> and,
> > of course, become sort of an opensource-solutions professional
> programmer.
> > And if I got it right, python would the most adequate language for me to
> > reach my goals.
> >
> > Only a few programmers in Brazil are familiar with python though. As I
> said
> > before, most beginners start with PhP and stick with it or go for JAVA or
> MS
> > proprietary languages. Actually, you can only learn python on your own
> > around here as no college or private institutes offer python courses.
> >
> > As you may see it coming, the big question for me is: should I stick with
> > PHP as most people here (those fond of free software) or Python is or
> would
> > be a better choice for me?
> >
> > FINAL QUESTION> Is Python a substitute for PHP? I mean, can I start
> learning
> > python by trying to do the things I've learned with PHP? Are they
> different
> > anyhow or they actually compete against each other?
> >
> > Thanks in advance, advice on which steps to take to reach my career goals
> > would be very appreciated as well!
> >
> > Eldon.
> >
> >
> >
> >
> >
> >> Date: Fri, 11 Jun 2010 15:27:44 -0700
> >> From: dkuhl...@rexx.com
> >> To: Tutor@python.org
> >> Subject: Re: [Tutor] What's the catch with ZopeDB?
> >>
> >> On Fri, Jun 11, 2010 at 09:42:35PM +0200, Knacktus wrote:
> >>
> >> >
> >> > To me, ZopeDB (a object database for Python) looks like an awesomely
> >> > easy solution. I could save some brain power for the innovative part
> or
> >> > drink more beer watching the soccer world cup. At the same moment, I
> >> > wonder why anyone in the python world would go through the hassle of
> >> > using relational databases unless forced.
> >> >
> >> > So, has anyone experience with ZopeDB? Are there some drawbacks I
> should
> >> >
> >> > be aware of before getting a book and dive in? (It sounds too good
> ;-))
> >> >
> >>
> >> Jan -
> >>
> >> If you are evaluating alternative solutions, you might also look
> >> into Django models.  There have been some very positive comments
> >> about Django on this list.  And, Django models can be used outside
> >> of the Django Web applications.  Also, Django models are reasonably
> >> object oriented.  A Django model/DB can sit on top of several
> >> different relational database engines, for example, PostgreSQL, MySQL,
> >> sqlite3, etc.
> >>
> >> See:
> >>
> >> http://docs.djangoproject.com/en/1.2/#the-model-layer
> >> http://www.djangobook.com/en/2.0/chapter05/
> >>
> >> - Dave
> >>
> >> --
> >> Dave Kuhlman
> >> http://www.rexx.com/~dkuhlman 
> >> ___
> >> Tutor maillist  -  Tutor@python.org
> >> To unsubscribe or change subscription options:
> >> http://mail.python.org/mailman/listinfo/tutor
> >
> > _
> > Your E-mail and More On-the-Go. Get Windows Live Hotmail Free.
> > https://signup.live.com/signup.aspx?id=60969
>
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehg...@gmail.com; http://www.facebook.com/mehgcap
> ___
> Tutor m

Re: [Tutor] Better construct? (was no subject)

2010-06-12 Thread bob gailer

On 6/11/2010 5:12 PM, Advertising Department wrote:

Please supply a meaningful subject.


#!/Library/Frameworks/Python.framework/Versions/Current/bin/pythonw
"""still thinking in imperative"
"""

## obviously this is a bad construct.



Why is it "obvious"?

What is "this"? Are you referring to the function, to the mainline 
program, or what?



## Can someone suggest a pythonesque way of doing this?


def getid():
response  = raw_input('prompt')
if response not in [ "", "y", "Y", "yes"] :
getid()# ouch
print "continue working"
# do more stuff
# do more stuff


getid()
dosomething()
getid()
dosomethingelse()


## obviously this is a bad construct.
## Can someone give me a pythonesque way of doing this?


One improvement - response.lower().startswith("yes") will cover all your 
cases.


You can collect functions in a sequence, then iterate over it. This 
allows for easy expansion (when you decide to add another function).


funcs = (dosomething(), dosomethingelse())
for func in funcs:
  getid()
  func()

--
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] winsound.Beep(500,500) "Failed to beep"

2010-06-12 Thread Alex Hall
Not that it helps much, but using win7x64 and Python 2.6 it works as
expected. Possibly your sound card? Update drivers?

On 6/12/10, Richard D. Moores  wrote:
 import winsound
 winsound.Beep(500,500)
> Traceback (most recent call last):
>   File "", line 1, in 
> RuntimeError: Failed to beep

>
> Vista, Python 3.1
>
> Any ideas?
>
> Dick Moores
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for duplicates within a list

2010-06-12 Thread Peter Otten
Ken G. wrote:

> I have been working on this problem for several days and I am not making
> any progress.  I have a group of 18 number, in ascending order, within a
> list.  They ranged from 1 to 39.  Some numbers are duplicated as much as
> three times or as few as none.
> 
> I started with one list containing the numbers.  For example, they are
> listed as like below:
> 
> a = [1, 2, 3, 3, 4]
> 
> I started off with using a loop:
> 
> for j in range (0, 5):
> x = a[0] # for example, 1
> 
> How would I compare '1' with 2, 3, 3, 4?
> 
> Do I need another duplicated list such as b = a and compare a[0] with
> either b[0], b[1], b[2], b[3], b[4]?
> 
> Or do I compare a[0] with a[1], a[2], a[3], a[4]?
> 
> In any event, if a number is listed more than once, I would like to know
> how many times, such as 2 or 3 times.  For example, '3' is listed twice
> within a list.

I haven't seen a solution that takes advantage of the fact that the numbers 
are sorted, so here's one:

>>> items = [1, 2, 3, 3, 4]
>>> value = items[0]   
>>> n = 0
>>> result = []
>>> for item in items:
... if value != item:
... print value, "-->", n
... value = item
... n = 1   
... else:   
... n += 1  
... 
1 --> 1 
2 --> 1
3 --> 2
>>> print value, "-->", n
4 --> 1

Python has a cool feature called generator that allows you to encapsulate 
the above nicely:

>>> def count_runs(items):
... it = iter(items)
... value = next(it)
... n = 1 # next consumes one item
... for item in it: # the for loop starts with the second item
... if value != item:
... yield value, n
... value = item
... n = 1
... else:
... n += 1
... yield value, n
...
>>> for v, n in count_runs([1, 1, 1, 2, 2, 3, 4, 4, 4, 4]):
... print v, "-->", n
...
1 --> 3
2 --> 2
3 --> 1
4 --> 4

Finally, there is itertools.groupby() which allows you to simplify the 
implementation count_runs():

>>> from itertools import groupby
>>> def count_runs2(items):
... for key, group in groupby(items):
... yield key, sum(1 for _ in group)
...
>>> for v, n in count_runs2([1, 1, 1, 2, 2, 3, 4, 4, 4, 4]):
... print v, "-->", n
...
1 --> 3
2 --> 2
3 --> 1
4 --> 4

Peter


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


[Tutor] Adding line numbers to a Python Script

2010-06-12 Thread Sudip Bhattacharya
I quote this example (and the problem that I am facing trying to understand)
from the book "Beginning Python - From Novice to Professional" by Magnus Lie
Hetland

Page 227

# numberlines.py
import fileinput(1)

for line in fileinput.input(inplace = true)(2)
   line = line.rstrip()(3)
   num=fileinput.lineno()..(4)
   print '%-40s #%2i' %(line,num).(5)


Question: Please help me understand:

Line (3) - Are we stripping the entire line of code first, inserting the
code at the end (line (5)) and then placing it back at the same place ?

Line (5) - What does the individual characters in the expression "Print
'%-40s #%2i' %(line,num)" mean ?

 - '-40s' : is this the space [what does "-40s" mean] that we are
creating post - which the line nos is inserted "#%2i" ?
 - What does '%2" mean ? - Is that 2 cursor spaces of width ?

Much thanks in advance...
-- 
Thanks and regards,
Sudip Bhattacharya

Mobile: +91  100 706
Home Land line: +91 11 22237561
Office Land line: +91 0124 4321078
eMail ID: sud...@sudipb.com; sud...@gmail.com

Please visit my website at: www.sudipb.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New to Programming

2010-06-12 Thread Dave Angel

Kaushal Shriyan wrote:

Hi,

I am absolutely new to programming language. Dont have any programming
experience. Can some one guide me please. is python a good start for
novice.

Thanks,

Kaushal

  

Like nearly all questions, the answer is "it depends."

Mainly, it depends on what your goal is.  In my case, I made my living 
with programming, for many years.  And in the process, learned and used 
about 35 languages, plus a few more for fun.  I wish I had discovered 
Python much earlier, though it couldn't have been my first, since it 
wasn't around.  But it'd have been much better than Fortran was, for 
learning.


So tell us about your goals.  Abstract knowledge, console utilities, gui 
development, games, web development, networking communication, ...


Next, you might want to evaluate what you already know.  There are a lot 
of non-programming things that a programmer needs to understand.  If you 
already know many of them, that's a big head start.  If you already know 
how to administer a Linux system, you're already a programmer and didn't 
know it.  If you write complex formulas for Excel, you're a programmer.  
If you already know modus ponens, and understand what a contrapositive 
is, you've got a head start towards logic (neither is a programming 
subject, just a start towards logical thinking).  If you've worked on a 
large document, and kept backups of  incremental versions, so you could 
rework the current version based on earlier ones, that's a plus.  If you 
know why a file's timestamp might change when you copy it from hard disk 
to a USB drive and back again, you've got a head start.  If you know why 
it might have a different timestamp when you look at it six months from 
now without changing it, you've got a head start.


If you're using Windows and never used a command prompt, you have a ways 
to go.  If you don't know what a file really is, or how directories are 
organized, you have a ways to go.  And if you think a computer is 
intelligent, you have a long way to go.


Python is a powerful tool.  But if you're totally new to programming, it 
can also be daunting.  And most people have no idea how easy some 
programs are, nor how hard some other programs are, to build.


In any case, some of the things recommending Python as a first language are:
  1) an interactive interpreter - you can experiment, trivially
  2) very fast turnaround, from the time you make a change, till you 
can see how it works.  This can be true even for large programs

  3) this mailing list

DaveA

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


[Tutor] New to Programming

2010-06-12 Thread Kaushal Shriyan
Hi,

I am absolutely new to programming language. Dont have any programming
experience. Can some one guide me please. is python a good start for
novice.

Thanks,

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


Re: [Tutor] (no subject)

2010-06-12 Thread Jose Amoreira
On Friday, June 11, 2010 10:12:27 pm Advertising Department wrote:
> #!/Library/Frameworks/Python.framework/Versions/Current/bin/pythonw
> """still thinking in imperative"
> """
> 
> ## obviously this is a bad construct.
> ## Can someone suggest a pythonesque way of doing this?
> 
> 
> def getid():
>   response  = raw_input('prompt')
>   if response not in [ "", "y", "Y", "yes"] :
>   getid() # ouch
>   print "continue working"
>   # do more stuff
>   # do more stuff
> 
> 
> getid()
> dosomething()
> getid()
> dosomethingelse()
> 
> 
> ## obviously this is a bad construct.
> ## Can someone give me a pythonesque way of doing this?
> 
Using recursion for validation, that doesn't sound right. I would rather do it 
with a simple while cycle:

response="any invalid string"
while response not in ["","y","Y","yes"]:
response = raw_input("prompt")

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


[Tutor] winsound.Beep(500,500) "Failed to beep"

2010-06-12 Thread Richard D. Moores
>>> import winsound
>>> winsound.Beep(500,500)
Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: Failed to beep
>>>

Vista, Python 3.1

Any ideas?

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


[Tutor] (no subject)

2010-06-12 Thread Advertising Department

#!/Library/Frameworks/Python.framework/Versions/Current/bin/pythonw
"""still thinking in imperative"
"""

## obviously this is a bad construct.
## Can someone suggest a pythonesque way of doing this?


def getid():
response  = raw_input('prompt')
if response not in [ "", "y", "Y", "yes"] :
getid() # ouch
print "continue working"
# do more stuff
# do more stuff


getid()
dosomething()
getid()
dosomethingelse()


## obviously this is a bad construct.
## Can someone give me a pythonesque way of doing this?

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


[Tutor] lib2to3 fixers

2010-06-12 Thread Zubin Mithra
Hey everyone,

I just discovered that the following construct does not work in Py3k.

>>> string.maketrans('-', '_')

However, the following works,

>>> str.maketrans('-', '_')

When i try to convert a python module containing the above construct,
it does not get modified in a way such that it could run on Python 3.0

I`m trying to automate the conversion of making the module Py3k
compatible and so I guess i`m left with two options.

1. replace string.maketrans() with a function which is compatible in
both Python 2.x and 3.0 ; as of now I`m unaware of such a construct.

2. write a fixer for doing this which I could use. I could`nt find any
good tutorials out there on writing fixers, i`d be grateful if you
could point me to any.

Thankx in advance,
cheers
zubin
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problems with Importing into the Python Shell

2010-06-12 Thread Steven D'Aprano
On Sat, 12 Jun 2010 02:50:26 pm Andrew Martin wrote:

> >>> from chap03 import *
>
> Traceback (most recent call last):
>   File "", line 1, in 
> from chap03 import *
>   File "C:/Python26\chap03.py", line 2
> print param param
> ^
> SyntaxError: invalid syntax

This tells you exactly what the error is: a syntax error in your module 
chap03, which prevents Python from importing it.

`print a b` is not valid Python syntax. Python can't correct the error, 
because it doesn't know if you mean print param+param, or param,param 
or "param param" or something else, and it refuses to guess.


> The chap03.py file is a simple one that looks like this:
> def print_twice(param):
> print param param

The print statement takes a comma-separated list of things to print:

print param, param



> My second problem is that I need to install and import GASP in order
> to follow the tutorial. When I tried to do import it, I ran into an
> error like
>
> this:
> >>> from gasp import *
>
> Traceback (most recent call last):
>   File "", line 1, in 
> from gasp import *
>   File "C:\Python26\lib\site-packages\gasp\__init__.py", line 1, in
>  from api import *
>   File "C:\Python26\lib\site-packages\gasp\api.py", line 1, in
>  import backend
>   File "C:\Python26\lib\site-packages\gasp\backend.py", line 7, in
>  except ImportError: raise 'Pygame is not installed. Please
> install it.' TypeError: exceptions must be old-style classes or
> derived from BaseException, not str

Here you have two problems. The first problem is that you need to have 
Pygame installed, and you don't, or it is installed in such a place 
that Python 2.6 can't see it.

The second is that the version of gasp you are using has a bug in it, 
possibly because you're using an old version. In the very early days of 
Python, it used string exceptions: to raise an error message, you would 
say:

raise "this is an error message"

For various reasons, this was not very satisfactory, and over the years 
these string exceptions were discouraged, then flagged as officially 
deprecated, then Python would print an warning message when you used 
them, and finally in Python 2.6 they because prohibited:

>>> raise "this is an error"
Traceback (most recent call last):
  File "", line 1, in 
TypeError: exceptions must be classes or instances, not str


So the version of gasp you are using pre-dates Python 2.6, and contains 
obsolete code that does not run correctly. Your work-arounds, in order 
of best-to-worst ideas:

(1) Install an updated version of gasp that works with Python 2.6;
(2) Install Python 2.5 and use that; or
(3) Hack your copy of gasp to fix the bug.

Of course, since you're a beginner, option 3 (not very desirable at the 
best of times!) is virtually impossible. Good luck!

However, there is one little ray of sunshine. If you install Pygame, 
gasp should successfully import it and therefore not try to raise a 
string exception, and the second error will disappear all on its own. 
(But who knows how many more little landmines are waiting...)



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


Re: [Tutor] Problems with Importing into the Python Shell

2010-06-12 Thread Mark Lawrence

On 12/06/2010 05:50, Andrew Martin wrote:

Hey, everyone, I am new to programming and just downloaded Python 2.6 onto
my windows vista laptop. I am attempting to follow 4.11 of the tutorial
called "How to Think Like a Computer Scientist: Learning with Python v2nd
Edition documentation" (
http://openbookproject.net/thinkcs/python/english2e/ch04.html). However, I
am having some trouble. First off, I do not understand how to import things
into the python shell. I have a script I saved as chap03.py, but when I try
to import it into the python shell i get an error like this:


from chap03 import *


This is generally considered bad practice, I'll let you do some research 
to find out why. :)




Traceback (most recent call last):
   File "", line 1, in
 from chap03 import *
   File "C:/Python26\chap03.py", line 2
 print param param
 ^
SyntaxError: invalid syntax




The chap03.py file is a simple one that looks like this:
def print_twice(param):
 print param param


One of the great advantages of Python is trying things from an 
interactive prompt, so let's go.


c:\Users\Mark\python>python
Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> def print_twice(param):
... print param param
  File "", line 2
print param param
^
SyntaxError: invalid syntax

So it is!  What's print_twice trying to do, let's guess?

>>> def print_twice(param):
... print param, param
...
>>> print_twice('Hi Andrew')
Hi Andrew Hi Andrew
>>>

Better!  See how I slotted that comma into the function print_twice, 
just hope my guess is right.  So run up some editor/IDE and slap that 
comma in there, it should at least keep you going.




My second problem is that I need to install and import GASP in order to
follow the tutorial. When I tried to do import it, I ran into an error like
this:

from gasp import *


Traceback (most recent call last):

The line above basically says "start reading from the bottom up"

   File "", line 1, in
 from gasp import *
   File "C:\Python26\lib\site-packages\gasp\__init__.py", line 1, in
 from api import *
   File "C:\Python26\lib\site-packages\gasp\api.py", line 1, in
 import backend
   File "C:\Python26\lib\site-packages\gasp\backend.py", line 7, in
 except ImportError: raise 'Pygame is not installed. Please install it.'
TypeError: exceptions must be old-style classes or derived from
BaseException, not str
The TypeError means exactly what it says.  The ImportError is trying to 
raise an exception, but what follows is a string type, not an exception 
type.  Just install Pygame to get yourself going, at some point in the 
tutorial you're bound to run into exception handling.




Can anybody help me with this?

Thanks a lot

P.S. SORRY FOR THE LONG EMAIL


By some standards this doesn't even qualify as short, it's just a snippet.


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


HTH, and keep asking as Python lists are renowned for their friendlyness.

Mark Lawrence.


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