Re: [Tutor] Reading/dealing/matching with truly huge (ascii) files

2012-02-22 Thread Alan Gauld

On 22/02/12 05:44, Elaina Ann Hyde wrote:


file is enormous, has over 50,000 rows and about 20 columns.


On modern computers its not that enormous - probably around 10M?
But there are techniques for this which we can cover another time is you 
do hit files bigger than fit in memory.


I didn't go through the code in detail. but...

e = 0.01
if i != j and
   Radeg[i] = (Radeg2[j]+e) and
   Radeg[i] = (Radeg2[j]-e) and
   Decdeg[i] = (Decdeg2[j]+e) and
   Decdeg[i] = (Decdeg2[j]-e):

Using e helps tune the precision as needed.

That layout style will help you see the logic more easily.

But in Python you can tidy that up even more by rewriting it like

if i != j and
  (Radeg2[j]-e) = Radeg[i] = (Radeg2[j]+e) and
  (Decdeg2[j]-e) = Decdeg[i] = (Decdeg2[j]+e):

And you could put it in a function to further control readability of the 
main program and encapsulate the tests.


def rowsEquate(row1,row2, i, j):...

if i != j and
   rowsEquate(Radeg,Radeg2,i,j) and
   rowsEquate(Deceg, Deceg2,i,j):




fopen.write(  .join([str(k) for k in list(dat[i])])+
+ .join([str(k) for k in list(dat[j])])+\n)


I may be wrong but it looks like something wrong with the quoting there?
The last quote on the first line, after the +?


---
Now this is where I had to stop, this is way, way too long and messy.


Its not really that long or messy, but it could be tidied up a little.


did a similar approach with smaller (9000 lines each) files and it
worked but took awhile,


This might be the biggest problem, it will take a long time on big files.

Personally I would tend to tackle a problem like this using a
database and write a query to select the rows that match in one 
operation. Especially if I had to process a lot of files.


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


Re: [Tutor] Pyhton editor

2012-02-22 Thread Alan Gauld

On 22/02/12 04:00, ken brockman wrote:


Being a neophyte to Python, I was under the impression that you had to
install tkinter independently.of python.


No, its part of the standard library. On some *nix installs tk
support is not compiled in but tkinter should be there. But on Windows 
its always there.


Running it in a separate thread sounds like what this feature is doing. 
But IDLE has been doing that for the last several releases too (since v2.5?)


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


Re: [Tutor] Reading/dealing/matching with truly huge (ascii) files

2012-02-22 Thread Walter Prins
Hi Elaina,

On 22 February 2012 05:44, Elaina Ann Hyde elainah...@gmail.com wrote:
 #select the value if it is very, very, very close
     if i != j and Radeg[i] = (Radeg2[j]+0.01) and Radeg[i]

Alan's pretty much said what I was thinking, but I have an additional
question/concern:  Why do you include the i != j condition in your if
statement?   This is saying that you never want to compare entries
from the 2 files if they're on the same row number?  Is that actually
intentional and correct or not?  (It seems somehow wrong to me since
you've not said anything about it in your post, and everything else
suggests you're comparing only the data values to select your output
records...)

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


Re: [Tutor] Reading/dealing/matching with truly huge (ascii) files

2012-02-22 Thread Steven D'Aprano
On Wed, Feb 22, 2012 at 04:44:57PM +1100, Elaina Ann Hyde wrote:
 So, Python question of the day:  I have 2 files that I could normally just
 read in with asciitable, The first file is a 12 column 8000 row table that
 I have read in via asciitable and manipulated.  The second file is
 enormous, has over 50,000 rows and about 20 columns.  What I want to do is
 find the best match for (file 1 column 1 and 2) with (file 2 column 4 and
 5), return all rows that match from the huge file, join them togeather and
 save the whole mess as a file with 8000 rows (assuming the smaller table
 finds one match per row) and 32=12+20 columns.

I don't know much about asciitable, so I'm going to have to guess what 
some of your code does. I think the critical part is where you grab a 
column from each file:

Radeg=dat['ra-drad']*180./math.pi
Decdeg=dat['dec-drad']*180./math.pi
 
Radeg2=dat2['ra-drad']*180./math.pi
Decdeg2=dat2['dec-drad']*180./math.pi

and then compare them, element by element:

for i in xrange(len(Radeg)):
for j in xrange(len(Radeg2)):
#select the value if it is very, very, very close
...

The selection criteria is messy and complicated. Start by cleaning it 
up: elegant code is easier to work with. The first step is to operate on 
items in the columns directly, rather than indirectly via an index 
value.

Instead of writing your for-loops like this:

for i in xrange(len(column)):
do something with column[i]
do another thing with column[i]

Python can iterate over the values in the column directly:

for x in column:
do something with x
do another thing with x

You don't save any lines, but you gain a lot of clarity without the 
unnecessary indirection.

Disclaimer: I have never used asciitable, and it is possible that 
asciitable's column type does not support this. If not, that's pretty 
awful design! But you can rescue the situation by manually assigning to 
a variable inside the loop:

for i in xrange(len(column)):
x = column[i]
do something with x
do another thing with x


If you need the index as well, use the enumerate function:

for i, x in enumerate(column):
...

Using that form, if column = [1.1, 2.2, 3.3, ...] then (i, x) will 
take the values (0, 1.1), (1, 2.2), (2, 3.3) ... 

However, in your case, you have not one column but two. This is where 
the zip function comes to the rescue, it lines the columns up like teeth 
in a zipper:

delta = 0.01
for i, (a, b) in enumerate(zip(Radeg, Decdeg)):
for j, (c, d) in enumerate(zip(Radeg2, Decdeg2)):
if i == j: # skip an iteration -- but why
continue
if a = c+delta and a = c-delta \
and b = d+delta and b = d-delta:
 write_stuff_to_file(...)

Now we can simplify the selection criteria:


delta = 0.01
for i, (a, b) in enumerate(zip(Radeg, Decdeg)):
for j, (c, d) in enumerate(zip(Radeg2, Decdeg2)):
if i == j: # skip an iteration -- but why
continue
if c-delta = a = c+delta and d-delta = b = d+delta:
 write_stuff_to_file(...)


Already easier to read. (And also likely to be a little faster, although 
not enough to really make a difference.) Or at least, I find it easier 
to read, and I hope you do too!

You're comparing the (a,b) values from the small file (8,000 rows) with 
each of the (c,d) values from the large file (50,000 rows). You will 
have to compare 8000*5=400 million values, which isn't going to be 
fast in Python unless you can avoid some of those comparisons.

If you can assume that there will only be one match per row, then once 
you have found that match, you can skip to the next iteration of the 
outer loop by breaking out of the inner loop, and avoid 42,000+ 
comparisons per row! If you can do this, that will be a BIG saving.


delta = 0.01
for i, (a, b) in enumerate(zip(Radeg, Decdeg)):
for j, (c, d) in enumerate(zip(Radeg2, Decdeg2)):
if i == j: # skip an iteration -- but why
continue
if c-delta = a = c+delta and d-delta = b = d+delta:
 write_stuff_to_file(...)
 # there can only be one match, and we've just found it,
 # so go on with the next outer loop
 break


But I don't know if that is a safe assumption to make. That depends on 
the semantics of your data.

The next thing to look at is the write_stuff_to_file(...) placeholder, 
which I'm using to stand in for your code:

fopen.write(  .join([str(k) for k in list(dat[i])]) +   + 
 .join([str(k) for k in list(dat[j])])+\n)

and see if that can be improved, but frankly I have to go now, I'll try 
to come back to that later.

P.S. you have:

 import astropysics

Is that module really called astropysics with no H?



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


Re: [Tutor] Reading/dealing/matching with truly huge (ascii) files

2012-02-22 Thread Peter Otten
Elaina Ann Hyde wrote:

 So, Python question of the day:  I have 2 files that I could normally just
 read in with asciitable, The first file is a 12 column 8000 row table that
 I have read in via asciitable and manipulated.  The second file is
 enormous, has over 50,000 rows and about 20 columns.  What I want to do is
 find the best match for (file 1 column 1 and 2) with (file 2 column 4 and
 5), return all rows that match from the huge file, join them togeather and
 save the whole mess as a file with 8000 rows (assuming the smaller table
 finds one match per row) and 32=12+20 columns.  So my read code so far is
 as follows:
 -
 import sys
 import asciitable
 import matplotlib
 import scipy
 import numpy as np
 from numpy import *
 import math
 import pylab
 import random
 from pylab import *
 import astropysics
 import astropysics.obstools
 import astropysics.coords
 
 x=small_file
 #cannot read blank values (string!) if blank insert -999.99
 dat=asciitable.read(x,Reader=asciitable.CommentedHeader,
 fill_values=['','-999.99'])
 y=large_file
 fopen2=open('cfile2match.list','w')
 dat2=asciitable.read(y,Reader=asciitable.CommentedHeader,
 fill_values=['','-999.99'])
 #here are the 2 values for the small file
 Radeg=dat['ra-drad']*180./math.pi
 Decdeg=dat['dec-drad']*180./math.pi
 
 #here are the 2 values for the large file
 Radeg2=dat2['ra-drad']*180./math.pi
 Decdeg2=dat2['dec-drad']*180./math.pi
 
 for i in xrange(len(Radeg)):
  for j in xrange(len(Radeg2)):
 #select the value if it is very, very, very close
 if i != j and Radeg[i] = (Radeg2[j]+0.01) and
 Radeg[i]
= (Radeg2[j]-0.01) and Decdeg[i] = (Decdeg2[j]+0.01) and
 Decdeg[i] = (Decdeg2[j]-0.01):
 fopen.write(  .join([str(k) for k in
 list(dat[i])])+ + .join([str(k) for k in list(dat[j])])+\n)
 ---
 Now this is where I had to stop, this is way, way too long and messy.  I
 did a similar approach with smaller (9000 lines each) files and it worked
 but took awhile, the problem here is I am going to have to play with the
 match range to return the best result and give only one (1!) match per row
 for my smaller file, i.e. row 1 of small file must match only 1 row of
 large file. then I just need to return them both.  However, it isn't
 clear to me that this is the best way forward.  I have been changing the
 xrange to low values to play with the matching, but I would appreciate any
 ideas.  Thanks

