Re: [Tutor] Reading and Manipulating XML Data

2009-07-25 Thread Alan Gauld


"Luis Galvan"  wrote

little foggy to me, which is where I need help.  The 'net always gives me 
an
exaggerated technical answer that is simply way over my head, so I'm 
asking,
does parsing mean to read and manipulate data?  If not, can someone 
provide

an answer in lay man's terms?


Others are better qualified than me to answer this but I'll have a
go anyway... Parsing is about taking raw datya and making
sense of it.. To try to turn a stream of data into meaningful
tokens or values. The stream needs to be in a clearly defined
structure (such as XML or a programming language grammar).
The parser reads the stream and breaks it into meaningful values,
such as tags etc for XML. It will usually build these up as a tree
structure so that you can navigate the tree to locate sopecific
bits of information. Thats as simple as I can describe it. If that's
too basic come back with more specific questions.


The last part of my question brings me back to the first part of this
message.  I can't seem to find any documentation on the internet that is
ideal to the beginning programmer regarding XML parsing.


Have you read the ElementTree tutorial by Fred Lundh?
Its fairly comprehensive and etree comes as opart of the
standard Python library. I'd certainly recommend etree over minidom!

http://effbot.org/zone/element-index.htm


...what are some decent python xml parsing guides out
there?  Any help is much appreciated!


You could try reading Text Processing in Python which is a book
but also available online at:

http://gnosis.cx/TPiP/

HTH,


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



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


Re: [Tutor] Need to be pointed in the right direction for fileorganisation.

2009-07-25 Thread Alan Gauld

"Mac Ryan"  wrote


While I am working my way up to a more pythonic and cleaner style in
the code, one thing that I have very confused ideas about is how I
should organise my code, in terms of classes and files.


I don't think there is any definitive answer.

- Put reusable components into modules.

- Don't necessarily create a module per class, but rather gather 
 related classes into a single module.


- Build modules "bottom up" so that depenedencies tend to 
 go one way, with higher level modules importing lower level ones.


Beyond that there are many different approaches to organisation.
They all have strengths and weaknesses.

The good news is that Python is such a high level language 
that you rarely have projects with so many modules that you 
need to create sophisticated directory structures. Usually 
everything can fit in one project folder. (Zope, Django etc being 
good examples of exceptions! :-)


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

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


Re: [Tutor] What kind of number is this

2009-07-25 Thread Dave Angel

