[Tutor] Why subclassing exceptions?

2011-09-27 Thread Mac Ryan
On Wed, 28 Sep 2011 09:58:49 +1000
Steven D'Aprano  wrote:

> Mac Ryan wrote:
> 
> > raise BaseException('Something is wrong here!')  
> 
> Never raise BaseException directly! BaseException is the very top of
> the exception hierarchy, you should raise the *most* specific
> exception you can, not the least specific. BaseException isn't even
> just for errors, it's also for flow control exceptions like
> StopIteration .

Fair enough! :) I just put that line to signal that there were cases
that weren't catch by the series of ``if``, but nevertheless you are
right.

**I would like to know more on the rationale behind this
guidelines, though.**

I explain: I already knew before that I should
subclass exceptions, nevertheless I very seldom do, as I feel like they
are just taking space on my screen doing nothing useful. All I need to
do is often just print out a useful message, so I find that

>>> raise StandardError('This value should be True.')

does the job in a much more elegant way than:

>>> class ShouldBeTrueError(StandardError):
... 
... '''
... Custom Error triggered in case a value should be True. 
... '''
... 
... pass
... 
>>> raise ShouldBeTrueError('Doh! An error!')

Ok, I already hear some of you screaming out loud "Anathema!!" ;) ...yet
could somebody please clarify why should I bother subclassing? [I'm
positive there is a good reason, but in all honesty I can't imagine
which one...].

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


Re: [Tutor] raw_input() slice list

2011-09-27 Thread bob gailer

On 9/27/2011 11:18 PM, questions anon wrote:

I would like to use user_input() to decide how to slice a list.
This works fine until I try to leave it blank to try and select the 
whole list [:]
I have posted the section of interest below and the error I get when I 
try to press enter. Further below that is the entire code.

Any feedback will be greatly appreciated.
*
section of code of interest:*
startperiod=int(raw_input("Start slice (e.g. 1 ): "))
endperiod=int(raw_input("End slice (e.g. 2): "))
skipperiod=int(raw_input("skip slice (e.g. 1): "))

if startperiod=="" and endperiod=="" and skipperiod=="":
startperiod=""
endperiod=""
skipperiod=""

int() expects a character representation of an integer. An empty string 
will raise the exception you reported.


startperiod will NEVER == "", as it will be an integer.

The entire if statement does nothing! Discard it.

Defer applying int().

Then you can check startperiod etc for equality to "".

if startperiod == "":
  startperiod = None
else:
  startperiod = int(startperiod)
if endperiod == "":

  endperiod = None
else:
  endperiod = int(endperiod)
if skipperiod == "":
  skipperiod = None
else:
  skipperiod= int(skipperiod)

AND BE PREPARED to catch & handle exceptions in case user enters a 
non-integer value.


for (path, dirs, files) in os.walk(MainFolder):
for dir in dirs:
print dir
path=path+'/'

for ncfile in files:
if ncfile[-3:]=='.nc':
print "dealing with ncfiles:", 
path+ncfile

ncfile=os.path.join(path,ncfile)
ncfile=Dataset(ncfile, 'r+', 
'NETCDF4')

variable=ncfile.variables[ncvariablename][:]

TIME=ncfile.variables['time'][:]

fillvalue=ncfile.variables[ncvariablename]._FillValue

ncfile.close()

for variable, TIME in 
zip((variable[startperiod:endperiod:skipperiod]),(TIME[startperiod:endperiod:skipperiod])):



*the error:*

Traceback (most recent call last):
  File "", line 1, in 
plotrawdata('TSFC')
  File "D:\My Dropbox\Python_code\functions.py", line 39, in plotrawdata
startperiod=int(raw_input("Start slice (e.g. 1 ): "))
ValueError: invalid literal for int() with base 10: ''


*THE WHOLE PROGRAM:*
from netCDF4 import Dataset
import numpy as N
import matplotlib.pyplot as plt
from numpy import ma as MA
from mpl_toolkits.basemap import Basemap
from netcdftime import utime
from datetime import datetime
import os
import matplotlib.colors as mc
import matplotlib.colorbar as c

OutputFolder=r"D:/DSE_work/temp_samples2/"
MainFolder=r"D:/DSE_work/temp_samples2/"


def plotrawdata(variable):
if variable=='TSFC':
ncvariablename='T_SFC'
MainFolder=r"D:/DSE_work/temp_samples2/"
ticks=[-5,0,5,10,15,20,25,30,35,40,45,50]
Title='Surface Temperature'

elif variable=='RHSFC':
ncvariablename='RH_SFC'

MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/temp_samples6/"

ticks=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 101]
Title='Surface RH'


fileforlatlon=Dataset("D:/DSE_work/temp_samples2/2020/01/IDZ00026_VIC_ADFD_T_SFC.nc", 
'r+', 'NETCDF4')

LAT=fileforlatlon.variables['latitude'][:]
LON=fileforlatlon.variables['longitude'][:]

startperiod=int(raw_input("Start slice (e.g. 1 ): "))
endperiod=int(raw_input("End slice (e.g. 2): "))
skipperiod=int(raw_input("skip slice (e.g. 1): "))

if startperiod=="" and endperiod=="" and skipperiod=="":
startperiod=str("")
endperiod=str("")
skipperiod=str("")