If you calculate the distance instead of checking if it's under a certain 
threshold you are guaranteed to get (one of the) best matches.
Pseudo-code:

from functools import partial
big_rows = read_big_file_into_memory()

def distance(small_row, big_row):
...

for small_row in read_small_file():
best_match = min(big_rows, key=partial(dist, small_row))
write_to_result_file(best_match)


As to the actual implementation of the distance() function, I don't 
understand your problem description (two columns in the first, three in the 
second, how does that work), but generally 

a, c = extract_columns_from_small_row(small_row)
b, d = extract_columns_from_big_row(big_row)
if (a = b + eps) and (c = d + eps):
   # it's good

would typically become

distance(small_row, big_row):
a, c = extract_columns_from_small_row(small_row)
b, d = extract_columns_from_big_row(big_row)
x = a-b
y = c-d
return math.sqrt(x*x+y*y)


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


[Tutor] return integer from function

2012-02-22 Thread David Craig

Hi,
I have a function that calculates the distance between two points on a 
sphere. It works but I cant get it to return a float for use in another 
script. Anyone know how I do that??


The function is below,
Thanks,
D

import math
def distance_on_unit_sphere(lat1, long1, lat2, long2):

# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0

# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians

# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians

# Compute spherical distance from spherical coordinates.

# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
#sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length

cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
   math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
type(arc)
arc = arc*6378.1
#print str(arc*6378.1)+' km'
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] return integer from function

2012-02-22 Thread Brian van den Broek
On 22 February 2012 12:57, David Craig dcdavem...@gmail.com wrote:
 Hi,
 I have a function that calculates the distance between two points on a
 sphere. It works but I cant get it to return a float for use in another
 script. Anyone know how I do that??


snip code

    cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
           math.cos(phi1)*math.cos(phi2))
    arc = math.acos( cos )
    type(arc)
    arc = arc*6378.1
    #print str(arc*6378.1)+' km'
    # Remember to multiply arc by the radius of the earth
    # in your favorite set of units to get length.
    return arc


Hi David,

I'm a bit puzzled. A few lines above the return, you have 'type(arc)'.
Try replacing that with 'print type(arc)' and also include 'print
type(arc)' immediately above your return. I think you will find that
the code you posted does return a float.

Best,

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


[Tutor] Create a table by writing to a text file.

2012-02-22 Thread David Craig

Hi,
I have created a list of containing strings that represent distances 
between many different points and would like to display the results in a 
table.
I have been trying to write them to a text file but it is difficult to 
organise them into rows and columns with appropriate spacing to make it 
readable. I would like something like,


Stations   Station1 Station2
Station1   0.033.57654
Station2  33.57654   0.0

but get,

Stations Station1 Station2
Station1 0.0 33.57654
Station2 33.57654 0.0

I've tried adding spaces but to some of the values (i.e. '0.0
') but this is very messy.

Is there a better way to do this?? My code is below.
Thanks
D


# Distance between stations

from dist import dist
import matplotlib.pyplot as plt
import numpy as np


# Guralp GPS decimal coordinates.
# station = [lat, lon, alt]
UFAN = [55.2333142, -7.6770179, 78.3]
UCRUI = [54.9846137, -8.3771698, 75.8]
UGLEN = [54.7064869, -8.7406732, 42.4]
UEASK = [54.2894659, -8.9583439, 9.1]
UACH = [53.8758499, -9.9621948, 22.0]
ULET = [53.5519317, -9.9413447, 70.4]
UHAG = [52.9393892, -9.4344939, 22.7]
ULOOP = [52.5809163, -9.8456417, 10.4]
UBALF = [52.1625237, -10.4099873, 74.3]
ULAMB = [51.7653115, -10.1531573, 13.5]
USHE = [51.5536226, -9.7907148, 115.3]
UGALL = [51.529665, -8.9529546, 33.4]

names = ['UFAN', 'UCRUI', 'UGLEN', 'UEASK', 'UACH', 'ULET', 'UHAG', 
'ULOOP', 'UBALF', 'ULAMB', 'USHE', 'UGALL']
stations = [UFAN, UCRUI, UGLEN, UEASK, UACH, ULET, UHAG, ULOOP, UBALF, 
ULAMB, USHE, UGALL]


distance = [[]]*len(stations)


for i in range(0,len(stations)):
#distance[i,0] = names[i]
temp = []
for j in range(0,len(stations)):
temp.append(' 
'+str(dist(stations[i][0],stations[i][1],stations[j][0],stations[j][1])))

distance[i] = temp

testFile = open('testFile.txt', 'a')
testFile.write('Stations   ')

for i in range(0,len(stations)):
testFile.write(names[i]+'')
testFile.write('\n')

for i in range(0,len(stations)):
testFile.write(names[i]+'  ')
for j in range(0,len(stations)):
testFile.write(distance[i][j]+' ')
testFile.write('\n')
testFile.close()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Create a table by writing to a text file.

2012-02-22 Thread Evert Rol
 Hi,
 I have created a list of containing strings that represent distances between 
 many different points and would like to display the results in a table.
 I have been trying to write them to a text file but it is difficult to 
 organise them into rows and columns with appropriate spacing to make it 
 readable. I would like something like,
 
 Stations   Station1 Station2
 Station1   0.033.57654
 Station2  33.57654   0.0
 
 but get,
 
 Stations Station1 Station2
 Station1 0.0 33.57654
 Station2 33.57654 0.0
 
 I've tried adding spaces but to some of the values (i.e. '0.0') 
 but this is very messy.
 Is there a better way to do this?? My code is below.

This is always a tricky thing to go about. Nicely human-readable doesn't imply 
nicely machine readable. Sometimes a single space or a single tab between 
values/columns is more practical for a(nother) program to read, but not for 
humans.
So I will work from the assummption that you want it human-readable only.
In that case, have a careful read through the string formatting options: 
http://docs.python.org/library/stdtypes.html#string-formatting
Before the two tables there, there's a point 4 which mention a minimum field 
width; that'd be something you could use. Eg:
 print |%20d| % 10
|  10|
 print |%20.5f| % 12.3456789
|12.34568|
 

Hopefully that gets you on the way.

Cheers,

  Evert



 Thanks
 D
 
 
 # Distance between stations
 
 from dist import dist
 import matplotlib.pyplot as plt
 import numpy as np
 
 
 # Guralp GPS decimal coordinates.
 # station = [lat, lon, alt]
 UFAN = [55.2333142, -7.6770179, 78.3]
 UCRUI = [54.9846137, -8.3771698, 75.8]
 UGLEN = [54.7064869, -8.7406732, 42.4]
 UEASK = [54.2894659, -8.9583439, 9.1]
 UACH = [53.8758499, -9.9621948, 22.0]
 ULET = [53.5519317, -9.9413447, 70.4]
 UHAG = [52.9393892, -9.4344939, 22.7]
 ULOOP = [52.5809163, -9.8456417, 10.4]
 UBALF = [52.1625237, -10.4099873, 74.3]
 ULAMB = [51.7653115, -10.1531573, 13.5]
 USHE = [51.5536226, -9.7907148, 115.3]
 UGALL = [51.529665, -8.9529546, 33.4]
 
 names = ['UFAN', 'UCRUI', 'UGLEN', 'UEASK', 'UACH', 'ULET', 'UHAG', 'ULOOP', 
 'UBALF', 'ULAMB', 'USHE', 'UGALL']
 stations = [UFAN, UCRUI, UGLEN, UEASK, UACH, ULET, UHAG, ULOOP, UBALF, ULAMB, 
 USHE, UGALL]
 
 distance = [[]]*len(stations)
 
 
 for i in range(0,len(stations)):
#distance[i,0] = names[i]
temp = []
for j in range(0,len(stations)):
temp.append(' 
 '+str(dist(stations[i][0],stations[i][1],stations[j][0],stations[j][1])))
distance[i] = temp
 
 testFile = open('testFile.txt', 'a')
 testFile.write('Stations   ')
 
 for i in range(0,len(stations)):
testFile.write(names[i]+'')
 testFile.write('\n')
 
 for i in range(0,len(stations)):
testFile.write(names[i]+'  ')
for j in range(0,len(stations)):
testFile.write(distance[i][j]+' ')
testFile.write('\n')
 testFile.close()
 ___
 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] Create a table by writing to a text file.

2012-02-22 Thread Mark Lawrence

On 22/02/2012 13:40, Evert Rol wrote:

Hi,

This is always a tricky thing to go about. Nicely human-readable doesn't imply 
nicely machine readable. Sometimes a single space or a single tab between 
values/columns is more practical for a(nother) program to read, but not for 
humans.
So I will work from the assummption that you want it human-readable only.
In that case, have a careful read through the string formatting options: 
http://docs.python.org/library/stdtypes.html#string-formatting
Before the two tables there, there's a point 4 which mention a minimum field 
width; that'd be something you could use. Eg:

print |%20d| % 10

|  10|

print |%20.5f| % 12.3456789

|12.34568|




Hopefully that gets you on the way.

Cheers,

   Evert




Note that string formatting referenced above is old style, new style can 
be found here http://docs.python.org/library/string.html#formatexamples


--
Cheers.

Mark Lawrence.

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


Re: [Tutor] Create a table by writing to a text file.

2012-02-22 Thread Steven D'Aprano

David Craig wrote:

I have been trying to write them to a text file but it is difficult to 
organise them into rows and columns with appropriate spacing to make it 
readable. I would like something like,


Stations   Station1 Station2
Station1   0.033.57654
Station2  33.57654   0.0

[...]
I've tried adding spaces but to some of the values (i.e. '0.0
') but this is very messy.


Try using string formatting strings. E.g.:

print %s %8.2f %8.2f % (station1, 0, 4)


will produce this output:

station1 0.00 4.00


Naturally you don't have to pass the resultant string to print. You can store 
it in a variable, and write it to a file:


line = %s %8.2f %8.2f % (station1, 0, 4)
myfile.write(line + '\n')



The format string codes cover a lot of options. Each code starts with a % 
sign, and ends with a letter s, d, f, and a few others.


%s  string
%d  decimal number
%f  floating point number
%%  use a literal percentage sign
plus others

Inside the format target, you can add optional terms for the field width, 
number of decimal points, etc. A few examples:


%8.2f  Pad the number to a total width of 8 (or more if necessary),
   using two figures after the decimal place. The number is
   right-justified and padded on the left with spaces.


%-4.1f Pad the number to a total width of 4 (or more if necessary),
   using one figure after the decimal place. The number is
   left-justified and padded on the right with spaces.

Lots more options here:

http://docs.python.org/library/stdtypes.html#string-formatting-operations


Alternatively, if you have Python 2.6 or newer, you can use the format method:

print {0} {1:8.2f} {2:8.2f}.format(station1, 0, 4)


will produce this output:

station1 0.00 4.00


See here for more options:

http://docs.python.org/library/string.html#string-formatting



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


Re: [Tutor] Create a table by writing to a text file.

2012-02-22 Thread Peter Otten
David Craig wrote:

 distance = [[]]*len(stations)

That doesn't do what you think it does:
 
 a = [[]] * 3
 a
[[], [], []]
 a[0].append(42)
 a
[[42], [42], [42]]

See? You get a list that contains the same list len(stations) times. Use

[[] for _ in stations]

instead.

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


Re: [Tutor] return integer from function

2012-02-22 Thread Steven D'Aprano

David Craig wrote:

Hi,
I have a function that calculates the distance between two points on a 
sphere. It works but I cant get it to return a float for use in another 
script. Anyone know how I do that??


You are going to have to explain what you mean in more detail.

If you mean, how can you pass the output of one script as the input of another 
in the shell, remember that the shell communicates by passing strings through 
stdout and stdin. So you need to have your first script actually print its 
output, and then pipe it to the next script, just like you would when using 
shell commands.


On the other hand, if you mean, how do you re-use your distance_on_unit_sphere 
function in another Python program, you need to import it exactly the same as 
you import math. For example, if your distance function is in a file 
sphere.py, and you want to use it in a file calculations.py (say), then 
put this line at the top of calculations.py:


import sphere

and now you can use sphere.distance_on_unit_sphere just as you can use 
math.sin and math.cos.


For this to work, though, sphere.py and calculations.py need to be in the same 
folder. (There are other ways to make that work, but they start getting a 
little tricky to get right.)


On the third hand, if you mean something else, you're going to need to explain 
what you mean because I have no idea what it might be! :)