Emad Nawfal (9E'/ FHAD) wrote:

Hi Tutors,
I have a bunch of text files that have many occurrences like the following
which I believe, given the context,  are numbers:

١٨٧٢

٥٧

 ٢٠٠٨

etc.

So, can somebody please explain what kind of numbers these are, and how I
can get the original numbers back. The files are in Arabic and were
downloaded from an Arabic website.
I'm running python2.6 on Ubuntu 9.04

  
Those are standard html encodings for some Unicode characters. Skipper 
has identified one of them as the digit '1' written in Arabic.  I 
presume the others will also be recognizable to you, since you 
apparently know Arabic.  The following text should be copied to a flie 
with extension .html   Then you run that in a browser, to see the 
characters.


DaveA





Test Arabic Characters


  
Table of characters 
1632 - ٠
1633 - ١
1634 - ٢
1635 - ٣
1636 - ٤
1637 - ٥
1638 - ٦
1639 - ٧
1640 - ٨
1641 - ٩
  



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


Re: [Tutor] Syntax Problem

2009-07-25 Thread Dave Angel

Jesse Harris wrote:

for d in Decks.all(): #loop thru all available decks
  self.response.out.write(''+d.name) 
  self.response.out.write(''+d.description)

self.response.out.write('')
self.response.out.write('')

: invalid syntax (main.py, line 206)

  args =
('invalid syntax', (r'C:\Program Files\Google\google_appengine\bangagears2\main.py', 206, 78, 
"
\t\tself.response.out.write(''+d.description)\n"))

  filename =
r'C:\Program Files\Google\google_appengine\bangagears2\main.py'

  lineno =
206

  message =
''

  msg =
'invalid syntax'

  offset =
78

  print_file_and_line =
None

  text =
"
\t\tself.response.out.write(''+d.description)\n"



  

There are so many things wrong I'm not sure where to begin.

This excerpt of code isn't nearly enough to compile, since it references 
lots of symbols not defined.  And it's not formatted the same as your 
original.  Your original definitely had tabs in it, as well as the 
normal spaces for indenting, which is asking for trouble.  You shouldn't 
use the name 'self' when you're not inside a method definition (it's not 
an error, but it is sure confusing).



If I take my best guess at some class and method definitions, and paste 
this fragment into a method of a class, and fix the indenting to what I 
might guess you were planning, it compiles and runs without problems.  
But I expected that, since the error is supposed to be in column 78, and 
you didn't have that many columns in your posting.  Even if I add back 
in the two tabs you omitted, and count them as eight characters each, 
we're still ten characters short.


Finally the error line displayed is not included in your excerpt.  Since 
the error message used ellipses in its quoting of the line, we can't see 
it all.  But if I had to guess, I'd say it was a case of mismatched 
quotation marks.  Or two lines combined together (note the two 
occurrences of self.response.out.write() )


DaveA

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


Re: [Tutor] Reading Data From File

2009-07-25 Thread Dave Angel

Chris Castillo wrote:

Okay I really need help with the program I am writing. I've can't seem to
figure out what I need to do and have tried several different methods.

I need to read in a text file in python that contains the following:

Student Name  ( could be unknown amount in file )
Numeric Grade  ( could be unknown amount in file also )
Numeric Grade
Numeric Grade
0 (zero value to terminate and move on to next student and their grades)

I need to print the following to the screen:
Student NameNumeric Grade, Numeric Grade, Numeric grade, etc.. - ( then
A, B C, D, or F average )

PLEASE HELP ME. I need to put the grades into a list and process each
student's grades before processing the next student's grades so that I can
print each Name, their grades, and average on the same line ( like above ).
Thanks

  
Generally, when I help someone with his homework, I expect him to have 
put some visible effort into solving the problem.


So you've tried several different methods.  Post the code from the most 
likely one of them, with a description of why it isn't doing what you 
needed, and one of us will probably be able to give you a hint to get 
past the trouble spot.


Don't post generalities, but actual code.  The whole thing should be 
less than a dozen lines.


DaveA

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


Re: [Tutor] What kind of number is this

2009-07-25 Thread عماد نوفل
On 7/25/09, Dave Angel  wrote:
> Emad Nawfal (9E'/ FHAD) wrote:
>> Hi Tutors,
>> I have a bunch of text files that have many occurrences like the following
>> which I believe, given the context,  are numbers:
>>
>> ١٨٧٢
>>
>> ٥٧
>>
>>  ٢٠٠٨
>>
>> etc.
>>
>> So, can somebody please explain what kind of numbers these are, and how I
>> can get the original numbers back. The files are in Arabic and were
>> downloaded from an Arabic website.
>> I'm running python2.6 on Ubuntu 9.04
>>
>>
> Those are standard html encodings for some Unicode characters. Skipper
> has identified one of them as the digit '1' written in Arabic.  I
> presume the others will also be recognizable to you, since you
> apparently know Arabic.  The following text should be copied to a flie
> with extension .html   Then you run that in a browser, to see the
> characters.
>
> DaveA
>
> 
>
> 
> 
> Test Arabic Characters
> 
> 
>
> Table of characters 
> 1632 - ٠
> 1633 - ١
> 1634 - ٢
> 1635 - ٣
> 1636 - ٤
> 1637 - ٥
> 1638 - ٦
> 1639 - ٧
> 1640 - ٨
> 1641 - ٩
>
> 
> 
>
>

Thank you very much Skipper and Dave.  Your replies have been very useful.
-- 
لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه
كالحقيقة.محمد الغزالي
"No victim has ever been more repressed and alienated than the truth"

Emad Soliman Nawfal
Indiana University, Bloomington

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


[Tutor] import rsvg

2009-07-25 Thread davidwilson
Hello,
I have searched high and low but for the life of me I am unable to locate this 
module.

>>> import cairo
>>> import rsvg
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named rsvg
>>> 


Basically from my previous post I would like to now manipulate the SVG files 
and export them as PNG. I am following the 
http://guillaume.segu.in/blog/code/43/svg-to-png/ post.

Is there an up to date method of doing this?

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


Re: [Tutor] import rsvg

2009-07-25 Thread Norman Khine
maybe because you need to install Gnome-Python

On Sat, Jul 25, 2009 at 1:36 PM,  wrote:
> Hello,
> I have searched high and low but for the life of me I am unable to locate 
> this module.
>
 import cairo
 import rsvg
> Traceback (most recent call last):
>  File "", line 1, in 
> ImportError: No module named rsvg

>
>
> Basically from my previous post I would like to now manipulate the SVG files 
> and export them as PNG. I am following the 
> http://guillaume.segu.in/blog/code/43/svg-to-png/ post.
>
> Is there an up to date method of doing this?
>
> Dave
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reading Data From File

2009-07-25 Thread bob gailer

I concur with wesley and dave re homework.

Some questions to consider:

do you know how to open a file?

do you know how to read a line from an opened file?

do you know how to incorporate reading lines in a loop?

do you know how to determine whether a character is "numeric"?

do you know how to print a line?

what is the criteria for determining A, B C, D, or F average?

--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how to get blank value

2009-07-25 Thread amrita
Hi,

I have a file having lines:-

48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
85 ALA H = 8.60 N =  CA =  HA = 4.65 C =

Now i want to make two another file in which i want to put those lines for
which C is missing and another one for which N,CA and C all are missing,

With these commands:-

import re
f = open('chem.txt')
for line in f:
 if re.search('C = ',line):
print line

I am getting those lines for which C value is there but how to get those
one for which it doesn't have any value, i did google search but still i
am not getting.

Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA

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


Re: [Tutor] how to get blank value

2009-07-25 Thread Alan Gauld


 wrote 


With these commands:-

import re
f = open('chem.txt')
for line in f:
if re.search('C = ',line):
   print line

I am getting those lines for which C value is there but how to get those
one for which it doesn't have any value, i did google search but still i
am not getting.


Don;t do a Google search, just read the re documentation, 
including the HowTo, looking for how to detect the 
end of a line.


Alan G.

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


Re: [Tutor] What kind of number is this

2009-07-25 Thread Mark Tolonen


"Emad Nawfal (عماد نوفل)"  wrote in message 
news:652641e90907250514m1566287aq75f675fd63360...@mail.gmail.com...

On 7/25/09, Dave Angel  wrote:

Emad Nawfal (9E'/ FHAD) wrote:

Hi Tutors,
I have a bunch of text files that have many occurrences like the 
following

which I believe, given the context,  are numbers:

١٨٧٢

٥٧

 ٢٠٠٨

etc.

So, can somebody please explain what kind of numbers these are, and how 
I

can get the original numbers back. The files are in Arabic and were
downloaded from an Arabic website.
I'm running python2.6 on Ubuntu 9.04



Those are standard html encodings for some Unicode characters. [snip]


You might find re.sub() useful to process your text files.  It will replace 
the HTML encodings with the actual Unicode character.



import re
data = 
u"١٨٧٢٥٧٢٠٠٨"

s = re.sub(r'&#(\d+);',lambda m: unichr(int(m.group(1))),data)
s

u'\u0661\u0668\u0667\u0662\u0665\u0667\u0662\u0660\u0660\u0668'

print s

1872572008

And this can be helpful for identifying Unicode characters:


import unicodedata
for c in s:

...  print unicodedata.name(c)
...
ARABIC-INDIC DIGIT ONE
ARABIC-INDIC DIGIT EIGHT
ARABIC-INDIC DIGIT SEVEN
ARABIC-INDIC DIGIT TWO
ARABIC-INDIC DIGIT FIVE
ARABIC-INDIC DIGIT SEVEN
ARABIC-INDIC DIGIT TWO
ARABIC-INDIC DIGIT ZERO
ARABIC-INDIC DIGIT ZERO
ARABIC-INDIC DIGIT EIGHT

-Mark


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


[Tutor] sqlite: don't understand a code snippet

2009-07-25 Thread David
Dear tutors,

I am trying to teach myself the way Python's works with databases.
I decided to start with SQLite, and am looking at Summerfield's
'Programming in Python 3'.
I got a code snippet that I don't fully understand (the comments are mine):


def get_and_set_director(db, director):
# try to fetch existing director ID from db
director_id = get_director_id(db, director)
# if director ID was found in db, return ID
if director_id is not None:
return director_id
cursor = db.cursor()
# insert new director record
cursor.execute("INSERT INTO directors (name) VALUES (?)",
   (director,))
db.commit()
# retrieve and return new director ID from db
return get_director_id(db, director)

Here is what I think is going on:

The function get_and_set_director() gets the director ID from the db
by calling the function get_director-id() and returns its value.

If the director ID is not in the db then, from outside the
get_and_set_director() function, the ID gets inserted to the db via
the commit() method. Finally, the director ID is returned (from the db)
by once again calling the get_director_id() function.

Question: where does a new the director ID come from?

Thanks for your directions!

David

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


Re: [Tutor] Need to be pointed in the right direction for file organisation.

2009-07-25 Thread Mac Ryan
Thank you Alan for the prompt reply,


> - Put reusable components into modules.

OK: the use of files as "libraries" is quite clear to me and indeed I
am already doing that. What is not clear is if I should _only_ put in
modules stuff that is reusable, or if there are other widely accepted
ways to user files.
For example, in the GTK application I am currently developing I have a
notebook widget (sort of tabbed windows which are visible only one at a
time). I was therefore thinking about separating the classes for each
"tabbed window" in different files, under the impression that this would
make the program faster / with a smaller memory footprint, as only the
needed file will be loaded into memory [In PHP you can reach quite a
gain in terms of speed if yo do so].
Would this be considered a proper way to code in python?

Another concern of mine was the readability of the source code, and I
was wondering indeed if there was a "pythonic style" that was commonly
understood as "the right one" [I'm thinking to those kind of guidelines
like "put the import directive at the top of the file", but for file
organisation]

> - Build modules "bottom up" so that depenedencies tend to 
>   go one way, with higher level modules importing lower level ones.

I'm not sure I got it completely, does this mean that the file structure
should be a hint of how dependency works, with ancestors nested in the
subfolders of the children classes or something similar?

Anyhow, thanks a lot for having answered so promptly! :)

Mac.

> > While I am working my way up to a more pythonic and cleaner style in
> > the code, one thing that I have very confused ideas about is how I
> > should organise my code, in terms of classes and files.
> 
> I don't think there is any definitive answer.
> 
> - Put reusable components into modules.
> 
> - Don't necessarily create a module per class, but rather gather 
>   related classes into a single module.
> 
> - Build modules "bottom up" so that depenedencies tend to 
>   go one way, with higher level modules importing lower level ones.
> 

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


Re: [Tutor] Reading Data From File

2009-07-25 Thread ctcast

grades = []
names = []
gradeTotal = 0
numStudents = 0

inputFile = open("input.txt", "r"

for line in inputFile:
if line.strip().isdigit():
grade = float(line)
if grade != 0.0:
gradeTotal += grade
grade = grades.append(grade)
else:
name = line.strip()
name = names.append(name)

This just loops over the entire file basically and just continually adds  
the grades to the grades list and names to the names list. How do I just  
process each student's set of grades before moving on to the next one  
(since there is a zero terminating value telling the loop that a new  
student and his or her grades are about to follow)


By the way I'm not worrying about determining the letter grade average  
right now, i'm importing a module I wrote after I figure this part out.


On Jul 25, 2009 8:34am, bob gailer  wrote:

I concur with wesley and dave re homework.





Some questions to consider:





do you know how to open a file?





do you know how to read a line from an opened file?





do you know how to incorporate reading lines in a loop?





do you know how to determine whether a character is "numeric"?





do you know how to print a line?





what is the criteria for determining A, BC, D, or F average?





--



Bob Gailer



Chapel Hill NC



919-636-4239


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


Re: [Tutor] sqlite: don't understand a code snippet

2009-07-25 Thread Rich Lovely
2009/7/25 David :
> Dear tutors,
>
> I am trying to teach myself the way Python's works with databases.
> I decided to start with SQLite, and am looking at Summerfield's
> 'Programming in Python 3'.
> I got a code snippet that I don't fully understand (the comments are mine):
>
>
> def get_and_set_director(db, director):
>    # try to fetch existing director ID from db
>    director_id = get_director_id(db, director)
>    # if director ID was found in db, return ID
>    if director_id is not None:
>    return director_id
> cursor = db.cursor()
> # insert new director record
> cursor.execute("INSERT INTO directors (name) VALUES (?)",
>               (director,))
> db.commit()
> # retrieve and return new director ID from db
> return get_director_id(db, director)
>
> Here is what I think is going on:
>
> The function get_and_set_director() gets the director ID from the db
> by calling the function get_director-id() and returns its value.
>
> If the director ID is not in the db then, from outside the
> get_and_set_director() function, the ID gets inserted to the db via
> the commit() method. Finally, the director ID is returned (from the db)
> by once again calling the get_director_id() function.
>
> Question: where does a new the director ID come from?
>
> Thanks for your directions!
>
> David
>
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

It sounds as if the directors table has an AUTO_INCREMENT column,
which will automatically assign itself the next value sequentially
when you insert an entry into the table.  i.e. The first inserted
entry gets an ID of 1, the next 2, and so on.  This is stored in a
column in the table.  The get_director_id(...) function will do
something like the following query:

cursor.execute("SELECT id FROM directors WHERE name == \"%s\"", (name,))

I don't know how well I've explained it, but this is the normal
technique for generating unique ids for rows in a database.

-- 
Rich "Roadie Rich" Lovely
There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need to be pointed in the right direction for file organisation.

2009-07-25 Thread Alan Gauld


"Mac Ryan"  wrote


time). I was therefore thinking about separating the classes for each
"tabbed window" in different files, under the impression that this would
make the program faster / with a smaller memory footprint, as only the
needed file will be loaded into memory 


The gains would be minimal, and its dcertainly not common practice. 
In fact having more modules loaded might even make performance 
worse! I'd certainly categorize that as premature optimisation!



Another concern of mine was the readability of the source code, and I
was wondering indeed if there was a "pythonic style" that was commonly
understood as "the right one" 


Not for file organisation. There is the package concept so if 
you have a lot of related modules you could create a package 
structure, but most of Python's organisation guidelines tend to 
focus on maximising reuse rather than organizing the current 
project, in my experience at least.


- Build modules "bottom up" so that depenedencies tend to 
  go one way, with higher level modules importing lower level ones.


I'm not sure I got it completely, does this mean that the file structure
should be a hint of how dependency works, 


No, just that you should try to keep low level functuions etc in 
separate files and have the higher level, more abstract modules 
import them. Rather than mixing low level, implementation 
dependant coded with more abstract - and therefore more portable

module code.

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

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


[Tutor] reading into a text file

2009-07-25 Thread keithabt
Hi I am trying to read a html document into a text file to looks at it for the 
purpose of spliting the data. I am not sure I am doing this right. I have my 
html 
document, my text file and a python script I called convt.py on the desktop in 
a 
folder. I opened up IDLE (python GUI) opened the folder on my desk top and then 
went to run module. I keep getting an error saying "No such file or 
directory: 'source.txt'
I am new to python so I really don't know if I am doing this right. Any 
suggestions?



#!/usr/bin/python
u=open("source.txt").read()
lines = u.split("")
print lines[1]

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


Re: [Tutor] reading into a text file

2009-07-25 Thread Alan Gauld

 wrote

Hi I am trying to read a html document into a text file 


Hi, welcome to the tutor list.

First thing to point out is that HTML files are just text files with 
a particular structure. But so far as reading them in Python 
goes they are no different to any other text file.


purpose of spliting the data. 


Now this is where it gets interesting, it depends what 
exactly you are trying to "split". What do you mean by
the "data"? If its the HTML elements there are specialised 
Python tools that will make this a lot easier. But if it is 
simply splitting into separate lines, read on...


I am not sure I am doing this right. I have my html 
document, my text file and a python script I called 
convt.py on the desktop 


Its usually a bad idea in Windows to do anythiong on 
the Desktop, keep that as a place for putting icons to 
launch programs. Put working files into separate project

folders.

in a folder. 


I assume this means a folder on your Desktop?

That's slightly better but still leaves problems because the 
true path to your folder is:


C:\Documents and Settings\YourName\Desktop\YourFolder

Which Windows tries to hide most of the time!

Personally I'd recommend creating a "Projects" or "Work"
folder at the top level of one of your drives (if you have more than one)
and moving your folder under that. Then the full path becomes

D:\Work\MyFolder

Which is a lot easier to deal with and less likely to run into Windows 
"cleverness" issues.


I opened up IDLE (python GUI) opened the folder on my desk top and then 
went to run module. 


OK, I'm still not 100% clear on what you are doing here but 
this is probably a good time to get to know the Windows 
command prompt. (Take a look at the box on the Getting Started 
topic in my tutorial for a brief intro.) Thats a better way to run your 
programs on real data IMHO.



I keep getting an error saying "No such file or directory: 'source.txt'


If you start a command prompt

Start->Run
Type CMD, Hit OK

At the prompt

C:\WINDOWS> or similar

type 


python myscript.py

It should now find it.

I am new to python so I really don't know if I am doing this right.  


#!/usr/bin/python
u=open("source.txt").read()
lines = u.split("")
print lines[1]


You are splitting by the sequence of .
That is each "line" starts with a paragraph tag followed immediately 
by a bold tag, is that really what you want? If so it looks fine.


You could modify your program so that it takes the filename at the 
command line, so you can process more than one file:


python myscript foo.html

or

python myscript.py bar.html

for example

HTH,


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

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


[Tutor] First code snipet

2009-07-25 Thread Darth Kaboda

I'm starting to learn Python as it seems to be adopted by many companies that 
I've been looking to apply to. I used the book Learning Phython to get the 
basics of the language and many of the gotcha's. I think I know enough of the 
basic features of the language to start playing around and can understand most 
code I've seen so far by looking at some of the posts here.

 

The one worry I have is not coding things the Phython way as I've been a Visual 
Basic programmer for so long and a C++ programmer before that. So would like to 
have people look at a simplistic class (shuffles lists of objects wrote it for 
shuffling cards but with Phython could be used for any "list" type object) I 
wrote to give me some feedback on the style of it.

 

Any feedback is appreciated.

 

Thanks,

Brian
import random

class shuffler(object):
def __init__(self):
self.rgen = random.Random()
def shuffle(self, inpile1, inpile2):
"""Function that shuffles two list of items."""
if self.rgen.randint(0,1):  #randomly decide which pile is shuffled 
down first
(pile1,pile2)=(inpile1,inpile2)
else:
(pile1,pile2)=(inpile2,inpile1)
pile1c = len(pile1)
pile2c = len(pile2)
rpile = pile1[0:0] #get blank copy of the passed in object types. 
Should allow user defined list type objects to work as well
while pile1c and pile2c:#while there are still items in both piles 
execute following logic
i = self.rgen.randint(1,4)  #to allow for human error get random 
offset of items to shuffle
if i > pile1c:  #ensure we don't go out of bounds for the pile
i = pile1c
for x in range(0,i):#append cards to the output pile and remove 
from shuffle pile
rpile.append(pile1.pop(0))
pile1c -= 1
i = self.rgen.randint(1,4)  #to allow for human error get random 
offset of items to shuffle
if i > pile2c:  #ensure we don't go out of bounds for the pile
i = pile2c
for x in range(0,i):#append cards to the output pile and remove 
from shuffle pile
rpile.append(pile2.pop(0))
pile2c -= 1
#check for which pile has left over items if any do
if pile1c:
rpile.extend(pile1)
elif pile2c:
rpile.extend(pile2)
return rpile
def shuffledeck(self, deck):
"""Function that shuffles a list type object"""
i = len(deck) #get length of the deck object to shuffle
cut = (i // 2) + self.rgen.choice(range(-4,5)) #find half way point of 
deck +/- human error factor
pile1 = deck[0:cut]
pile2 = deck[cut:]
return self.shuffle(pile1,pile2)

if __name__ == '__main__':
myshuffle = shuffler()
deck = range(1,53)
print deck
for i in range(1,5):
deck = myshuffle.shuffledeck(deck)
print deck

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


Re: [Tutor] Reading Data From File

2009-07-25 Thread Dave Angel

ctc...@gmail.com wrote:

grades = []
names = []
gradeTotal = 0
numStudents = 0

inputFile = open("input.txt", "r"

for line in inputFile:
if line.strip().isdigit():
grade = float(line)
if grade != 0.0:
gradeTotal += grade
grade = grades.append(grade)
else:
name = line.strip()
name = names.append(name)

This just loops over the entire file basically and just continually 
adds the grades to the grades list and names to the names list. How do 
I just process each student's set of grades before moving on to the 
next one (since there is a zero terminating value telling the loop 
that a new student and his or her grades are about to follow)


By the way I'm not worrying about determining the letter grade average 
right now, i'm importing a module I wrote after I figure this part out.


On Jul 25, 2009 8:34am, bob gailer  wrote:

I concur with wesley and dave re homework.



There are syntax errors of at least two kinds here.  The first is you're 
missing a trailing parenthesis.  And the second is you lost all your 
indentation when you retyped the code.  It'd really be better if you 
pasted the actual code instead.  Not much of a problem in this case, at 
least if I guess the same as you had, but in many cases the indentation 
*is* the problem.


Next problem is that you're assuming that list.append() returns 
something useful. It doesn't return anything, which is to say it returns 
"None."  So it's not useful to do:

grade = grades.append(grade)

just leave off the left half of that.  And likewise leave off the name=  
from the other call to append().


The next problem is that you have two independent lists, but no way to 
correlate which elements of one correspond to which elements of the 
other. So you have a choice to make.  Do you need all the data for 
post-processing, or is it enough that you print it out, and discard it 
afterwards?


I'll assume that you'd answer that it's enough to just be able to print 
it out.  In that case, you just need some well placed print statements.  
Each time you come to a line with a zero in it, you have enough 
information to print out one student's information.  And in this case, 
you don't need a list of students, just the name of the current one.


Do you expect any numbers to be non-integers?  I'd assume so because you 
used the float() function instead of int().  But isdigit() is going to 
be a problem if there's a decimal in there.


DaveA

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


[Tutor] Need to start learning again

2009-07-25 Thread Fred @ Mac
I started learning python, but then life got busy...  I need some help  
finding good resources to start learning again.


My main need for python at first would be to write small programs to  
perform system commands.  Like moving files around, copying or  
deleting files, and perhaps some simple interface construction so I  
can create a window to show the status of the little programs i plan  
to write.


Any help would be appreciated.


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


Re: [Tutor] Need to start learning again

2009-07-25 Thread Luis Galvan
Check out thenewboston's video tutorials at Youtube:

http://www.youtube.com/view_play_list?p=EA1FEF17E1E5C0DA

They're fairly recent and they definitely got me started with learning the
syntax.  After you're through with those, he also has a series on wxPython.

A couple ebooks you'd be interested in would be Dive into Python or A Byte
of Python, both very thorough and descriptive, the latter being a bit easier
to newer programmers.

A great book might consider purchasing would be Wesley Chun's Core Python
Programming.

This is only a slice of the cake though, try Googling around for more
resources.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] First code snipet

2009-07-25 Thread Andreas Kostyrka
Some things:

1) It's Python, not Phython.
2) Slightly shorter solution to your problem:

import random

input = range(53)
random.shuffle(input)
print input

3) The important part here is that reimplementing something that is in
the standard library does not make sense usually.

4) A more sensible implementation of shuffle comes directly out of
random.py:

def shuffle(self, x, random=None, int=int):
"""x, random=random.random -> shuffle list x in place; return
None.

Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.
"""

if random is None:
random = self.random
for i in reversed(xrange(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = int(random() * (i+1))
x[i], x[j] = x[j], x[i]

Notice that it is not exactly optimal, one could easily replace the
reversed(xrange()) expression with a 3 parameter version of xrange:
for i in xrange(len(x) - 1, 0, -1):

Andreas



Am Samstag, den 25.07.2009, 17:15 -0700 schrieb Darth Kaboda:
> I'm starting to learn Python as it seems to be adopted by many
> companies that I've been looking to apply to. I used the book Learning
> Phython to get the basics of the language and many of the gotcha's. I
> think I know enough of the basic features of the language to start
> playing around and can understand most code I've seen so far by
> looking at some of the posts here.
>  
> The one worry I have is not coding things the Phython way as I've been
> a Visual Basic programmer for so long and a C++ programmer before
> that. So would like to have people look at a simplistic class
> (shuffles lists of objects wrote it for shuffling cards but
> with Phython could be used for any "list" type object) I wrote to give
> me some feedback on the style of it.
>  
> Any feedback is appreciated.
>  
> Thanks,
> Brian
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


signature.asc
Description: Dies ist ein digital signierter Nachrichtenteil
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] First code snipet

2009-07-25 Thread Darth Kaboda


 

> Subject: Re: [Tutor] First code snipet
> From: andr...@kostyrka.org
> To: darthkab...@msn.com
> CC: tutor@python.org
> Date: Sun, 26 Jul 2009 03:02:27 +0200
> 
> Some things:
> 
> 1) It's Python, not Phython.
> 2) Slightly shorter solution to your problem:
> 
> import random
> 
> input = range(53)
> random.shuffle(input)
> print input
> 
> 3) The important part here is that reimplementing something that is in
> the standard library does not make sense usually.
> 
> 4) A more sensible implementation of shuffle comes directly out of
> random.py:
> 
> def shuffle(self, x, random=None, int=int):
> """x, random=random.random -> shuffle list x in place; return
> None.
> 
> Optional arg random is a 0-argument function returning a random
> float in [0.0, 1.0); by default, the standard random.random.
> """
> 
> if random is None:
> random = self.random
> for i in reversed(xrange(1, len(x))):
> # pick an element in x[:i+1] with which to exchange x[i]
> j = int(random() * (i+1))
> x[i], x[j] = x[j], x[i]
> 
> Notice that it is not exactly optimal, one could easily replace the
> reversed(xrange()) expression with a 3 parameter version of xrange:
> for i in xrange(len(x) - 1, 0, -1):
> 
> Andreas
> 
> 
> 
> Am Samstag, den 25.07.2009, 17:15 -0700 schrieb Darth Kaboda:
> > I'm starting to learn Python as it seems to be adopted by many
> > companies that I've been looking to apply to. I used the book Learning
> > Phython to get the basics of the language and many of the gotcha's. I
> > think I know enough of the basic features of the language to start
> > playing around and can understand most code I've seen so far by
> > looking at some of the posts here.
> > 
> > The one worry I have is not coding things the Phython way as I've been
> > a Visual Basic programmer for so long and a C++ programmer before
> > that. So would like to have people look at a simplistic class
> > (shuffles lists of objects wrote it for shuffling cards but
> > with Phython could be used for any "list" type object) I wrote to give
> > me some feedback on the style of it.
> > 
> > Any feedback is appreciated.
> > 
> > Thanks,
> > Brian
> > ___
> > Tutor maillist - Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor

 