for (path, dirs, files) in os.walk(MainFolder):
for dir in dirs:
print dir
path=path+'/'

for ncfile in files:
if ncfile[-3:]=='.nc':
print "dealing with ncfiles:", 
path+ncfile

ncfile=os.path.join(path,ncfile)
ncfile=Dataset(ncfile, 'r+', 
'NETCDF4')

variable=ncfile.variables[ncvariablename][:]

TIME=ncfile.variables['time'][:]

fillvalue=ncfile.variables[ncvariablename]._FillValue

ncfile.close()

for variable, TIME in 
zip((variable[startperiod:endperiod:skipperiod]),(TIME

Re: [Tutor] map one file and print it out following the sequence

2011-09-27 Thread lina
Hi,

Thanks for both of your reply.

File 1 is:

 3 C 1  CUR C19 10.200  12.0110
 4   CR1 1  CUR C20 1   -0.060  12.0110
 5HC 1  CUR H20 10.060   1.0080

File 2 is:
ATOM  2  H20 CUR 1  30.338  28.778  -6.812  1.00  0.00

ATOM  4  C20 CUR 1  31.394  28.922  -7.039  1.00
0.00
ATOM  5  C19 CUR 1  31.790  29.357  -8.323  1.00  0.00

I wish to get:

ATOM  5  C19 CUR 1  31.790  29.357  -8.323  1.00
0.00
ATOM  4  C20 CUR 1  31.394  28.922  -7.039  1.00
0.00
ATOM  2  H20 CUR 1  30.338  28.778  -6.812  1.00  0.00


The dictionary is C19 C20 H20 sequence read from file 1 field 5.
rearrange the file 2 field 3 following the sequence of C19, C20, H20.

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


[Tutor] raw_input() slice list

2011-09-27 Thread questions anon
I would like to use user_input() to decide how to slice a list.
This works fine until I try to leave it blank to try and select the whole
list [:]
I have posted the section of interest below and the error I get when I try
to press enter. Further below that is the entire code.
Any feedback will be greatly appreciated.
*
section of code of interest:*
startperiod=int(raw_input("Start slice (e.g. 1 ): "))
endperiod=int(raw_input("End slice (e.g. 2): "))
skipperiod=int(raw_input("skip slice (e.g. 1): "))

if startperiod=="" and endperiod=="" and skipperiod=="":
startperiod=""
endperiod=""
skipperiod=""


for (path, dirs, files) in os.walk(MainFolder):
for dir in dirs:
print dir
path=path+'/'

for ncfile in files:
if ncfile[-3:]=='.nc':
print "dealing with ncfiles:",
path+ncfile
ncfile=os.path.join(path,ncfile)
ncfile=Dataset(ncfile, 'r+', 'NETCDF4')

variable=ncfile.variables[ncvariablename][:]
TIME=ncfile.variables['time'][:]

fillvalue=ncfile.variables[ncvariablename]._FillValue
ncfile.close()

for variable, TIME in
zip((variable[startperiod:endperiod:skipperiod]),(TIME[startperiod:endperiod:skipperiod])):


*the error:*

Traceback (most recent call last):
  File "", line 1, in 
plotrawdata('TSFC')
  File "D:\My Dropbox\Python_code\functions.py", line 39, in plotrawdata
startperiod=int(raw_input("Start slice (e.g. 1 ): "))
ValueError: invalid literal for int() with base 10: ''


*THE WHOLE PROGRAM:*
from netCDF4 import Dataset
import numpy as N
import matplotlib.pyplot as plt
from numpy import ma as MA
from mpl_toolkits.basemap import Basemap
from netcdftime import utime
from datetime import datetime
import os
import matplotlib.colors as mc
import matplotlib.colorbar as c

OutputFolder=r"D:/DSE_work/temp_samples2/"
MainFolder=r"D:/DSE_work/temp_samples2/"


def plotrawdata(variable):
if variable=='TSFC':
ncvariablename='T_SFC'
MainFolder=r"D:/DSE_work/temp_samples2/"
ticks=[-5,0,5,10,15,20,25,30,35,40,45,50]
Title='Surface Temperature'

elif variable=='RHSFC':
ncvariablename='RH_SFC'

MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/temp_samples6/"
ticks=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 101]
Title='Surface RH'


fileforlatlon=Dataset("D:/DSE_work/temp_samples2/2020/01/IDZ00026_VIC_ADFD_T_SFC.nc",
'r+', 'NETCDF4')
LAT=fileforlatlon.variables['latitude'][:]
LON=fileforlatlon.variables['longitude'][:]

startperiod=int(raw_input("Start slice (e.g. 1 ): "))
endperiod=int(raw_input("End slice (e.g. 2): "))
skipperiod=int(raw_input("skip slice (e.g. 1): "))

if startperiod=="" and endperiod=="" and skipperiod=="":
startperiod=str("")
endperiod=str("")
skipperiod=str("")


for (path, dirs, files) in os.walk(MainFolder):
for dir in dirs:
print dir
path=path+'/'

for ncfile in files:
if ncfile[-3:]=='.nc':
print "dealing with ncfiles:",
path+ncfile
ncfile=os.path.join(path,ncfile)
ncfile=Dataset(ncfile, 'r+', 'NETCDF4')

variable=ncfile.variables[ncvariablename][:]
TIME=ncfile.variables['time'][:]

fillvalue=ncfile.variables[ncvariablename]._FillValue
ncfile.close()

for variable, TIME in
zip((variable[startperiod:endperiod:skipperiod]),(TIME[startperiod:endperiod:skipperiod])):
#for variable, TIME in
zip((variable[sliceperiod]),(TIME[sliceperiod])):

cdftime=utime('seconds since
1970-01-01 00:00:00')

ncfiletime=cdftime.num2date(TIME)
print ncfiletime
timestr=str(ncfiletime)
d = datetime.strptime(timestr,
'%Y-%m-%d %H:%M:%S')
date_string =
d.strftime('%Y%m%d_%H%M')
#Set up basemap using mercator
projection
http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html
map =
Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33,

llcrnrlon=13

Re: [Tutor] help with a recursive function

2011-09-27 Thread Alan Gauld

On 27/09/11 19:32, c smith wrote:

i understand the general idea of recursion and if I am following well
written code I can understand how it works, but when I try to write it
for myself I get a bit confused with the flow.


Others have dealt with the specifics.

If you really want to learn how to use and write recursive code there is 
(IMHO!) no better place to go than the online book How To Design 
Programs. It's written using Scheme but the code is clear enough that 
you should translate to Python easily. You probably only need to read 
the first 4 chapters or so. The author builds up a set of heuristics for 
defining recursive solutions - i.e. writing functions!


http://www.htdp.org

Enjoy,

Alan G.

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


Re: [Tutor] help with a recursive function

2011-09-27 Thread Steven D'Aprano

Mac Ryan wrote:


raise BaseException('Something is wrong here!')


Never raise BaseException directly! BaseException is the very top of the 
exception hierarchy, you should raise the *most* specific exception you 
can, not the least specific. BaseException isn't even just for errors, 
it's also for flow control exceptions like StopIteration .


At worst, you should raise StandardError, but even that is a pretty 
dodgy thing to do. In general you want something more specific, like 
ValueError or TypeError. In this particular case, the appropriate error 
would be to raise RuntimeError: if you're ever in the position of having 
to just give up and say "I have no idea what is wrong, but something is 
wrong", then RuntimeError is the one to use.



More about exceptions here:

http://docs.python.org/library/exceptions.html


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


Re: [Tutor] help with a recursive function

2011-09-27 Thread Steven D'Aprano

c smith wrote:

hi list,
i understand the general idea of recursion and if I am following well
written code I can understand how it works, but when I try to write it for
myself I get a bit confused with the flow.


Your flow is fine. You just forget to return anything in two of the 
three branches. It's one thing to *call* the recursive function, but you 
have to do something with the result, normally return it. Otherwise 
Python just throws the result away and then returns None, exactly the 
same as this non-recursive function:


def add_one(x):
"""Return x + 1"""
y = x + 1


You need a return statement.

Further comments below:



I was trying to turn an ackerman function into python code for practice and
I tried writing it like this:
#!/usr/bin/env python

import sys, os
def ack(m,n):

if m == 0:
return n+1
elif m > 0 and n == 0:
ack(m-1,1)
elif m > 0 and n > 0:
ack(m-1,ack(m,n-1))

if __name__=='__main__':
sys.argv[1] = int(sys.argv[1])
sys.argv[2] = int(sys.argv[2])

print ack(sys.argv[1], sys.argv[2])

The major problem, I think, is that I cant figure out where to turn the args
into ints.


(1) That has nothing to do with recursion.

(2) Your guess as to the problem is wrong. You are successfully turning 
the args into ints.


(3) In my opinion, it is bad form to write back to sys.argv like that. 
You should say something like this:


m = int(sys.argv[1])
n = int(sys.argv[2])
print ack(m, n)


although what you haven't done is strictly *wrong*, it is a bit strange.




When run in this form I get the 'typeError' error on 'n+1' I guess because
the args are still strings.


Rather than guess, you should read the error message and pay attention 
to what it actually says. When I run your code, I get:


TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'


But if I try to add 1 to a string, I get a very different error message:

>>> '2' + 1
Traceback (most recent call last):
  File "", line 1, in 
TypeError: cannot concatenate 'str' and 'int' objects


So the problem is *not* that n is still a string, the problem is that n 
is NoneType, that is, n = None. Why is n None? Because this branch of 
the function:


ack(m-1,ack(m,n-1))

calls ack with m=m-1 and n=ack(m, n-1) but ack(...) returns None in two 
out of the three branches. Hence n gets set to None.



If you want to understand recursion, you are probably better off 
starting with simpler examples: start by writing your own recursive 
factorial function, then Fibonacci, and once you understand them, then 
try Ackerman.




--
Steven

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


Re: [Tutor] My code works but it is a little bit broken.

2011-09-27 Thread brandon w
That was my problem. I had the "insert" function. I don't know why I did not
see that before or why I even put that in there.
Thank you for your help once again.

On Tue, Sep 27, 2011 at 6:43 AM, Alan Gauld wrote:

> On 27/09/11 02:32, brandon w wrote:
>
>> The fields take the initial value and multiply it to get the amount.
>> The problem in in the callback function. It uses the  event to
>> clear a field, but when the mouse enters a second time it adds a numeric
>> value. This is a semantic error. It is not doing what I want it to do.
>>
>
> Here is the callback function:
>
>
> def callback(event):
>field0 = varText1.get()
>initAmount.delete(0, END)
>initAmount.insert(0, field0)
>return
>
> It quite clearly does an insert. If you don't want the insert remove it?
> I still don't think I understand what your problem is? You read the field
> and insert it, presumably you did that for a reason, so why are you
> surprised when it works as you designed it to work?
>
>
>
> --
> Alan G
> 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
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] map one file and print it out following the sequence

2011-09-27 Thread Prasad, Ramit
>I have file 1: cur.itp
>
> 1   CH3 1  CUR  C1 1    0.066  15.0350   
> 2    OA 1  CUR  O1 1   -0.183  15.9994   
> 3 C 1  CUR  C2 1    0.126  12.0110   

>and file 2: procesed.pdb
>ATOM  1  H52 CUR 1  33.502  30.958  -9.831 -0.71 -0.23   
>H  
>ATOM  2  H32 CUR 1  34.440  28.421  -3.916  0.00  0.09   H 

>Now I wish the file 2 filed 3 output as the order of the file 1 field 2,
>namely will be,

>ATOM 10  C21 CUR 1  30.599  28.677 -10.410 -0.06 -0.05   
>C  
>ATOM 11  O4  CUR 1  30.948  29.625  -9.382 -0.04  0.04   O 

>mapping={}
>for line in open("cur.itp").readlines():

I would also suggest changing the line above to the following lines below. 
with open("cur.itp") as f:
for line in f.readlines():
# do task here.

I would do this as it will close the file automatically (starting with Python 
2.6?). Not a big deal in this sample program, but I think this is considered a 
good practice (I am sure people will correct me if I am wrong).

>    parts=line.strip().split()
>    if len(parts)==8:
>   mapping[parts[4]]=parts[0]

This will create a dictionary of where the key is C2 or O1 or C1 and the value 
is the line number (or what I assume to be the line number). 

>origs=open("processedpdb").read().split()
>print " ".join([mapping[orig] for orig in origs])
>
> the last sentence I even don't know what I am doing. sorry.

I can help with that.
" " is a string and the join function takes an iterable (like an array or set) 
and then creates one string with all the elements of the iterable in it but 
separated by a space.  You can use any string for the separator even 
multi-character ones. 
>>> print " ".join( [ 'blah' , 'hum', 'bug' , 'see' ] )
blah hum bug see
>>> print ",".join( [ 'blah' , 'hum', 'bug' , 'see' ] )
blah,hum,bug,see
>>> print ", ".join( [ 'blah' , 'hum', 'bug' , 'see' ] )
blah, hum, bug, see
>>> print "a_-_a".join( [ 'blah' , 'hum', 'bug' , 'see' ] )
blaha_-_ahuma_-_abuga_-_asee


In your situation this will probably print nothing (actually it should raise a 
KeyError).

>origs=open("processedpdb").read().split()
>print " ".join([mapping[orig] for orig in origs])

The reason I do not think this will print anything is because you are searching 
for the incorrect information in the mapping dictionary. First it will read the 
entire file and then split the file by lines. So origs will be a list of lines.

[mapping[orig] for orig in origs]
If done correctly this will generate a list with the results of mapping[orig]. 
The problem is that you are looking for a key that is "ATOM  1  H52 CUR 
1  33.502  30.958  -9.831 -0.71 -0.23   H" but all the keys are in 
the format "C1" or "C2" or "O1" as mentioned before. Accessing the dictionary 
in this manner will raise a key error when trying to access a value for which 
there is no key.
>>> d = {}
>>> d['blayh']

KeyError: 'blayh'


> namely rearrange it.

I am not sure what you are trying to do. It would help a lot if you could 
explain a bit more detail about what you are trying to accomplish. From what I 
see your output looks to be the same as your file2. Without knowing exactly 
what you are trying to achieve I cannot really help to fix this, except for 
pointing out some of the mistakes.


Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with a recursive function

2011-09-27 Thread Mac Ryan
On Tue, 27 Sep 2011 14:32:00 -0400
c smith  wrote:

> hi list,
> i understand the general idea of recursion and if I am following well
> written code I can understand how it works, but when I try to write
> it for myself I get a bit confused with the flow.
> I was trying to turn an ackerman function into python code for
> practice and I tried writing it like this:
> #!/usr/bin/env python
> 
> import sys, os
> def ack(m,n):
> 
> if m == 0:
> return n+1
> elif m > 0 and n == 0:
> ack(m-1,1)
> elif m > 0 and n > 0:
> ack(m-1,ack(m,n-1))
> 
> if __name__=='__main__':
> sys.argv[1] = int(sys.argv[1])
> sys.argv[2] = int(sys.argv[2])
> 
> print ack(sys.argv[1], sys.argv[2])
> 
> The major problem, I think, is that I cant figure out where to turn
> the args into ints.

You did it right, just when you loaded them. What is not correct is to
try to assign them to a property inside a standard library module. You
should assign them to local variables (``m`` and ``n`` for example).

> Also, does the second 'elif' make sense?

I have am not familiar with the ackerman functions, but since you
mentioned recursion, I suppose you wanted to recurse in those elif`s
and return the result of a new call to the funtion.

If that is the case, you could happily skip the "else" part of "elif"
because if the ``if`` code will run, the interpreter will never reach
the ``elif`` line.

> I am not sure if the function can take itself as an argument.
> thanks for any suggestions, this list has been a big help.

Here's the code readapted (but verify it still does what is intended
to!):

#!/usr/bin/env python

import sys, os
def ack(m,n):

if m == 0:
return n+1
if m > 0:
if n == 0:
return ack(m-1,1)
if n > 0:
return ack(m-1,ack(m,n-1))
raise BaseException('Something is wrong here!')

if __name__=='__main__':
m = int(sys.argv[1])
n = int(sys.argv[2])
print ack(m, n)


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


Re: [Tutor] map one file and print it out following the sequence

2011-09-27 Thread Alan Gauld

On 27/09/11 14:45, lina wrote:

Hi,

I have file 1: cur.itp

  1   CH3 1  CUR  C1 10.066  15.0350
  2OA 1  CUR  O1 1   -0.183  15.9994
  3 C 1  CUR  C2 10.126  12.0110

and file 2: procesed.pdb

ATOM  1  H52 CUR 1  33.502  30.958  -9.831 -0.71
-0.23   H
ATOM  2  H32 CUR 1  34.440  28.421  -3.916  0.00
0.09   H
ATOM  3  H22 CUR 1  31.110  22.839   1.886 -0.18
0.12   H



While it's good to show us sample data please keep it to the minimum 
needed to illustrate the point.




Now I wish the file 2 filed 3 output as the order of the file 1 field 2,
namely will be,
ATOM 10  C21 CUR 1  30.599  28.677 -10.410 -0.06
-0.05   C
ATOM 11  O4  CUR 1  30.948  29.625  -9.382 -0.04
0.04   O


Sorry, I have no idea what you mean by that.
Can you explain again in more detail please?



hope someone can give me some advice,


We probably can once we understand what you are trying to do.
Or maybe its just me being slow...


origs=open("processedpdb").read().split()
print " ".join([mapping[orig] for orig in origs])

the last sentence I even don't know what I am doing. sorry.


That makes two of us!

--
Alan G
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


[Tutor] help with a recursive function

2011-09-27 Thread c smith
hi list,
i understand the general idea of recursion and if I am following well
written code I can understand how it works, but when I try to write it for
myself I get a bit confused with the flow.
I was trying to turn an ackerman function into python code for practice and
I tried writing it like this:
#!/usr/bin/env python

import sys, os
def ack(m,n):

if m == 0:
return n+1
elif m > 0 and n == 0:
ack(m-1,1)
elif m > 0 and n > 0:
ack(m-1,ack(m,n-1))

if __name__=='__main__':
sys.argv[1] = int(sys.argv[1])
sys.argv[2] = int(sys.argv[2])

print ack(sys.argv[1], sys.argv[2])

The major problem, I think, is that I cant figure out where to turn the args
into ints.
When run in this form I get the 'typeError' error on 'n+1' I guess because
the args are still strings.
Also, does the second 'elif' make sense?
I am not sure if the function can take itself as an argument.
thanks for any suggestions, this list has been a big help.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How Python handles data (was guess-my-number programme)

2011-09-27 Thread Steven D'Aprano

Wayne Werner wrote:


When you do something like this in C:

int x = 0;
int y = 0;

What you have actually done behind the scenes is allocated two bytes of
memory(IIRC that's in the C spec, but I'm not 100% sure that it's guaranteed
to be two bytes). Perhaps they are near each other, say at addresses
0xab0fcd and 0xab0fce. And in each of these locations the value of 0 is
stored.


The amount of memory will depend on the type of the variable. In C, you 
have to declare what type the variable will be. The compiler then knows 
how much space to allocate for it.




When you create a variable, memory is allocated, and you refer to that
location by the variable name, and that variable name always references that
address, at least until it goes out of scope. So if you did something like
this:

x = 4;
y = x;

Then x and y contain the same value, but they don't point to the same
address.


Correct, at least for languages like C or Pascal that have the "memory 
location" model for variables.




In Python, things are a little bit more ambiguous because everything is an
object.  So if you do this:


No. There is nothing ambiguous about it, it is merely different from C. 
The rules are completely straightforward and defined exactly.


Also, the fact that Python is object oriented is irrelevant to this 
question. You could have objects stored and referenced at memory 
locations, like in C, if the language designer wanted it that way.




x = 4
y = x

Then it's /possible/ (not guaranteed) that y and x point to the same memory
location. You can test this out by using the 'is' operator, which tells you
if the variables reference the same object:


The second half of your sentence is correct, you can test it with the 
'is' operator. But the first half is wrong: given the two assignments 
shown, x=4 and y=x, it *is* guaranteed that x and y will both reference 
the same object. That is a language promise made by Python: assignment 
never makes a copy. So if you have


x = 4

and then you do

y = x

the language *promises* that x and y now are names for the same object. 
That is, "x is y" will return True, or id(x) == id(y).



However, what is not promised is the behaviour of this:

x = 4
y = 4

In this case, you are doing two separate assignments where the right 
hand side is given by a literal which merely happens to be the same. The 
compiler is free to either create two separate objects, both with value 
4, or just one. In CPython's case, it reuses some small numbers, but not 
larger ones:


>>> x = 4
>>> y = 4
>>> x is y
True
>>> x = 4
>>> y = 4
>>> x is y
False


CPython caches the first 100 integers, I believe, although that will 
depend on exactly which version of CPython you are using.


The reason for caching small integers is that it is faster to look them 
up in the cache than to create a new object each time; but the reason 
for only caching a handful of them is that the cache uses memory, and 
you wouldn't want billions of integers being saved for a rainy day.




x = 4
y = x
x is y

True

But this is not guaranteed behavior - this particular time, python happened
to cache the value 4 and set x and y to both reference that location.


As I've said, this is guaranteed behaviour, but furthermore, you 
shouldn't think about objects ("variables") in Python having locations. 
Of course, in reality they do, since it would be impossible -- or at 
least amazingly difficult -- to design a programming language without 
the concept of memory location. But as far as *Python* is concerned, 
rather than the underlying engine that makes Python go, variables don't 
have locations in an meaningful sense.


Think of objects in Python as floating in space, rather than lined up in 
nice rows with memory addresses. From Python code, you can't tell what 
address an object is at, and if you can, you can't do anything with the 
knowledge.


Some implementations, such as CPython, expose the address of an object 
as the id(). But you can't do anything with it, it's just a number. And 
other implementations, such as Jython and IronPython, don't do that. 
Every object gets a unique number, starting from 1 and counting up. If 
an object is deleted, the id doesn't get reused in Jython and IronPython 
(unlike CPython).


Unlike the C "memory address" model, Python's model is of "name 
binding". Every object can have zero, one, or more names:


print []  # Here, the list has no name.
x = []  # Here, the list has a single name, "x"
x = y = []  # Here, the list has two names, "x" and "y".

In practice, Python uses a dictionary to map names to objects. That 
dictionary is exposed to the user using the function globals().


The main differences between "memory location" variables and "name 
binding" variables are:



(1) Memory locations are known by the compiler at compile-time, but only 
at run-time for name binding languages. In C-like languages, if I say:


x = 42
print x

the compiler knows to store 42 into location 123456 (say), a

[Tutor] map one file and print it out following the sequence

2011-09-27 Thread lina
Hi,

I have file 1: cur.itp

 1   CH3 1  CUR  C1 10.066  15.0350
 2OA 1  CUR  O1 1   -0.183  15.9994
 3 C 1  CUR  C2 10.126  12.0110
 4   CR1 1  CUR  C3 1   -0.020  12.0110
 5HC 1  CUR H31 10.011   1.0080
 6 C 1  CUR  C7 20.137  12.0110
 7OA 1  CUR  O2 2   -0.175  15.9994
 8 H 1  CUR H22 20.038   1.0080
 9   CR1 1  CUR  C6 3   -0.025  12.0110
10HC 1  CUR H61 30.009   1.0080
11   CR1 1  CUR  C5 3   -0.025  12.0110
12HC 1  CUR H51 30.009   1.0080
13 C 1  CUR  C4 3   -0.041  12.0110
14 C 1  CUR  C8 3   -0.012  13.0190
15 C 1  CUR  C9 3   -0.013  13.0190
16 C 1  CUR C10 30.304  12.0110
17OA 1  CUR  O6 3   -0.234  15.9994
18 H 1  CUR H62 30.028   1.0080
19 C 1  CUR C11 40.000  13.0190
20 C 1  CUR C12 50.304  12.0110
21OA 1  CUR  O3 5   -0.234  15.9994
22 H 1  CUR H32 50.028   1.0080
23 C 1  CUR C13 5   -0.012  13.0190
24 C 1  CUR C14 5   -0.012  13.0190
25 C 1  CUR C15 5   -0.041  12.0110
26   CR1 1  CUR C20 5   -0.026  12.0110
27HC 1  CUR H20 50.009   1.0080
28   CR1 1  CUR C16 5   -0.025  12.0110
29HC 1  CUR H16 50.009   1.0080
30   CR1 1  CUR C17 6   -0.018  12.0110
31HC 1  CUR H17 60.012   1.0080
32 C 1  CUR C18 60.140  12.0110
33OA 1  CUR  O5 6   -0.172  15.9994
34 H 1  CUR H52 60.038   1.0080
35 C 1  CUR C19 70.123  12.0110
36OA 1  CUR  O4 7   -0.187  15.9994
37   CH3 1  CUR C21 70.064  15.0350

and file 2: procesed.pdb

ATOM  1  H52 CUR 1  33.502  30.958  -9.831 -0.71 -0.23
H
ATOM  2  H32 CUR 1  34.440  28.421  -3.916  0.00  0.09
H
ATOM  3  H22 CUR 1  31.110  22.839   1.886 -0.18  0.12
H
ATOM  4  H51 CUR 1  29.829  27.375   1.674 -0.21 -0.00
H
ATOM  5  H31 CUR 1  33.510  26.681  -0.511 -0.27 -0.02
H
ATOM  6  H6  CUR 1  29.459  24.909   1.878 -0.23 -0.01
H
ATOM  7  H17 CUR 1  35.217  29.440  -7.832 -0.21  0.01
H
ATOM  8  H20 CUR 1  30.338  28.778  -6.812 -0.06 -0.01
H
ATOM  9  H16 CUR 1  34.487  28.652  -5.564 -0.18 -0.00
H
ATOM 10  C21 CUR 1  30.599  28.677 -10.410 -0.06 -0.05
C
ATOM 11  O4  CUR 1  30.948  29.625  -9.382 -0.04  0.04
O
ATOM 12  C19 CUR 1  31.790  29.357  -8.323 -0.10 -0.00
C
ATOM 13  C20 CUR 1  31.394  28.922  -7.039 -0.06 -0.01
C
ATOM 14  C15 CUR 1  32.371  28.675  -6.051 -0.08  0.00
C
ATOM 15  C16 CUR 1  33.744  28.855  -6.335 -0.18 -0.00
C
ATOM 16  C17 CUR 1  34.160  29.295  -7.609 -0.21  0.01
C
ATOM 17  C18 CUR 1  33.174  29.543  -8.587 -0.20  0.02
C
ATOM 18  C14 CUR 1  31.931  28.137  -4.836 -0.06  0.00
C
ATOM 19  C13 CUR 1  31.827  29.048  -3.599 -0.03 -0.01
C
ATOM 20  C12 CUR 1  33.154  29.408  -2.909 -0.04 -0.03
C
ATOM 21  O3  CUR 1  34.199  28.542  -2.995  0.00  0.09
O
ATOM 22  C11 CUR 1  33.102  30.386  -1.736 -0.14 -0.02
C
ATOM 23  C10 CUR 1  31.707  30.606  -1.152 -0.30 -0.04
C
ATOM 24  O6  CUR 1  31.139  31.683  -1.277 -0.38  0.05
O
ATOM 25  C9  CUR 1  31.046  29.377  -0.519 -0.35 -0.04
C
ATOM 26  C8  CUR 1  31.923  28.547   0.425 -0.29  0.01
C
ATOM 27  C4  CUR 1  31.681  27.171   0.558 -0.27  0.01
C
ATOM 28  C3  CUR 1  32.636  26.289   0.009 -0.27 -0.02
C
ATOM 29  C2  CUR 1  32.451  24.894   0.139 -0.24 -0.02
C
ATOM 30  C7  CUR 1  31.296  24.423   0.823 -0.22 -0.02
C
ATOM 31  C6  CUR 1  30.341  25.296   1.368 -0.23 -0.01
C
ATOM 32  C5  CUR 1  30.547  26.678   1.242 -0.21 -0.00
C
ATOM 33  O1  CUR 1  33.288  23.913  -0.343 -0.69  0.04
O
ATOM 34  C1  CUR 1  34.646  24.135  -0.767 -0.21 -0.06
C
ATOM 35  O2  CUR 1  31.119  23.072   0.955 -0.18  0.12
O
ATOM 36  O5  CUR 1  33.561  30.000  -9.813 -0.71 -0.23
O

Now I wish the file 2 filed 3 output as the order of the file 1 field 2,
namely will be,
ATOM 10  C21 CUR 1  30.599  28.677 -10.410 -0.06 -0.05
C
ATOM 11  O4  CUR 1  30.948  29.625  -9.382 -0.04  0.04
O



namely r

[Tutor] How Python handles data (was guess-my-number programme)

2011-09-27 Thread Wayne Werner
On Sat, Sep 24, 2011 at 2:58 AM, Kĩnũthia Mũchane <
kinuthia.much...@gmail.com> wrote:

> **
> On 09/23/2011 11:28 PM, Wayne Werner wrote:
>
> 
>  >>> tries = 1
> >>> tries
> 1
>
>  The variable 'tries' now contains the value 1 (In Python this is not
> technically true, but it's useful to describe it that way).
>
> Why?
>

Python is a true object-oriented language in that everything in Python is an
object. As an aside, one of the great things about Python is that you can
program using almost any paradigm and ignore the object-oreintedness. In a
language such as C, variables refer to memory locations that you store
values in.

When you do something like this in C:

int x = 0;
int y = 0;

What you have actually done behind the scenes is allocated two bytes of
memory(IIRC that's in the C spec, but I'm not 100% sure that it's guaranteed
to be two bytes). Perhaps they are near each other, say at addresses
0xab0fcd and 0xab0fce. And in each of these locations the value of 0 is
stored.
When you create a variable, memory is allocated, and you refer to that
location by the variable name, and that variable name always references that
address, at least until it goes out of scope. So if you did something like
this:

x = 4;
y = x;

Then x and y contain the same value, but they don't point to the same
address.

In Python, things are a little bit more ambiguous because everything is an
object.  So if you do this:

x = 4
y = x

Then it's /possible/ (not guaranteed) that y and x point to the same memory
location. You can test this out by using the 'is' operator, which tells you
if the variables reference the same object:

>>> x = 4
>>> y = x
>>> x is y
True

But this is not guaranteed behavior - this particular time, python happened
to cache the value 4 and set x and y to both reference that location. This
is done for optimization, both space and speed, and possibly other reasons
I'm not aware of. So instead of saying "I stored the value 4 in x and copied
that value into y", the correct statement would be "I gave the value 4 the
name of x, and then I also gave it the name of y". The biggest reason that
we use the first abstraction, storing a value in a "container" (variable),
is that this is the abstraction that you find when talking about almost any
other programming language. So whether out of habit, or simply because it
will be less confusing to folks who encounter other languages, most
Pythonistas will refer to

x = 4

as storing 4 in x.

Python uses caching for a variety of built-in types, so you can see the 'is'
phenomenon on other types as well:

>>> x = 'hi'
>>> y = x
>>> y is x
True
>>> x = 3.14
>>> y = x
>>> x is y
True
>>> x = 'This is a super long sentence'
>>> y = x
>>> x is y
True
>>> y = 'This is a super long sentence'
>>> x is y
False
>>> x == y
True
>>> x = 'hi'
>>> y = 'hi'
>>> x is y
True
>>> y += '!'
>>> x is y
False
>>> x == y
False
>>> x
'hi'
>>> y
'hi!'

One thing that is important to note is that in each of these examples, the
data types are immutable. In C++ if you have a string and you add to the end
of that string, that string is still stored in the same location. In Python
there's this magical string space that contains all the possible strings in
existence[1] and when you "modify" a string using addition, what you're
actually doing is telling the interpreter that you want to point to the
string that is the result of addition, like 'hi' + '!'. Sometimes Python
stores these as the same object, other times they're stored as different
objects. And since you can't change immutable objects in-place (e.g.
'hello'[0] = 'j' raises a TypeError, as does ('hello',)[0] = 'goodbye'),
it's just fine to use the standard "store 4 in x" abstraction.

But there are also mutable types such as lists and dictionaries that will
get you in trouble if you don't understand the difference.

Here is an example that has bitten every Python programmer who's been
programming long enough:

>>> names = ["Werner", "Lancelot", "Bedevere", "Idle", "Chapman"]
>>> def add_something(mylist):
... knights = mylist
... for x in range(len(knights)-1):
... knights[x] = "Sir " + knights[x]
... return knights
...
>>> knights = add_something(names)
>>> knights
['Sir Werner', 'Sir Lancelot', 'Sir Bedevere', 'Sir Idle', 'Chapman']
>>> names
['Sir Werner', 'Sir Lancelot', 'Sir Bedevere', 'Sir Idle', 'Chapman']

And the question is "wait, why did 'names' change??" Because we thought that
when we wrote 'knights = mylist' that we were storing a copy of mylist in
knights, just like when we ran 'y = x' we stored a copy of 4 in y. But
instead what we did was add the name "knights" to the list that was already
named by "mylist" and "names". So we can modify the list by using any of
those names.

Mostly it's nothing to worry about. You will have no problems writing
programs in Python if you don't understand the name concept when it comes to
immutable types, because the behavior ends out the same from the logic side
of things (as lo

Re: [Tutor] password loop

2011-09-27 Thread Wayne Werner
On Fri, Sep 23, 2011 at 5:56 PM, ADRIAN KELLY wrote:

>  Can anyone help me with the programme below; i hope you can see what i am
> trying to do, if i enter the wrong password the loop goes on forever and if
> i enter the right one nothing is printed...
> i am a newbieall comments welcome
>

I didn't notice anyone else mention it, but this is where the interactive
interpreter really shines, because it allows you to see immediately what the
result is:

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello"
hello
>>> print "I am your computer"
I am your computer
>>> password = 'route'
>>> enter_password = raw_input('Please enter your password: ')
Please enter your password: bob
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello"
hello
>>> print "I am your computer"
I am your computer
>>> password = 'route'
>>> enter_password = raw_input('Please enter your password: ')
Please enter your password: bob
>>>

>From your code and your variable names, it looks like you're confused as to
what the statement 'enter_password = raw_input('Enter your password')' does.
Because you use the assignment operator (the = sign), the expression on the
right (raw_input('Enter your password')) is evaluated, and then the result
of that operation is assigned to the enter_password variable.

If you use the interactive interpreter you will see that happen immediately,
and there's no confusion about exactly what is happening. Whenever I am
coding (and most Pythonistas, I suspect) I have two windows open - one
containing the code that I'm working on, and another containing an
interactive interpreter (I use IPython which is much more powerful than your
standard interpreter). This allows me to try out snippets (short pieces) of
code, to see what will happen there. It's much quicker to play around in the
interpreter and then copy my code into my actual program, than write my code
and then test to see if it does what I thought it would do.

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


Re: [Tutor] My code works but it is a little bit broken.

2011-09-27 Thread Alan Gauld

On 27/09/11 02:32, brandon w wrote:

The fields take the initial value and multiply it to get the amount.
The problem in in the callback function. It uses the  event to
clear a field, but when the mouse enters a second time it adds a numeric
value. This is a semantic error. It is not doing what I want it to do.


Here is the callback function:

def callback(event):
field0 = varText1.get()
initAmount.delete(0, END)
initAmount.insert(0, field0)
return

It quite clearly does an insert. If you don't want the insert remove it?
I still don't think I understand what your problem is? You read the 
field and insert it, presumably you did that for a reason, so why are 
you surprised when it works as you designed it to work?



--
Alan G
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