--
Steven

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


Re: [Tutor] Create a table by writing to a text file.

2012-02-22 Thread David Craig
Thanks everyone, was able to get what I wanted from '/t' but I'm sure 
the other formatting options will be useful in future.

@Peter

a = [[]] * 3
  a

[[], [], []]


  a[0].append(42)
  a

[[42], [42], [42]]


you had me worried for a minute, but
a = [[]] * 3
a[0]=[1,2,3]
a
[[1, 2, 3], [], []]

On 02/22/2012 01:40 PM, Evert Rol wrote:

Hi,
I have created a list of containing strings that represent distances between 
many different points and would like to display the results in a table.
I have been trying to write them to a text file but it is difficult to organise 
them into rows and columns with appropriate spacing to make it readable. I 
would like something like,

Stations   Station1 Station2
Station1   0.033.57654
Station2  33.57654   0.0

but get,

Stations Station1 Station2
Station1 0.0 33.57654
Station2 33.57654 0.0

I've tried adding spaces but to some of the values (i.e. '0.0') but 
this is very messy.
Is there a better way to do this?? My code is below.

This is always a tricky thing to go about. Nicely human-readable doesn't imply 
nicely machine readable. Sometimes a single space or a single tab between 
values/columns is more practical for a(nother) program to read, but not for 
humans.
So I will work from the assummption that you want it human-readable only.
In that case, have a careful read through the string formatting options: 
http://docs.python.org/library/stdtypes.html#string-formatting
Before the two tables there, there's a point 4 which mention a minimum field 
width; that'd be something you could use. Eg:

print |%20d| % 10

|  10|

print |%20.5f| % 12.3456789

|12.34568|
Hopefully that gets you on the way.

Cheers,

   Evert




Thanks
D


# Distance between stations

from dist import dist
import matplotlib.pyplot as plt
import numpy as np


# Guralp GPS decimal coordinates.
# station = [lat, lon, alt]
UFAN = [55.2333142, -7.6770179, 78.3]
UCRUI = [54.9846137, -8.3771698, 75.8]
UGLEN = [54.7064869, -8.7406732, 42.4]
UEASK = [54.2894659, -8.9583439, 9.1]
UACH = [53.8758499, -9.9621948, 22.0]
ULET = [53.5519317, -9.9413447, 70.4]
UHAG = [52.9393892, -9.4344939, 22.7]
ULOOP = [52.5809163, -9.8456417, 10.4]
UBALF = [52.1625237, -10.4099873, 74.3]
ULAMB = [51.7653115, -10.1531573, 13.5]
USHE = [51.5536226, -9.7907148, 115.3]
UGALL = [51.529665, -8.9529546, 33.4]

names = ['UFAN', 'UCRUI', 'UGLEN', 'UEASK', 'UACH', 'ULET', 'UHAG', 'ULOOP', 
'UBALF', 'ULAMB', 'USHE', 'UGALL']
stations = [UFAN, UCRUI, UGLEN, UEASK, UACH, ULET, UHAG, ULOOP, UBALF, ULAMB, 
USHE, UGALL]

distance = [[]]*len(stations)


for i in range(0,len(stations)):
#distance[i,0] = names[i]
temp = []
for j in range(0,len(stations)):
temp.append(' 
'+str(dist(stations[i][0],stations[i][1],stations[j][0],stations[j][1])))
distance[i] = temp

testFile = open('testFile.txt', 'a')
testFile.write('Stations   ')

for i in range(0,len(stations)):
testFile.write(names[i]+'')
testFile.write('\n')

for i in range(0,len(stations)):
testFile.write(names[i]+'  ')
for j in range(0,len(stations)):
testFile.write(distance[i][j]+' ')
testFile.write('\n')
testFile.close()
___
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] Create a table by writing to a text file.

2012-02-22 Thread Jerry Hill
On Wed, Feb 22, 2012 at 10:24 AM, David Craig dcdavem...@gmail.com wrote:

 you had me worried for a minute, but
 a = [[]] * 3
 a[0]=[1,2,3]
 a
 [[1, 2, 3], [], []]


That's not the same thing.  In your example you create three copies of the
same empty list inside your outer list.  You then throw away the first copy
of the empty list and replace it with a new list.  What Peter showed was
mutating that inner list in place.  If you aren't really, really careful,
you will eventually get bitten by this if you create your lists with
multiplication.

 container = [[]] * 3

You can see that this really is three references to the exact same list:
 print [id(item) for item in container]
[17246328, 17246328, 17246328]

If you replace the items, you're fine:
 container[0] = [1, 2, 3]
 print [id(item) for item in container]
[17245808, 17246328, 17246328]

But as soon as you change the contents of one of those duplicate lists,
you're in trouble:
 container[1].append('Data')
 print container
[[1, 2, 3], ['Data'], ['Data']]
 print [id(item) for item in container]
[17245808, 17246328, 17246328]


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


Re: [Tutor] how to rewrite area.py

2012-02-22 Thread William Stewart











On 2/21/2012 6:51 PM, William Stewart wrote: 





hello
I need to rewrite area.py program so that it has separate functions for the 
perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). 

Need to - why? Is this a homework assignment?






I am horrible at math and I cannot even figure out what I need to do for this
Any help would be appreciated

All I have is the menu which looks like this
 
 
Did you run this program? What results did you get? How did they differ from 
what you expected?
Yes it wont run tdue to some problems in my indents but I am working on it


What does being horrible at mat have to do with this?
I dont know

What do you know about defining functions? Not much

Did you write this program yourself?
this is new to me it a beginners computer class, but I think this may be too 
advanced for me , I havent learned anything about python before starting except 
some basic tutorials


If you are taking a Python class and don't know what to do either the class is 
poorly designed or you are in the wrong class.

Please say more about this.

We are glad to help, but won't write your homework for you.



Someone game me some help but Im not sure if I piut it in right
it looks like this
 
import math
from math import pi
 
print your options are:
print  
print 1) Area(SQUARE)
print 2) Area(RECTANGLE)
print 3) Area(CIRCLE)
print 4) Perimeter(SQUARE)
print 5) Perimeter(RECTANGLE)
print 6) Perimeter(CIRCLE)
print 7) Exit
while True: 
    selection = raw_input(Please select an option from the menu.: )

def get_area_of_square():
    print Please enter the width of a square
    area = width**2
    return area

def get_area_of_rectangle():
    Print please enter the width of a rectangle
    area = width*height
    return area
def get_radius_of_circle():
    print please enter the radius of a circle
    radius = pi**2
    retrun radius
    
    
SQUARES:
    area = width*width = width**2
    perimeter = width+width+width+width = 4*width
RECTANGLES:
    area = width*height
    perimeter = width+height+width+height = 2*(width+height)
CIRCLES:
    area = pi*radius**2
    circumference = 2*pi*radius
    
thanks


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


Re: [Tutor] Create a table by writing to a text file.

2012-02-22 Thread Alan Gauld

On 22/02/12 13:14, David Craig wrote:

Hi,
I have created a list of containing strings that represent distances
between many different points and would like to display the results in a
table.



Others have mentioned using format strings.
If it is only for display you could switch to html.
Then defining the table and adding numbers to the cells not only
aligns the values but gives you control over colours, borders and
fonts.

Just another option to consider.

--
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 Designing a simple Program called Life

2012-02-22 Thread leo degon
Hello All,
My name is Leo. I'm just beginning to learn python. I am
learning on my own and have no previous programming experience. I decided
to create a version of john conway's game of life as a personal project.

I've been wondering what GUI to use.
 I've been using Tkinter so far but I've not gotten very far. So far I've
started the basic window but now I'm kinda of stuck in how to proceed.

My idea is when the program initializes to have a root menu with a series
of options.
 Accepting these options under the  new game launches a window where you
can set the initial state of the board to the correct dimensions, colors,
rules, name and initial distribution of live cells. Accepting that window
would launch a window containing the game board and the in-game options. I
would like to be able to pause the game, run it at different speeds, and
add new live cells to the board. I would like to have multiple boards able
to run at once, and I would like the option to save a board and its rules
to load at a later time.

I'd like any ideas on how to approach this project in general and specific.

I'll post the code that I already have later today.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help Designing a simple Program called Life

2012-02-22 Thread bob gailer

On 2/22/2012 1:50 PM, leo degon wrote:

Hello All,
My name is Leo.

Hi Leo  Welcome to Python help.

We are a few volunteers who like assisting others.

A few guidelines:
- always reply-all so a copy goes to the list
- reply in-line rather than at the top.
- if your code is large put it in a pastebin on the web and post the link.
I'm just beginning to learn python. I am learning on my own and have 
no previous programming experience. I decided to create a version of 
john conway's game of life as a personal project.


I've been wondering what GUI to use.
 I've been using Tkinter so far but I've not gotten very far. So far 
I've started the basic window but now I'm kinda of stuck in how to 
proceed.

There are a number of good tutorials on tkinter. Find one and go thru it.


My idea is when the program initializes to have a root menu with a 
series of options.
 Accepting these options under the  new game launches a window where 
you can set the initial state of the board to the correct dimensions, 
colors, rules, name and initial distribution of live cells. Accepting 
that window would launch a window containing the game board and the 
in-game options. I would like to be able to pause the game, run it at 
different speeds, and add new live cells to the board. I would like to 
have multiple boards able to run at once, and I would like the option 
to save a board and its rules to load at a later time.


You have chosen a very ambitious project (for a beginner). I suggest you 
start by creating one part of the whole - get that working then add one 
more piece.
I'd like any ideas on how to approach this project in general and 
specific.




One idea - start with a fixed dimension grid and one initial state - get 
the grid to display with the initial state.
Then step back, say well done,Leo then add code to advance to 
subsequent states with some limit.


I'll post the code that I already have later today.



--
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] Recognizing real numbers

2012-02-22 Thread bob gailer

On 2/21/2012 10:00 PM, Michael Lewis wrote:

Hi everyone,

I have some code where I import a file to use a module. That module 
that I import
takes text and a multiplier, checks for any numbers in that text and 
will then multiply those numbers by the given multiplier. The imported 
module is below. I am getting the text from a file that I have which 
starts out as:


.5 lb. butter
1.75 Cups Graham Cracker Crumbs
2.0 Cups Powder Sugar
1.0 Cups Peanut Butter
2.0 Cups Semi-sweet Chocolate Chips

It seems that the .isdigit() function that I use doesn't recognize the 
.5 as a number and therefore doesn't multiply it. How can I get my 
code to recognize numbers such as .5, 1.75 as numbers?


Wow - the requirements just changed. Up tilll now we were dealing with 
multiplying each digit. Now we have to parse out a string that 
represents a number with decimal places! I hope that we don't raise the 
oven temperature in the process.


Is it true that the number to multiply is always at the beginning of a 
line? If so that makes the job a lot easier.



Imported module:

def MultiplyText(text, multiplier):
'''Recieve a S  int. For digits in S, multiply by multiplier and 
return updated S.'''
return ' '.join(str(float(num) * multiplier) if num.isdigit() else 
num for num in text)


Module doing the importing/opening/reading/creating a new file

import Homework5_1 as multiply

def DoubleDigits(file_name):
'''Open file/read file/write new file that doubles all int's in the
read file'''
try:
read_file = open(file_name)
except IOError:
return 'No such file.'
new_file_name = file_name + '2'
try:
write_file = open(new_file_name, 'w')
except IOError:
read_file.close()
return 'No such file to write to.'
for line in read_file:
new_line = line.split()
new_line = ''.join(multiply.MultiplyText(new_line, 2))
write_file.write(new_line + '\n')
read_file.close()
write_file.close()

def main():
DoubleDigits(raw_input('What file do you want to open? '))


if '__name__' == '__main__':
print main()

Output that is written to my file:

Peanut Butter Bars

Ingredients

.5 lb. butter
1.75 Cups Graham Cracker Crumbs
4.0 Cups Powder Sugar
2.0 Cups Peanut Butter
4.0 Cups Semi-sweet Chocolate Chips

Melt butter. Add graham cracker crumbs,
peanut butter and sugar. Mix well and
pat into sheet pan. Cover with melted
chocolate. Refrigerate until semi-firm,
then cut into squares.

--
Michael J. Lewis



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



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


[Tutor] I cannot run any Python programs

2012-02-22 Thread Tamar Osher

Hi.  I need help.

I have installed Python 3.2.2 and have been using IDLE (the Python shell) to 
type and save a Python program, such as 'Hello World'.

However, the command prompt (the black box) will not allow me to type a Python 
program or to run a Python program.  So I tried to run a Python program using 
Notepad++, and while I am able to type it, I am not able to save it.

I am not able to run any Python programs.  I have read so much about Python, 
and have researched the situation in detail, and have experimented with various 
environmental variables and user/system paths.  I need help to correct the 
situation..
Can someone please help me?  Thanks for helping.  I look forward to hearing 
from you.
 
From Your Friend: Tamar Osher
Skype: tamarosher
Email: emeraldoff...@hotmail.com
Message Phone: 011- 1- 513-252-2936
www.HowToBeGifted.com - marketing communication, web design, and much more





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


Re: [Tutor] I cannot run any Python programs

2012-02-22 Thread Joel Goldstick
On Wed, Feb 22, 2012 at 5:23 PM, Tamar Osher emeraldoff...@hotmail.com wrote:
 Hi.  I need help.

 I have installed Python 3.2.2 and have been using IDLE (the Python shell)
 to type and save a Python program, such as 'Hello World'.

 However, the command prompt (the black box) will not allow me to type a
 Python program or to run a Python program.  So I tried to run a Python
 program using Notepad++, and while I am able to type it, I am not able to
 save it.

 I am not able to run any Python programs.  I have read so much about
 Python, and have researched the situation in detail, and have experimented
 with various environmental variables and user/system paths.  I need help
 to correct the situation..

 Can someone please help me?  Thanks for helping.  I look forward to hearing
 from you.

 From Your Friend: Tamar Osher
 Skype: tamarosher
 Email: emeraldoff...@hotmail.com
 Message Phone: 011- 1- 513-252-2936
 www.HowToBeGifted.com - marketing communication, web design, and much more


run cmd to get to the shell.
in the shell, navigate to the directory where you have saved your file.

type:

python myprogram.py

Tell us what happens.






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




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


Re: [Tutor] I cannot run any Python programs

2012-02-22 Thread Tamar Osher

Dear Joel: HI!  Thanks for helping.  When I use the Python shell, and navigate 
to the saved Python program, what happens is:
A second Python shell pops up, displaying the coding of the program (which is a 
tiny 'hello world' program).  This is what is displayed in the second Python 
shell:
 print(Hello, World!)

In the first Python shell, when I type in what you requested, this is what 
happens:
 python myprogram.py
SyntaxError: invalid syntax
 python hello.py
SyntaxError: invalid syntax
 

I am not able to use the Python shell to find the saved Python program.  I am 
able to use Notepad++ to locate the saved Python program, but I cannot run the 
program.  I cannot do anything with the command prompt (black box).

I request help to figure out how to run Python programs. Thanks for helping me!
 
From Your Friend: Tamar Osher
Email: emeraldoff...@hotmail.com








 Date: Wed, 22 Feb 2012 17:33:22 -0500
 Subject: Re: [Tutor] I cannot run any Python programs
 From: joel.goldst...@gmail.com
 To: emeraldoff...@hotmail.com
 CC: tutor@python.org
 
 On Wed, Feb 22, 2012 at 5:23 PM, Tamar Osher emeraldoff...@hotmail.com 
 wrote:
  Hi.  I need help.
 
  I have installed Python 3.2.2 and have been using IDLE (the Python shell)
  to type and save a Python program, such as 'Hello World'.
 
  However, the command prompt (the black box) will not allow me to type a
  Python program or to run a Python program.  So I tried to run a Python
  program using Notepad++, and while I am able to type it, I am not able to
  save it.
 
  I am not able to run any Python programs.  I have read so much about
  Python, and have researched the situation in detail, and have experimented
  with various environmental variables and user/system paths.  I need help
  to correct the situation..
 
  Can someone please help me?  Thanks for helping.  I look forward to hearing
  from you.
 
  From Your Friend: Tamar Osher
  Skype: tamarosher
  Email: emeraldoff...@hotmail.com
  Message Phone: 011- 1- 513-252-2936
  www.HowToBeGifted.com - marketing communication, web design, and much more
 
 
 run cmd to get to the shell.
 in the shell, navigate to the directory where you have saved your file.
 
 type:
 
 python myprogram.py
 
 Tell us what happens.
 
 
 
 
 
 
  ___
  Tutor maillist  -  Tutor@python.org
  To unsubscribe or change subscription options:
  http://mail.python.org/mailman/listinfo/tutor
 
 
 
 
 -- 
 Joel Goldstick
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recognizing real numbers

2012-02-22 Thread Dave Angel

On 02/21/2012 10:00 PM, Michael Lewis wrote:

Hi everyone,

I have some code where I import a file to use a module. That module that I
import takes text and a multiplier, checks for any numbers in that text and
will then multiply those numbers by the given multiplier. The imported
module is below. I am getting the text from a file that I have which starts
out as:

.5 lb. butter
1.75 Cups Graham Cracker Crumbs
2.0 Cups Powder Sugar
1.0 Cups Peanut Butter
2.0 Cups Semi-sweet Chocolate Chips

It seems that the .isdigit() function that I use doesn't recognize the .5
as a number and therefore doesn't multiply it. How can I get my code to
recognize numbers such as .5, 1.75 as numbers?

Imported module:

def MultiplyText(text, multiplier):
 '''Recieve a S  int. For digits in S, multiply by multiplier and
return updated S.'''
 return ' '.join(str(float(num) * multiplier) if num.isdigit() else num
for num in text)

Somehow, every other time I read that code I missed the for num in 
text phrase that was wrapped around by the mail.


I'm apologizing for my earlier remarks stating that this function would 
not work.  i would clean up the variable names (text is a list, and num 
is a string), and the function comment states that you're multiplying 
individual digits).  But since it works, it's a good base to start with 
for your floating point question.


Easiest answer is to write a function that does check if a string is a 
valid float, the same as num.isdigit()  (lousy names also occur in the 
standard library) does for int.


The new function would be easiest to write with a try/except form.  Take 
a string as a formal parameter, try to float() it in a try block, and if 
it succeeds, return True.


It'd be convenient if there were such a method in str, but since there 
isn't, you'd have to change  num.isdigit() to  isfloat(num).


Have you gotten to try/except in your class yet?

--

DaveA

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


Re: [Tutor] Recognizing real numbers

2012-02-22 Thread Joel Goldstick
On Wed, Feb 22, 2012 at 4:35 PM, bob gailer bgai...@gmail.com wrote:
 On 2/21/2012 10:00 PM, Michael Lewis wrote:

 Hi everyone,

 I have some code where I import a file to use a module. That module that I
 import

 takes text and a multiplier, checks for any numbers in that text and will
 then multiply those numbers by the given multiplier. The imported module is
 below. I am getting the text from a file that I have which starts out as:

 .5 lb. butter
 1.75 Cups Graham Cracker Crumbs
 2.0 Cups Powder Sugar
 1.0 Cups Peanut Butter
 2.0 Cups Semi-sweet Chocolate Chips

 It seems that the .isdigit() function that I use doesn't recognize the .5 as
 a number and therefore doesn't multiply it. How can I get my code to
 recognize numbers such as .5, 1.75 as numbers?

 Wow - the requirements just changed. Up tilll now we were dealing with
 multiplying each digit. Now we have to parse out a string that represents a
 number with decimal places! I hope that we don't raise the oven temperature
 in the process.

 Is it true that the number to multiply is always at the beginning of a line?
 If so that makes the job a lot easier.

 Imported module:

 def MultiplyText(text, multiplier):
     '''Recieve a S  int. For digits in S, multiply by multiplier and return
 updated S.'''
     return ' '.join(str(float(num) * multiplier) if num.isdigit() else num
 for num in text)

 Module doing the importing/opening/reading/creating a new file

 import Homework5_1 as multiply

 def DoubleDigits(file_name):
     '''Open file/read file/write new file that doubles all int's in the
     read file'''
     try:
         read_file = open(file_name)
     except IOError:
         return 'No such file.'
     new_file_name = file_name + '2'
     try:
         write_file = open(new_file_name, 'w')
     except IOError:
         read_file.close()
         return 'No such file to write to.'
     for line in read_file:
         new_line = line.split()
         new_line = ''.join(multiply.MultiplyText(new_line, 2))
         write_file.write(new_line + '\n')
     read_file.close()
     write_file.close()

 def main():
     DoubleDigits(raw_input('What file do you want to open? '))


 if '__name__' == '__main__':
     print main()

 Output that is written to my file:

 Peanut Butter Bars

 Ingredients

 .5 lb. butter
 1.75 Cups Graham Cracker Crumbs
 4.0 Cups Powder Sugar
 2.0 Cups Peanut Butter
 4.0 Cups Semi-sweet Chocolate Chips

 Melt butter. Add graham cracker crumbs,
 peanut butter and sugar. Mix well and
 pat into sheet pan. Cover with melted
 chocolate. Refrigerate until semi-firm,
 then cut into squares.

 --
 Michael J. Lewis



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



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

If the first stuff in the line is always the number, and you capture
the line in s then:

n  = float(s.split()[0])   will give you the number.  You should wrap
this up with a try block so that it doesn't fail if it isn't a number

split method separates on whitespace and puts each part of the string
in a list.  [0] takes the first of those list items.  float converts
to a float




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


Re: [Tutor] I cannot run any Python programs

2012-02-22 Thread Joel Goldstick
On Wed, Feb 22, 2012 at 5:49 PM, Tamar Osher emeraldoff...@hotmail.com wrote:
 Dear Joel: HI!  Thanks for helping.  When I use the Python shell, and
 navigate to the saved Python program, what happens is:
 A second Python shell pops up, displaying the coding of the program (which
 is a tiny 'hello world' program).  This is what is displayed in the second
 Python shell:
 print(Hello, World!)

 In the first Python shell, when I type in what you requested, this is what
 happens:
 python myprogram.py
 SyntaxError: invalid syntax
 python hello.py
 SyntaxError: invalid syntax


 I am not able to use the Python shell to find the saved Python program.  I
 am able to use Notepad++ to locate the saved Python program, but I cannot
 run the program.  I cannot do anything with the command prompt (black box).

 I request help to figure out how to run Python programs. Thanks for helping
 me!


from the  stuff at the start of each line, you are in a python
shell.  Don't do that.  Just get into a command shell.
Since I believe you are in windows, press the start button, then run
command and the command you run should be cmd

This will bring you to a window which looks a lot like DOS used to
look.  You probably are too young for that.  Anyway, at that point,
try typing python myprogram.py


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


Re: [Tutor] I cannot run any Python programs

2012-02-22 Thread Tamar Osher

Dear Joel: Hi!  Thanks for helping.  I typed cmd, and got the same black box, 
this time labeled C:\windows\system32\cmd.exe instead of Command Prompt.  
When I type python myprogram.py, this is what appears on the screen:'python' is 
not recognized as an internal or external command, operable program, or batch 
file.

Can you help me?  I hope so!
 
From Your Friend: Tamar Osher
Email: emeraldoff...@hotmail.com







 Date: Wed, 22 Feb 2012 18:02:23 -0500
 Subject: Re: [Tutor] I cannot run any Python programs
 From: joel.goldst...@gmail.com
 To: emeraldoff...@hotmail.com
 CC: tutor@python.org
 
 On Wed, Feb 22, 2012 at 5:49 PM, Tamar Osher emeraldoff...@hotmail.com 
 wrote:
  Dear Joel: HI!  Thanks for helping.  When I use the Python shell, and
  navigate to the saved Python program, what happens is:
  A second Python shell pops up, displaying the coding of the program (which
  is a tiny 'hello world' program).  This is what is displayed in the second
  Python shell:
  print(Hello, World!)
 
  In the first Python shell, when I type in what you requested, this is what
  happens:
  python myprogram.py
  SyntaxError: invalid syntax
  python hello.py
  SyntaxError: invalid syntax
 
 
  I am not able to use the Python shell to find the saved Python program.  I
  am able to use Notepad++ to locate the saved Python program, but I cannot
  run the program.  I cannot do anything with the command prompt (black box).
 
  I request help to figure out how to run Python programs. Thanks for helping
  me!
 
 
 from the  stuff at the start of each line, you are in a python
 shell.  Don't do that.  Just get into a command shell.
 Since I believe you are in windows, press the start button, then run
 command and the command you run should be cmd
 
 This will bring you to a window which looks a lot like DOS used to
 look.  You probably are too young for that.  Anyway, at that point,
 try typing python myprogram.py
 
 
 -- 
 Joel Goldstick
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I cannot run any Python programs

2012-02-22 Thread Joel Goldstick
On Wed, Feb 22, 2012 at 6:11 PM, Tamar Osher emeraldoff...@hotmail.com wrote:
 Dear Joel: Hi!  Thanks for helping.  I typed cmd, and got the same black
 box, this time labeled C:\windows\system32\cmd.exe instead of Command
 Prompt.  When I type python myprogram.py, this is what appears on the
 screen:
 'python' is not recognized as an internal or external command, operable
 program, or batch file.

 Can you help me?  I hope so!


 From Your Friend: Tamar Osher
 Email: emeraldoff...@hotmail.com







 Date: Wed, 22 Feb 2012 18:02:23 -0500

 Subject: Re: [Tutor] I cannot run any Python programs
 From: joel.goldst...@gmail.com
 To: emeraldoff...@hotmail.com
 CC: tutor@python.org

 On Wed, Feb 22, 2012 at 5:49 PM, Tamar Osher emeraldoff...@hotmail.com
 wrote:
  Dear Joel: HI!  Thanks for helping.  When I use the Python shell, and
  navigate to the saved Python program, what happens is:
  A second Python shell pops up, displaying the coding of the program
  (which
  is a tiny 'hello world' program).  This is what is displayed in the
  second
  Python shell:
  print(Hello, World!)
 
  In the first Python shell, when I type in what you requested, this is
  what
  happens:
  python myprogram.py
  SyntaxError: invalid syntax
  python hello.py
  SyntaxError: invalid syntax
 
 
  I am not able to use the Python shell to find the saved Python program.
  I
  am able to use Notepad++ to locate the saved Python program, but I
  cannot
  run the program.  I cannot do anything with the command prompt (black
  box).
 
  I request help to figure out how to run Python programs. Thanks for
  helping
  me!
 

 from the  stuff at the start of each line, you are in a python
 shell. Don't do that. Just get into a command shell.
 Since I believe you are in windows, press the start button, then run
 command and the command you run should be cmd

 This will bring you to a window which looks a lot like DOS used to
 look. You probably are too young for that. Anyway, at that point,
 try typing python myprogram.py


 --
 Joel Goldstick

Don't top post.  Put your comments at the bottom of the message or
intersperse where appropriate.  I'm not a windows guy anymore.
Someone who is can help you figure out how to find out where python is
and put it on your path.

In the mean time, google microsoft python setting up path and you
may be on your way!

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


Re: [Tutor] I cannot run any Python programs

2012-02-22 Thread Tamar Osher

Thanks!  I hope to find a Windows7 expert to help me.
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to rewrite area.py

2012-02-22 Thread William Stewart
so I copied your format except I changed shape 3 to circle, Did I do the circle 
part right?
and would this be considered seperate functions?
 
Thanks for your help

import math
from math import pi

menu = 
Pick a shape(1-3):
   1) Square
   2) Rectangle
   3) Triangle
   4) Quit

shape = int(input(menu))
while shape != 4:
   if shape == 1:
  length = float(input(Length: ))
  print( Area of square = , length ** 2 )
   elif shape == 2:
  length = float(input(Length: ))
  width = float(input(Width: ))
  print( Area of rectangle = , length * width )   

   elif shape == 3:
  area = float(input(Radius: ))
  circumference = float(input(radius: ))
  print( Area of Circle = , pi*radius**2 )
   shape = int(input(menu))
 
 
 
OR would this work better?
 
 
import math
from math import pi
print your options are:
print  
print 1) Area(SQUARE)
print 2) Area(RECTANGLE)
print 3) Area(CIRCLE)
print 4) Perimeter(SQUARE)
print 5) Perimeter(RECTANGLE)
print 6) Perimeter(CIRCLE)
print 7) Exit
while True: 
    selection = raw_input(Please select an option from the menu.: )

def get_area_of_square():
    print Please enter the width of a square
    area = width**2
    return area

def get_area_of_rectangle():
    Print please enter the width of a rectangle
    area = width*height
    return area
def get_radius_of_circle():
    print please enter the radius of a circle
    radius = pi**2
    retrun radius
    
    
SQUARES:
    area = width*width = width**2
    perimeter = width+width+width+width = 4*width
RECTANGLES:
    area = width*height
    perimeter = width+height+width+height = 2*(width+height)
CIRCLES:
    area = pi*radius**2
    circumference = 2*pi*radius
    
 
 



--- On Tue, 2/21/12, Alan Gauld alan.ga...@btinternet.com wrote:


From: Alan Gauld alan.ga...@btinternet.com
Subject: Re: [Tutor] how to rewrite area.py
To: tutor@python.org
Date: Tuesday, February 21, 2012, 7:46 PM


On 21/02/12 23:51, William Stewart wrote:

 I need to rewrite area.py program so that it has separate functions for
 the perimeter and area of a square, a rectangle, and a circle (3.14 *
 radius**2).

You will find something similar in my tutorial in the topic Branching.
Look under the heading Python multi-selection and there is some code you 
should be able to include as template.

Have a go and come back with questions.

 I am horrible at math and I cannot even figure out what I need to do for
 this

Steven has done the math bit for you, so just plug it into the python code you 
need.

-- 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] Help Designing a simple Program called Life

2012-02-22 Thread Alan Gauld

On 22/02/12 18:50, leo degon wrote:

Hello All,
 My name is Leo. I'm just beginning to learn python. I am
learning on my own and have no previous programming experience. I
decided to create a version of john conway's game of life as a personal
project.


OK, Thats quite a good project for a beginner because it will require ac 
number of differentb concepts.



I've been wondering what GUI to use.


Personally I'd say don't. at least not for a start. Get the game working 
on the console first then transfer it to the GUI later.

One of the fundamental paradigms for GUI program is the Model-View
paradigm where you have separate code to represent the logic of the 
program - the model - from that which displays the UI - The view.

You can have different views of the same model. eg. a text view
and a graphical view. You can even have both open at the same time!

In your case start with a very simple text view using print
statements.


My idea is when the program initializes to have a root menu with a
series of options.


In GUI progrqamming beginners often start by thinking about the GUI 
layout and controls. Thats usually the wrong place to start.

Start with the model.

In your case that's a grid or matrix with some cells filled in. You need 
to cyclically recalculate the status of each cell based on the status of 
the cells around it. (Hint: it may be easier to create a grid thats 1 
cell bigger in every direction than your display...)



in-game options. I would like to be able to pause the game, run it at
different speeds, and add new live cells to the board.  I would like to
have multiple boards able to run at once, and I would like the option to
save a board and its rules to load at a later time.


All good ideas but get the most basic one working first a hard coded 
starting point that morphs into the second generation. Once that works 
get the cycles running until you hit a key to stop. At that stage we 
might think about introducing a GUI... But thats probably quie a long 
way off just yet.



I'd like any ideas on how to approach this project in general and specific.


Build a little, test a lot.

Think about how you will test it before you build it (this is known as 
test driven development - TDD - in software engineering circles. But 
it's good for amateurs too!)



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


Re: [Tutor] I cannot run any Python programs

2012-02-22 Thread Mark Lawrence

On 22/02/2012 23:29, Tamar Osher wrote:


Thanks!  I hope to find a Windows7 expert to help me.

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


Try reading this http://docs.python.org/using/windows.html

--
Cheers.

Mark Lawrence.

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


Re: [Tutor] I cannot run any Python programs

2012-02-22 Thread Alan Gauld

On 22/02/12 23:29, Tamar Osher wrote:

Thanks! I hope to find a Windows7 expert to help me.


You don't need a Windows 7 expert, just to set things
up properly.

First open up Notepad++ again and enter everything between
the  then save to a file called myHello.py and exit Notepad++.


print (Hello world, Python calling!)
input(Hit return to exit)


Find myhello.py in Windows explorer and double click it.
(It's probably a good idea to create a special folder to
store your python programs. It'll be easier to find them
in the future!)

If python is installed correctly a black window should
open displaying:

Hello world, Python calling
Hit return to exit

If you hit return the window should close.

Now open the  same file in IDLE (File-Open)

You should have a new edit window.
In IDLE  choose the Run-Run Module menu item.

Your program should now run inside IDLE and display its output in the 
Python Shell window of IDLE. When you hit return this time IDLE stays 
open but returnms to the Python shell prompt 


If that all works, great, you are set up. If it doesn't come back and 
tell us *exactly* what you did and what was displayed. Copy 'n paste any 
error messages if possible.


HTH
--
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


Re: [Tutor] how to rewrite area.py

2012-02-22 Thread Alan Gauld

On 22/02/12 23:45, William Stewart wrote:

so I copied your format except I changed shape 3 to circle, Did I do the
circle part right?


Nearly.
The circumference is wrong, you need to calculate it not read it from 
the user.




and would this be considered separate functions?


No, but your second variant is separate functions. You just need to 
insert them into the first version as appropriate. (After you get them 
working of course!:-)



*elif shape == 3:
area = float(input(Radius: ))
circumference = float(input(radius: ))
print( Area of Circle = , pi*radius**2 )
shape = int(input(menu))*
while True:
selection = raw_input(Please select an option from the menu.: )

def get_area_of_square():
print Please enter the width of a square

This line needs to be an input as you did above.
All you are doing here is printing a message not reading anything back.
And certainly not assigning anything to width.


area = width**2
return area


That defines the function but does not call it. You should put the 
definition outside the loop - above all the code above - and then call 
it inside the if/else statement:


area = get_area_of_square()

or even

print Area of square = , get_area_of_square()

HTH
--
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 writing functions

2012-02-22 Thread Saad Javed
I am learning python and need guidance for writing some code. I've written
a simple program (with pointers from people) that parses an tv show xml
feed and prints their values in plain text after performing some string
operations.

[CODE]feed = urllib.urlopen(rssPage) #rssPage: address of xml feed
tree = etree.parse(feed)
x = tree.xpath(/rss/channel/item/title/text())
x = str(x[0])
for tag in tags: #tags is a list of items like hdtv, xvid, 720p etc
x = re.sub(r'\b' + tag + r'\b', '', x)
z = re.sub(r'[^\w\s]', '', x)
y = tree1.xpath(/rss/channel/item/pubDate/text())
print %s - %s %(z.rstrip(), y[0][:16])[/CODE]

The code works fine (prints the name of the show and date). Now since I am
parsing more than one feed, I thought the better way was to split the
functionality into diff functions: one to get the values and the other to
remove the tags. I'm still *very* new to python and came up with the
following code.

[CODE]def get_value(feed):
try:
url = urllib2.urlopen(feed)
 tree = etree.parse(url)
x = tree.xpath(/rss/channel/item/title/text())
 y = tree.xpath(/rss/channel/item/pubDate/text())
x = str(x[0])
 y = str(y[0][:16])
return x
return y
 except SyntaxError:
print 'Service Unavailable'
pass

def del_tag(x):
tags = ['HDTV', 'LOL', 'VTV', 'x264', 'DIMENSION', 'XviD', '720P',
'IMMERSE', '720p', 'X264']
 for tag in tags:
x = re.sub(r'\b' + tag + r'\b', '', x)
 y = re.sub(r'[^\w\s]', '', x)
def main():
a = get_value(rssPage)
 b = del_tag(a)
print b
 if __name__ == '__main__':
main()[/CODE]

My desired working is to supply the xml feed address to the
[B]get_value[/B] function which returns the title and date as strings
assigned to [B]x[/B] and [B]y[/B]. Then I run the [B]del_tag[/B] function
on the title string ([B]x[/B]) and remove tags and the [B]main()[/B]
function prints both [B]x[/B] and [B]y[/B] (Title, Date).

Running this code returns [B]None[/B].

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


[Tutor] Which computer operating system is best for Python developers?

2012-02-22 Thread Tamar Osher

Hi.  I am still having trouble installing and using Python on my (new) Windows 
7 computer, but I plan to contact Microsoft forums and see if they can help me, 
since this is a Windows problem and not a Python problem.

My question: For the future, what type of computer is best for Python 
developers?  Do all Python developers use some type of Unix computer?
I appreciate your feedback and look forward to hearing from you.  Thanks for 
your time.
 
From Your Friend: Tamar Osher
Email: emeraldoff...@hotmail.com





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


Re: [Tutor] Which computer operating system is best for Python developers?

2012-02-22 Thread David Rock
* Tamar Osher emeraldoff...@hotmail.com [2012-02-22 19:00]:
 
 Hi.  I am still having trouble installing and using Python on my (new)
 Windows 7 computer, but I plan to contact Microsoft forums and see if
 they can help me, since this is a Windows problem and not a Python
 problem.
 
 My question: For the future, what type of computer is best for Python
 developers?  Do all Python developers use some type of Unix computer?
 I appreciate your feedback and look forward to hearing from you.
 Thanks for your time.

As always, the answer is it depends.  If you plan on doing Win32
python programming, it doesn't make sense to use anything other than a
Windows system.  It is usually easier if you can develop on a system
that is similar to where your programs will run, but it is by no means a
requirement.  Your biggest challenge if developing on unlike systems,
will be using methods that might be OS-specific (os.fork() comes to
mind).  

As long as you keep things neutral, you shouldn't have huge issues.

-- 
David Rock
da...@graniteweb.com


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


Re: [Tutor] Which computer operating system is best for Python developers?

2012-02-22 Thread Mark Lawrence

On 23/02/2012 01:00, Tamar Osher wrote:


Hi.  I am still having trouble installing and using Python on my (new) Windows 
7 computer, but I plan to contact Microsoft forums and see if they can help me, 
since this is a Windows problem and not a Python problem.

My question: For the future, what type of computer is best for Python 
developers?  Do all Python developers use some type of Unix computer?
I appreciate your feedback and look forward to hearing from you.  Thanks for 
your time.


From Your Friend: Tamar Osher

Email: emeraldoff...@hotmail.com

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


I use Windows simply for the convenience and have never had a problem 
that couldn't be solved.  I guess that some 40 years of industry 
experience tells me that reading manuals before trying something tends 
to save time in the long run.


--
Cheers.

Mark Lawrence.

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


Re: [Tutor] Recognizing real numbers (bob gailer)

2012-02-22 Thread Michael Lewis
  Hi everyone,

 I have some code where I import a file to use a module. That module
 that I import
 takes text and a multiplier, checks for any numbers in that text and
 will then multiply those numbers by the given multiplier. The imported
 module is below. I am getting the text from a file that I have which
 starts out as:

 .5 lb. butter
 1.75 Cups Graham Cracker Crumbs
 2.0 Cups Powder Sugar
 1.0 Cups Peanut Butter
 2.0 Cups Semi-sweet Chocolate Chips

 It seems that the .isdigit() function that I use doesn't recognize the
 .5 as a number and therefore doesn't multiply it. How can I get my
 code to recognize numbers such as .5, 1.75 as numbers?

Wow - the requirements just changed. Up tilll now we were dealing with
multiplying each digit. Now we have to parse out a string that
represents a number with decimal places! I hope that we don't raise the
oven temperature in the process.

Well - this is part of my homework and the first question dealt with only
multiplying each digit. the second part of the homework then asked to write
a file that imported the file from the previous homework portion and
utilized the multiplication function in that file. No oven temperature
changes...I promise.

Is it true that the number to multiply is always at the beginning of a
line? If so that makes the job a lot easier.

It's not true. The number can be anywhere in the text.

 Imported module:

 def MultiplyText(text, multiplier):
 '''Recieve a S  int. For digits in S, multiply by multiplier and
 return updated S.'''
 return ' '.join(str(float(num) * multiplier) if num.isdigit() else
 num for num in text)

 Module doing the importing/opening/reading/creating a new file

 import Homework5_1 as multiply

 def DoubleDigits(file_name):
 '''Open file/read file/write new file that doubles all int's in the
 read file'''
 try:
 read_file = open(file_name)
 except IOError:
 return 'No such file.'
 new_file_name = file_name + '2'
 try:
 write_file = open(new_file_name, 'w')
 except IOError:
 read_file.close()
 return 'No such file to write to.'
 for line in read_file:
 new_line = line.split()
 new_line = ''.join(multiply.MultiplyText(new_line, 2))
 write_file.write(new_line + '\n')
 read_file.close()
 write_file.close()

 def main():
 DoubleDigits(raw_input('What file do you want to open? '))


 if '__name__' == '__main__':
 print main()

 Output that is written to my file:

 Peanut Butter Bars

 Ingredients

 .5 lb. butter
 1.75 Cups Graham Cracker Crumbs
 4.0 Cups Powder Sugar
 2.0 Cups Peanut Butter
 4.0 Cups Semi-sweet Chocolate Chips

 Melt butter. Add graham cracker crumbs,
 peanut butter and sugar. Mix well and
 pat into sheet pan. Cover with melted
 chocolate. Refrigerate until semi-firm,
 then cut into squares.

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


Re: [Tutor] Recognizing real numbers

2012-02-22 Thread Michael Lewis
On Wed, Feb 22, 2012 at 2:52 PM, Dave Angel d...@davea.name wrote:

 On 02/21/2012 10:00 PM, Michael Lewis wrote:

 Hi everyone,

 I have some code where I import a file to use a module. That module that I
 import takes text and a multiplier, checks for any numbers in that text
 and
 will then multiply those numbers by the given multiplier. The imported
 module is below. I am getting the text from a file that I have which
 starts
 out as:

 .5 lb. butter
 1.75 Cups Graham Cracker Crumbs
 2.0 Cups Powder Sugar
 1.0 Cups Peanut Butter
 2.0 Cups Semi-sweet Chocolate Chips

 It seems that the .isdigit() function that I use doesn't recognize the .5
 as a number and therefore doesn't multiply it. How can I get my code to
 recognize numbers such as .5, 1.75 as numbers?

 Imported module:

 def MultiplyText(text, multiplier):
 '''Recieve a S  int. For digits in S, multiply by multiplier and

 return updated S.'''
 return ' '.join(str(float(num) * multiplier) if num.isdigit() else num
 for num in text)

  Somehow, every other time I read that code I missed the for num in
 text phrase that was wrapped around by the mail.


No worries - this list has been crazy helpful to me.


 I'm apologizing for my earlier remarks stating that this function would
 not work.  i would clean up the variable names (text is a list, and num is
 a string), and the function comment states that you're multiplying
 individual digits).  But since it works, it's a good base to start with for
 your floating point question.

 Easiest answer is to write a function that does check if a string is a
 valid float, the same as num.isdigit()  (lousy names also occur in the
 standard library) does for int.

 The new function would be easiest to write with a try/except form.  Take a
 string as a formal parameter, try to float() it in a try block, and if it
 succeeds, return True.

 It'd be convenient if there were such a method in str, but since there
 isn't, you'd have to change  num.isdigit() to  isfloat(num).

 Have you gotten to try/except in your class yet?


We have. I actually have a function written in my imported file to check if
a string is a valid float, but I didn't use it because I also have
raw_input in that same function, which I don't want. I'll rework the
imported function to remove the raw_input and put that in a function by
itself so I can utilize the valid float try/except that I've already
written.



 --

 DaveA




-- 
Michael J. Lewis

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


Re: [Tutor] Reading/dealing/matching with truly huge (ascii) files

2012-02-22 Thread Elaina Ann Hyde
On Wed, Feb 22, 2012 at 8:50 PM, Peter Otten __pete...@web.de wrote:

 Elaina Ann Hyde wrote:

  So, Python question of the day:  I have 2 files that I could normally
 just
  read in with asciitable, The first file is a 12 column 8000 row table
 that
  I have read in via asciitable and manipulated.  The second file is
  enormous, has over 50,000 rows and about 20 columns.  What I want to do
 is
  find the best match for (file 1 column 1 and 2) with (file 2 column 4 and
  5), return all rows that match from the huge file, join them togeather
 and
  save the whole mess as a file with 8000 rows (assuming the smaller table
  finds one match per row) and 32=12+20 columns.  So my read code so far is
  as follows:
  -
  import sys
  import asciitable
  import matplotlib
  import scipy
  import numpy as np
  from numpy import *
  import math
  import pylab
  import random
  from pylab import *
  import astropysics
  import astropysics.obstools
  import astropysics.coords
 
  x=small_file
  #cannot read blank values (string!) if blank insert -999.99
  dat=asciitable.read(x,Reader=asciitable.CommentedHeader,
  fill_values=['','-999.99'])
  y=large_file
  fopen2=open('cfile2match.list','w')
  dat2=asciitable.read(y,Reader=asciitable.CommentedHeader,
  fill_values=['','-999.99'])
  #here are the 2 values for the small file
  Radeg=dat['ra-drad']*180./math.pi
  Decdeg=dat['dec-drad']*180./math.pi
 
  #here are the 2 values for the large file
  Radeg2=dat2['ra-drad']*180./math.pi
  Decdeg2=dat2['dec-drad']*180./math.pi
 
  for i in xrange(len(Radeg)):
   for j in xrange(len(Radeg2)):
  #select the value if it is very, very, very close
  if i != j and Radeg[i] = (Radeg2[j]+0.01) and
  Radeg[i]
 = (Radeg2[j]-0.01) and Decdeg[i] = (Decdeg2[j]+0.01) and
  Decdeg[i] = (Decdeg2[j]-0.01):
  fopen.write(  .join([str(k) for k in
  list(dat[i])])+ + .join([str(k) for k in list(dat[j])])+\n)
  ---
  Now this is where I had to stop, this is way, way too long and messy.  I
  did a similar approach with smaller (9000 lines each) files and it worked
  but took awhile, the problem here is I am going to have to play with the
  match range to return the best result and give only one (1!) match per
 row
  for my smaller file, i.e. row 1 of small file must match only 1 row of
  large file. then I just need to return them both.  However, it isn't
  clear to me that this is the best way forward.  I have been changing the
  xrange to low values to play with the matching, but I would appreciate
 any
  ideas.  Thanks

 If you calculate the distance instead of checking if it's under a certain
 threshold you are guaranteed to get (one of the) best matches.
 Pseudo-code:

 from functools import partial
 big_rows = read_big_file_into_memory()

 def distance(small_row, big_row):
...

 for small_row in read_small_file():
best_match = min(big_rows, key=partial(dist, small_row))
write_to_result_file(best_match)


 As to the actual implementation of the distance() function, I don't
 understand your problem description (two columns in the first, three in the
 second, how does that work), but generally

 a, c = extract_columns_from_small_row(small_row)
 b, d = extract_columns_from_big_row(big_row)
 if (a = b + eps) and (c = d + eps):
   # it's good

 would typically become

 distance(small_row, big_row):
a, c = extract_columns_from_small_row(small_row)
b, d = extract_columns_from_big_row(big_row)
x = a-b
y = c-d
return math.sqrt(x*x+y*y)


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




Thanks for all the helpful hints, I really like the idea of using distances
instead of a limit.  Walter was right that the 'i !=j' condition was
causing problems.  I think that Alan and Steven's use of the index
separately was great as it makes this much easier to test (and yes
'astropysics' is a valid package, it's in there for later when I convert
astrophysical coordinates and whatnot, pretty great but a little buggy
FYI).  So I thought, hey, why not try to do a little of all these ideas,
and, if you'll forgive the change in syntax, I think the problem is that
the file might really just be too big to handle, and I'm not sure I have
the right idea with the best_match:
---
#!/usr/bin/python

import sys
import asciitable
import matplotlib
import scipy
import numpy as np
import math
import pylab
import random
from pylab import *
import astropysics
import astropysics.obstools
import astropysics.coords
from astropysics.coords import ICRSCoordinates,GalacticCoordinates

#small
x=open('allfilematch.list')

#really big 2MASS file called 'sgr_2df_big.list'
y=open('/Volumes/Diemos/sgr_2df_big.list')


Re: [Tutor] Recognizing real numbers

2012-02-22 Thread Dave Angel

On 02/22/2012 08:54 PM, Michael Lewis wrote:

On Wed, Feb 22, 2012 at 2:52 PM, Dave Angeld...@davea.name  wrote:
SNIP

I actually have a function written in my imported file to check if
a string is a valid float, but I didn't use it because I also have
raw_input in that same function, which I don't want. I'll rework the
imported function to remove the raw_input and put that in a function by
itself so I can utilize the valid float try/except that I've already
written.



That alone is a valuable lesson.  When writing functions, try to make 
each function do one task, thoroughly and flexibly.  Then it's much more 
likely to be reusable.



--

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


Re: [Tutor] Reading/dealing/matching with truly huge (ascii) files

2012-02-22 Thread Mark Lawrence

On 23/02/2012 01:55, Elaina Ann Hyde wrote:

[big snips]

Hi Elaina,

I'm sorry but I can't help with your problem with the memory cos I don't 
know enough about the combination of Python and Unix wrt memory 
management.  However can I suggest that you use more whitespace in your 
code to make it easier on all MkI eyeballs, e.g. you have


Decdeg2=dat2['col4']+(dat2['col5']/60.)+(dat2['col6']/(60.*60.))

I think this looks better as

Decdeg2 = dat2['col4'] + (dat2['col5']/60.) + (dat2['col6'] / (60.*60.))

--
Cheers.

Mark Lawrence.

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


[Tutor] Compiled Python File

2012-02-22 Thread Michael Lewis
First, thanks to everyone who helped me out regarding my Recognizing real
numbers post. I gained a lot of knowledge over the past two days!

I've noticed that after I execute some of my .py files, a Compiled Python
File is automatically saved to my directory. This doesn't happen for every
file that I execute though. Why is that?

Thanks!

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


Re: [Tutor] Compiled Python File

2012-02-22 Thread Steven D'Aprano
On Wed, Feb 22, 2012 at 07:29:42PM -0800, Michael Lewis wrote:
 First, thanks to everyone who helped me out regarding my Recognizing real
 numbers post. I gained a lot of knowledge over the past two days!
 
 I've noticed that after I execute some of my .py files, a Compiled Python
 File is automatically saved to my directory. This doesn't happen for every
 file that I execute though. Why is that?

When you execute a file directly from the shell, using something like 
this command:

$ python my_python_script.py

no .pyc file is created. But when you import a file from within Python, 
either by hand or within a script:

 import my_module

Python compiles it and saves the compiled version to my_module.pyc so 
that the next time you call import, it will be faster.


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


Re: [Tutor] Which computer operating system is best for Python developers?

2012-02-22 Thread Steven D'Aprano
On Wed, Feb 22, 2012 at 07:00:57PM -0600, Tamar Osher wrote:
 
 Hi.  I am still having trouble installing and using Python on my (new) 
 Windows 7 computer, but I plan to contact Microsoft forums and see if they 
 can help me, since this is a Windows problem and not a Python problem.
 
 My question: For the future, what type of computer is best for Python 
 developers?  Do all Python developers use some type of Unix computer?
 I appreciate your feedback and look forward to hearing from you.  Thanks for 
 your time.

For sure, Linux is the best OS for development.

That doesn't mean that you can't develop on other OSes, or that Linux is 
perfect, but generally speaking it is the simplest and easiest, at least 
once you learn the Linux/Unix ways of thinking, or can memorize a few of 
the most common commands you need to use.

And please don't read this as an attack on Windows, or Mac OS, or 
whatever your favourite OS is. All OSes have their strengths and 
weaknesses, and the range and quality of free development tools happens 
to be one of Linux's biggest strength.

If you hang around on the python-dev mailing list, you will see that one 
of Python's ongoing weaknesses is that the developers don't have enough 
people able and willing to test Python under Windows and fix problems as 
they occur. When you ask why, they tell you that it's because dealing 
with Microsoft licencing is difficult, that the C compilers change too 
often in backwards-incompatible ways, that they can't get people to do 
testing, that in a thousand little ways it just isn't fun or easy to 
develop Python on Windows. Or even develop *in* Python.

On my Linux system, I get Python pre-installed, plus a whole bunch of 
programmers' editors, debugging tools, admin tools, etc. If they don't 
come installed, they are usually one command away:

yum install name-of-package
aptitude install name-of-package

depending on whether you are using Red Hat based Linux, or Debian based 
Linux. On Windows, every package needs to be installed by hand. If 
there's a binary installer, I better hope it works on my system, 
because compiling it myself is a PITA even if I had a C compiler, which 
I don't.

On Windows, I have Notepad, which is a crap editor, WordPad, which isn't 
designed for programming, or heavyweight IDEs that come with my 
compiler. I would need to learn a whole new IDE for every language I 
learn.

On Linux, I have half a dozen programmer's editors already available for 
me. Even the feeblest, nano, is more powerful than Notepad. I just use 
whatever tools I'm already used to using, and it just works:

http://blog.sanctum.geek.nz/series/unix-as-ide/

Unix/Linux is designed to be an development environment, rather than 
having development be an optional extra. No suprises there: Linux 
particularly, but also Unix back in the early days, was built by 
programmers to scratch their own itch: they wanted a good development 
environment, and so they built Unix to be a good development 
environment.

With Windows and Mac OS, it is primarily designed as a desktop OS, with 
development being a necessary evil rather than a design choice.

If you decide to shift from Windows to something else, you may find that 
it's more work learning the new OS than it would have been to have just 
stuck with what you know and learn to use it effectively.


-- 
Steven

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


[Tutor] Writing to a file/changing the file name

2012-02-22 Thread Michael Lewis
Hi everyone,

I have a program where I open a file (recipe.txt), I read that file and
write it to another file. I am doing some multiplying of numbers in
between; however, my question is, when I name the file I am writing to, the
file extension is changed, but the file name is not. What am I doing wrong?

Code:

import Homework5_1 as multiply

def MultiplyNumbersInFile(file_name, multiplier):
'''Open file/read file/write new file that doubles all int's in the
read file'''
try:
read_file = open(file_name)
except IOError:
print I can't find file: , file_name
return
new_file_name = file_name + '2'
try:
write_file = open(new_file_name, 'w')
except IOError:
read_file.close()
print I can't open file: , new_file_name
return
for line in read_file:
new_line = line.split()
new_line = ''.join(multiply.MultiplyText(new_line, multiplier))
write_file.write(new_line + '\n')
read_file.close()
write_file.close()

def main():
file_name = raw_input('What file do you want to open? ')
multiplier = multiply.GetUserNumber()
MultiplyNumbersInFile(file_name, multiplier)

if __name__ == '__main__':
main()

What I am doing in IDLE:

What file do you want to open? recipe.txt
Enter a multiplier: 2

The file that is actually created in my directory is still named recipe;
however, the file type is now TXT2 File. How do I make it so I am updating
the file name to recipe2 instead of the file type?


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


Re: [Tutor] Writing to a file/changing the file name

2012-02-22 Thread Christian Witts

On 2012/02/23 07:04 AM, Michael Lewis wrote:

Hi everyone,

I have a program where I open a file (recipe.txt), I read that file 
and write it to another file. I am doing some multiplying of numbers 
in between; however, my question is, when I name the file I am writing 
to, the file extension is changed, but the file name is not. What am I 
doing wrong?


Code:

import Homework5_1 as multiply

def MultiplyNumbersInFile(file_name, multiplier):
'''Open file/read file/write new file that doubles all int's in the
read file'''
try:
read_file = open(file_name)
except IOError:
print I can't find file: , file_name
return
new_file_name = file_name + '2'
try:
write_file = open(new_file_name, 'w')
except IOError:
read_file.close()
print I can't open file: , new_file_name
return
for line in read_file:
new_line = line.split()
new_line = ''.join(multiply.MultiplyText(new_line, multiplier))
write_file.write(new_line + '\n')
read_file.close()
write_file.close()

def main():
file_name = raw_input('What file do you want to open? ')
multiplier = multiply.GetUserNumber()
MultiplyNumbersInFile(file_name, multiplier)

if __name__ == '__main__':
main()

What I am doing in IDLE:

What file do you want to open? recipe.txt
Enter a multiplier: 2

The file that is actually created in my directory is still named 
recipe; however, the file type is now TXT2 File. How do I make it so I 
am updating the file name to recipe2 instead of the file type?



--
Michael J. Lewis



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
That's because your `file_name` variable contains the file name and 
extension.  You will need to split it into it's component pieces and 
then put it back together once you've changed the name, and for that you 
can use os.path.splitext


 import os
 filename, extension = os.path.splitext('recipe.txt')
 print (filename, extension)
('recipe', '.txt')
 new_filename = filename + '2' + extension
 print new_filename
'recipe2.txt'

--

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


Re: [Tutor] help writing functions

2012-02-22 Thread Andreas Perstinger

On 2012-02-23 01:59, Saad Javed wrote:

I am learning python and need guidance for writing some code. I've written
a simple program (with pointers from people) that parses an tv show xml
feed and prints their values in plain text after performing some string
operations.

[CODE]feed = urllib.urlopen(rssPage) #rssPage: address of xml feed

  ^^

[snip]


Running this code returns [B]None[/B].

^^^

This is not a web forum, so please post only in plain text.

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