Thanks for the correction not sure why I typed it that way after typing it 
correctly in the first sentence, must have wondered off somewhere in my mind I 
guess. 

 

Oops I guess I should have also mentioned what I was trying to accomplish with 
this class. I wanted to mimic how a deck of cards get's shuffled in the real 
world. i.e. split the deck and shuffle the two halves together. 

 

Brian


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


Re: [Tutor] Need to start learning again

2009-07-25 Thread Wayne
On Sat, Jul 25, 2009 at 6:24 PM, Fred @ Mac  wrote:

> I started learning python, but then life got busy...  I need some help
> finding good resources to start learning again.
>

I learned everything I know from Google ;) or at least sources provided by
Google. I'd also recommend Python for System Administrators by Noah Gift and
Jeremy Jones. If it's available at your local public library, I'd check it
out (and well worth the $15 price used).


>
> My main need for python at first would be to write small programs to
> perform system commands.  Like moving files around, copying or deleting
> files, and perhaps some simple interface construction so I can create a
> window to show the status of the little programs i plan to write.


Python for Sys admins covers all of the above. If you want a very simple
interface, I'd go with Tkinter. It's a lot easier to use than some of the
bigger GUIs, like GTK, but it also sacrifices a lot of features to go with
that simplicity.

A couple  of folks on this mailing list have python tutorials that are
certainly worth a read.

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


Re: [Tutor] First code snipet

2009-07-25 Thread Wayne
On Sat, Jul 25, 2009 at 7:15 PM, Darth Kaboda  wrote:

>  I'm starting to learn Python as it seems to be adopted by many companies
> that I've been looking to apply to. I used the book Learning Phython to get
> the basics of the language and many of the gotcha's. I think I know enough
> of the basic features of the language to start playing around and can
> understand most code I've seen so far by looking at some of the posts here.
>
> The one worry I have is not coding things the Phython way as I've been a
> Visual Basic programmer for so long and a C++ programmer before that. So
> would like to have people look at a simplistic class (shuffles lists of
> objects wrote it for shuffling cards but with Phython could be used for any
> "list" type object) I wrote to give me some feedback on the style of it.
>
> Any feedback is appreciated.
>

There's a spot in your code that could be turned into a function. I'm not
sure what you'd call it, but where you "lay down" 1-4 cards. Since you're
doing the same thing for each stack, you may as well turn it into a function
and just call it for each stack.

Pretty cool idea for something to do, though.

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


Re: [Tutor] Need to start learning again

2009-07-25 Thread Che M



> From: fredp...@mac.com
> To: tutor@python.org
> Date: Sat, 25 Jul 2009 16:24:13 -0700
> Subject: [Tutor] Need to start learning again
> 
> I started learning python, but then life got busy...  I need some help  
> finding good resources to start learning again.
> 
> My main need for python at first would be to write small programs to  
> perform system commands.  Like moving files around, copying or  
> deleting files, and perhaps some simple interface construction so I  
> can create a window to show the status of the little programs i plan  
> to write.
> 
> Any help would be appreciated.

For file manipulation, take a look at this:
http://effbot.org/librarybook/os.htm

And yes, Tkinter probably would make things easier for a simple GUI.

_
Windows Live™ Hotmail®: Celebrate the moment with your favorite sports pics. 
Check it out.
http://www.windowslive.com/Online/Hotmail/Campaign/QuickAdd?ocid=TXT_TAGLM_WL_QA_HM_sports_photos_072009&cat=sports___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor