Re: [Tutor] First code snipet

2009-07-26 Thread Alan Gauld


"Darth Kaboda"  wrote


The one worry I have is not coding things the Phython way
...So would like to have people look at a simplistic class




rpile = pile1[0:0] #get blank copy of the passed in object types.


This will return an empty list regardless of the type of passed in object.
The only possible difference is a subclassed list but if its been well
implemented you shouldn't care! I'd just go with:

rpile = []


for x in range(0,i):


Its usual in Python to omit the first 0

for x in  range(i):

is all that's needed.

Otherwise it looks OK to me.

You might be able to leverage the stdlib more effectively, for
example there is a shuffle type menthod for randomising a
single list. And zip() to merge two lists...

--
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] Reading Data From File

2009-07-26 Thread Chris Castillo
ya i was kind of in a hurry composing the email earlier. sorry for the
typos and misunderstanding. This is what I actually have.

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)


So even If I take the stuff out that you said, My structure still
wouldn't be right because I'm processing everything all at once with
no way to reference any of the grades with the student. How do I
structure this differently to do that? That's what I'm having trouble
with.

On 7/25/09, Dave Angel  wrote:
> 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


Re: [Tutor] Reading Data From File

2009-07-26 Thread Dave Angel

Chris Castillo wrote:

ya i was kind of in a hurry composing the email earlier. sorry for the
typos and misunderstanding. This is what I actually have.

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)


So even If I take the stuff out that you said, My structure still
wouldn't be right because I'm processing everything all at once with
no way to reference any of the grades with the student. How do I
structure this differently to do that? That's what I'm having trouble
with.

On 7/25/09, Dave Angel  wrote:
  

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



(In a mailing list like this one, putting a response at the top of your 
message is called top-posting, and makes it harder for the next person 
to see the sequence of messages.)


As I said before:
   *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 tried to assume an answer, but it looks like you stopped reading 
before that point.  So I'll try again, with a little more detail.


Each time you come to a line with a zero in it, you have enough 
information to print out one student's information.  You know the 
current student, you know all his scores.  So you could print it out at 
that point in the loop, rather than waiting till the entire program is past.


If you're not sure what I'm talking about, first put in a test for the 0 
line.  Add in a single print that prints out name and grades at that 
point.  You do know that you can print a list, just the same as any 
other variable?



Once you see you have enough data at that point, you'll have to make a 
minor change to eliminate this student's data from getting printed again 
for the next one.


Then it's just a question of formatting the print nicely.  So you 
replace the single print with a function call, passing it the name and 
grades, and format the information in that function.


And if you won't try what I said, then at least answer the question.

DaveA

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


[Tutor] Need help in making this code more pythonic

2009-07-26 Thread ammar azif
Hello,

I need some suggestions on how to make this code pythonic. The program 
basically runs a simulation of an object that moves on a 2D plane. The object 
keeps on moving from its current coordinate to  randomly picked adjacent 
coordinates with the object is not allowed to move move to a previously covered 
coordinate point as the rule. If the object is unable to move the program will 
terminate. Some of the concerns I have in mind is the code in the move method 
in Person class. I am sure there are some built-in methods or features in 
python that I could use to improve the implementation of that method. Hope you 
guys can enlighten me.





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


Re: [Tutor] Need help in making this code more pythonic

2009-07-26 Thread ammar azif
Sorry I forgot to attach the code file.
Here it is.


--- On Sun, 7/26/09, ammar azif  wrote:

From: ammar azif 
Subject: [Tutor] Need help in making this code more pythonic
To: tutor@python.org
Date: Sunday, July 26, 2009, 6:23 AM

Hello,

I need some suggestions on how to make this code pythonic. The program 
basically runs a simulation of an object that moves on a 2D plane. The object 
keeps on moving from its current coordinate to  randomly picked adjacent 
coordinates with the object is not allowed to move move to a previously covered 
coordinate point as the rule. If the object is unable to move the program will 
terminate. Some of the concerns I have in mind is the code in the move method 
in Person class. I am sure there are some built-in methods or features in 
python that I could use to improve the implementation of that method. Hope you 
guys can enlighten me.





  
-Inline Attachment Follows-

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



  import random
import time
class Person(object):
def __init__(self, position,length,width):
self.positions = {position:None} #coordinates covered 
self.position = position #current coordinate
self.length = length # world length
self.width= width #world width


def move(self):
x = self.position[0]
y = self.position[1]
#set dead end 
cannot_move = True
#list of potential next coordinates
potential_positions =[]
if x+1>=0 and x+1<=self.length-1:
if not self.positions.has_key((x+1,y)):
cannot_move = False
potential_positions.append((x+1,y))
   
if x-1>=0 and x-1<=self.length-1:
if not self.positions.has_key((x-1,y)):
cannot_move = False
potential_positions.append((x-1,y))
 
if y-1>=0 and y-1<=self.width-1:
if not self.positions.has_key((x,y-1)):
cannot_move = False
potential_positions.append((x,y-1))
 
if y+1>=0 and y+1<=self.width-1:
if not self.positions.has_key((x,y+1)):
cannot_move = False
potential_positions.append((x,y+1))


if cannot_move :
#return value that signifies the person cannot move
return False
else:
#randomly pick a coordinate from list of potential coordinates
index=random.randrange(len(potential_positions))
self.positions[potential_positions[index]]=None
self.position = potential_positions[index]
return True


width = 10
length = 10
person = Person((0,0),length,width)
plots = {(0,0):None}
print 'Initial Positions Covered Count:'+str(len(person.positions))
print 'Moving!'


while person.move():
string = 'Current position:' + str(person.position)+'Total covered:'+str(len(person.positions))+'\n'

for x in range(width):
for y in range(length):

if person.positions.has_key((x,y)):
string+='X'
else:
string+=' '
if y==length-1:
string+='\n'
print string

time.sleep(1)

print 'Cannot move!'
print person.positions












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


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

2009-07-26 Thread David
Rich,

thanks a lot -- that was the problem.

David

Rich Lovely wrote:
> 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  -  Tutor@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.
>
>   

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


Re: [Tutor] First code snipet

2009-07-26 Thread Dave Angel

Darth Kaboda wrote:
 

  

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


 

  
Good point.  It is important to state your goal for the code, preferably 
in comments in your code, as well as in the message asking us the 
question.  Suggest you include a doc-string for each class and method 
declaration.


But it's important to tell us how you expect to use it, as well.  If 
it's for your own learning, then it's pretty good as it is.  But if you 
intend to show it to prospective employers, there are a lot of ways to 
clean it up.



So...

Unlike Java, not everything needs to be in a class.  This shuffler class 
accomplishes nothing that the module doesn't already do.  The only 
instance attribute you use is rgen, and that could just as readily have 
been a global (visible within the entire module).


Naming is important.  I think I would have factored it into three 
functions  cut() and ripple().  shuffle() simply calls cut(), then ripple().


You need to know the library better.  Andreas already mentioned the std 
library random.shuffle(), and you correctly explained why you didn't use 
it.  But there are other library functions that would make your code 
more concise, more readable, and maybe faster.


Starting with shuffle() (which I'd call ripple())

Because Python makes it easy to swap two variables in-place, it's common 
to swap arguments directly, rather than copy them to local attributes.  
So I'd replace the first 4 lines with:
  if self.rgen.randint(0,1):  #randomly decide which pile is shuffled 
down first

   inpile2, inpile1 = inpile1, inpile2

len() is very fast, so there's no need for a separate variable to keep 
track of the lengths of inpile1 and inpile2.  So eliminate all refs to 
pile1c and pile2.  In the while, just use

   while  len(inpile1) and len(inpile2):

Lists have no type associated with them.  Each object in a list has its 
own type.  So there's no meaning to constructing an empty list out of 
another one.

rpile = []

pop(0) is slow, compared with pop(-1).  If you used the latter, you 
would have to do a reverse on the list when you were done to keep the 
realism.  And that would make the code less readable.  So I think this 
is an unnecessary optimization.  But keep it in mind if you're ever 
dealing with thousands of items in a list. Peeling them off from the 
front one at a time will be slow.


The logic of popping a random number of cards from one list, and 
appending them to the result could be done the same way you do the 
cut(), using sli

Re: [Tutor] First code snipet

2009-07-26 Thread Alan Gauld


"Dave Angel"  wrote


len() is very fast, so there's no need for a separate variable to keep 
track of the lengths of inpile1 and inpile2.  So eliminate all refs to 
pile1c and pile2.  In the while, just use

   while  len(inpile1) and len(inpile2):


Or even simpler:

while inpile1 and inpile2:

An empty list is false too.

pop(0) is slow, compared with pop(-1).  


I didn't know that, but timing seems to suggest about 50% slower.
Interesting.

Alan G.

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


Re: [Tutor] Need help in making this code more pythonic

2009-07-26 Thread Rich Lovely
> --- On Sun, 7/26/09, ammar azif  wrote:
>
> From: ammar azif 
> Subject: [Tutor] Need help in making this code more pythonic
> To: tutor@python.org
> Date: Sunday, July 26, 2009, 6:23 AM
>
> Hello,
>
> I need some suggestions on how to make this code pythonic. The program
> basically runs a simulation of an object that moves on a 2D plane. The
> object keeps on moving from its current coordinate to  randomly picked
> adjacent coordinates with the object is not allowed to move move to a
> previously covered coordinate point as the rule. If the object is unable to
> move the program will terminate. Some of the concerns I have in mind is the
> code in the move method in Person class. I am sure there are some built-in
> methods or features in python that I could use to improve the implementation
> of that method. Hope you guys can enlighten me.
>
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

A Couple of pointers:

Rather than having a dict with all values == None, you can use a set
(which is effectively the same thing, but looks cleaner and is easier
to read).

Us the "k in d" operator rather than d.has_key(k)


x = position[0]
y = position[1]

is more pythonically written

x,y = position

using tuple unpacking.


rather than using
cannot_move = True
and then
if cannot_move:

You'd be more pythonic to use

if not potential_positions:

An empty list is false in a boolean context, a list with one or more
items is true.

Rather than using random.rand_int(len(...)) to generate an index, you
can go straight to the result by using random.choice(...)


You might also want to add some docstrings to your class and its move
method, so that you can tell at a glance what the class does.  A
docstring is simple a string on the first (non-blank) line after the
definition:

def move(self):
"Moves person one space in a random direction.  It is not
permitted to move to a previous occupied position"

Finally, you might want to put the code doing the actual work into a
"if __name__ == "__main__": block, so that you can import the script
as a module, and not get extra output. Take a look at some of the
files in the standard library to see what I mean.

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


[Tutor] renaming files within a directory

2009-07-26 Thread davidwilson
Hello,
I have a directory containing svg/Flag_of_United_States.svg etc...


Flag_of_the_Seychelles.svg
Flag_of_the_Solomon_Islands.svg
Flag_of_the_United_Arab_Emirates.svg
Flag_of_the_United_Kingdom.svg
Flag_of_the_United_States.svg
Flag_of_the_Vatican_City.svg


Also I have a CSV file like

"us", "United States"
"es", "Spain"



How can I rename the svg files so that they become:

flag-us.svg
flag-es.svg

etc..

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


Re: [Tutor] renaming files within a directory

2009-07-26 Thread Tim Golden

davidwil...@safe-mail.net wrote:

Hello,
I have a directory containing svg/Flag_of_United_States.svg etc...


Flag_of_the_Seychelles.svg
Flag_of_the_Solomon_Islands.svg
Flag_of_the_United_Arab_Emirates.svg
Flag_of_the_United_Kingdom.svg
Flag_of_the_United_States.svg
Flag_of_the_Vatican_City.svg


Also I have a CSV file like

"us", "United States"
"es", "Spain"



How can I rename the svg files so that they become:

flag-us.svg
flag-es.svg



This is one of those ones where it helps if you have
a go first and tell us how far you got, or where
the problem lies. Otherwise you're likely to get
a lot of sarcastically helpful replies along the lines
of:

move Flag_of_the_Seychelles.svg flag-sc.svg


To get you started if you're nowhere at the moment,
you want to create a dictionary from your csv which maps 
the long name to the short name so that can then

parse the file name to find the long name, use the
dictionary to find the short name, and then issue
a rename command to the new name.

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


Re: [Tutor] renaming files within a directory

2009-07-26 Thread davidwilson
OK, I know that.

Here is what I have so far, but I get stuck on the mapping of the filename with 
the csv file.

>>> import os
>>> files = [file for file in os.listdir(os.getcwd()) if file.endswith('svg')]
>>> files
['Flag_of_Abkhazia.svg', 'Flag_of_Afghanistan.svg', 'Flag_of_Albania.svg', 
'Flag_of_Algeria.svg', 'Flag_of_Andorra.svg', 'Flag_of_Angola.svg', 
'Flag_of_Antigua_and_Barbuda.svg', 'Flag_of_Argentina.svg', 
'Flag_of_Armenia.svg', 'Flag_of_Australia.svg']

>>> import csv
>>> reader = csv.reader(open("country.csv"))
>>> for row in reader:
... print row   

['"km";"Comoros"']
['"dj";"Djibouti"']
['"er";"Eritrea"']
['"et";"Ethiopia"']


Here is where I am at.
Not sure how to map the two.

Dave





 Original Message 
From: Tim Golden 
Apparently from: tutor-bounces+davidwilson=safe-mail@python.org
To: 
Cc: tutor@python.org
Subject: Re: [Tutor] renaming files within a directory
Date: Sun, 26 Jul 2009 16:13:38 +0100

> davidwil...@safe-mail.net wrote:
> > Hello,
> > I have a directory containing svg/Flag_of_United_States.svg etc...
> > 
> > 
> > Flag_of_the_Seychelles.svg
> > Flag_of_the_Solomon_Islands.svg
> > Flag_of_the_United_Arab_Emirates.svg
> > Flag_of_the_United_Kingdom.svg
> > Flag_of_the_United_States.svg
> > Flag_of_the_Vatican_City.svg
> > 
> > 
> > Also I have a CSV file like
> > 
> > "us", "United States"
> > "es", "Spain"
> > 
> > 
> > 
> > How can I rename the svg files so that they become:
> > 
> > flag-us.svg
> > flag-es.svg
> 
> 
> This is one of those ones where it helps if you have
> a go first and tell us how far you got, or where
> the problem lies. Otherwise you're likely to get
> a lot of sarcastically helpful replies along the lines
> of:
> 
> move Flag_of_the_Seychelles.svg flag-sc.svg
> 
> 
> To get you started if you're nowhere at the moment,
> you want to create a dictionary from your csv which maps 
> the long name to the short name so that can then
> parse the file name to find the long name, use the
> dictionary to find the short name, and then issue
> a rename command to the new name.
> 
> TJG
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] renaming files within a directory

2009-07-26 Thread Tim Golden

davidwil...@safe-mail.net wrote:

Here is what I have so far, but I get stuck on the mapping of the filename with 
the csv file.


import os
files = [file for file in os.listdir(os.getcwd()) if file.endswith('svg')]
files

['Flag_of_Abkhazia.svg', 'Flag_of_Afghanistan.svg', 'Flag_of_Albania.svg', 
'Flag_of_Algeria.svg', 'Flag_of_Andorra.svg', 'Flag_of_Angola.svg', 
'Flag_of_Antigua_and_Barbuda.svg', 'Flag_of_Argentina.svg', 
'Flag_of_Armenia.svg', 'Flag_of_Australia.svg']


import csv
reader = csv.reader(open("country.csv"))
for row in reader:
... print row   


['"km";"Comoros"']
['"dj";"Djibouti"']
['"er";"Eritrea"']
['"et";"Ethiopia"']


Here is where I am at.
Not sure how to map the two.



OK. Good stuff so far. You may not actually need
that auxiliary list of files, but no problem really.

Are you familiar with a dictionary in Python? It maps
a key to a value. Here, you want the long names to
be the keys and the short names to be values. If you
were putting them together by hand (as a constant)
it would look something like this:

countries = {
 "Comoros" : "km",
 "Ethiopia" : "et",
}

and you could look up like this:

ethiopia_tld = countries['Ethiopia']

So what you have to do is to use one of the dictionary
constructors (hint: help (dict)) to create a dictionary
out of the list of lists which you csv reader produced.
You'll need to swap the elements round as the csv has
the code first, but you want the country first.

Does that take you any further forward?

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


Re: [Tutor] Reading Data From File

2009-07-26 Thread Chris Castillo
On 7/26/09, Dave Angel  wrote:
> Chris Castillo wrote:
>> ya i was kind of in a hurry composing the email earlier. sorry for the
>> typos and misunderstanding. This is what I actually have.
>>
>> 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)
>>
>>
>> So even If I take the stuff out that you said, My structure still
>> wouldn't be right because I'm processing everything all at once with
>> no way to reference any of the grades with the student. How do I
>> structure this differently to do that? That's what I'm having trouble
>> with.
>>
>> On 7/25/09, Dave Angel  wrote:
>>
>>> 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
>>>
>>>
>>>
> (In a mailing list like this one, putting a response at the top of your
> message is called top-posting, and makes it harder for the next person
> to see the sequence of messages.)
>
> As I said before:
> *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 tried to assume an answer, but it looks like you stopped reading
> before that point.  So I'll try again, with a little more detail.
>
> Each time you come to a line with a zero in it, you have enough
> information to print out one student's information.  You know the
> current student, you know all his scores.  So you could print it out at
> that point in the loop, rather than waiting till the entire program is past.
>
> If you're not sure what I'm talking about, first put in a test for the 0
> line.  Add in a single print that prints out name and grades at that
> point.  You do know that you can print a list, just the same as any
> other variable?
>
>
> Once you see you have enough data at that point, you'll have to make a
> minor change to eliminate this student's data from getting printed again
> for the next one.
>
> Then it's just a question of formatting the print nicely.  So you
> replace the single print with a function call, passing it the name and
> grades, and format the informat

Re: [Tutor] renaming files within a directory

2009-07-26 Thread davidwilson
OK I am lost ;(

I changed the code to:

>>> reader = csv.reader(open("countries.csv"),  delimiter=";")
>>> for row in reader:
... print row 
... 
['bi', 'Burundi']
['km', 'Comoros']
['dj', 'Djibouti']
['er', 'Eritrea']

...

Now each row is a list with two items each.

But when I do this:

>>> dic = []
>>> for row in reader:
... newdic.append({row[0]: row[1]})
... 
>>> dic
[]

I get an empty dictionary


 Original Message 
From: Tim Golden 
Apparently from: tutor-bounces+davidwilson=safe-mail@python.org
To: 
Cc: tutor@python.org
Subject: Re: [Tutor] renaming files within a directory
Date: Sun, 26 Jul 2009 18:32:43 +0100

> davidwil...@safe-mail.net wrote:
> > Here is what I have so far, but I get stuck on the mapping of the filename 
> > with the csv file.
> > 
>  import os
>  files = [file for file in os.listdir(os.getcwd()) if 
>  file.endswith('svg')]
>  files
> > ['Flag_of_Abkhazia.svg', 'Flag_of_Afghanistan.svg', 'Flag_of_Albania.svg', 
> > 'Flag_of_Algeria.svg', 'Flag_of_Andorra.svg', 'Flag_of_Angola.svg', 
> > 'Flag_of_Antigua_and_Barbuda.svg', 'Flag_of_Argentina.svg', 
> > 'Flag_of_Armenia.svg', 'Flag_of_Australia.svg']
> > 
>  import csv
>  reader = csv.reader(open("country.csv"))
>  for row in reader:
> > ... print row   
> > 
> > ['"km";"Comoros"']
> > ['"dj";"Djibouti"']
> > ['"er";"Eritrea"']
> > ['"et";"Ethiopia"']
> > 
> > 
> > Here is where I am at.
> > Not sure how to map the two.
> 
> 
> OK. Good stuff so far. You may not actually need
> that auxiliary list of files, but no problem really.
> 
> Are you familiar with a dictionary in Python? It maps
> a key to a value. Here, you want the long names to
> be the keys and the short names to be values. If you
> were putting them together by hand (as a constant)
> it would look something like this:
> 
> countries = {
>   "Comoros" : "km",
>   "Ethiopia" : "et",
> }
> 
> and you could look up like this:
> 
> ethiopia_tld = countries['Ethiopia']
> 
> So what you have to do is to use one of the dictionary
> constructors (hint: help (dict)) to create a dictionary
> out of the list of lists which you csv reader produced.
> You'll need to swap the elements round as the csv has
> the code first, but you want the country first.
> 
> Does that take you any further forward?
> 
> TJG
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] renaming files within a directory

2009-07-26 Thread Tim Golden

davidwil...@safe-mail.net wrote:

OK I am lost ;(

I changed the code to:


reader = csv.reader(open("countries.csv"),  delimiter=";")
for row in reader:
... print row 
... 
['bi', 'Burundi']

['km', 'Comoros']
['dj', 'Djibouti']
['er', 'Eritrea']

...

Now each row is a list with two items each.

But when I do this:


dic = []
for row in reader:

... newdic.append({row[0]: row[1]})
... 

dic

[]

I get an empty dictionary


Well, you actually get an empty list :)
To instantiate an empty dictionary, you use curly brackets:

d = {}

To add something to a dictionary, you use:

d[] = 

Try something like this:


import csv

reader = csv.reader(open("countries.csv"),  delimiter=";")
countries = {} # note the curly brackets
for row in reader:
  code, name = row # handy Python tuple unpacking
  countries[name] = code




Once you're used to the idea, you can get reasonably slick
with dictionary initialisers and generator expressions:

import csv

reader = csv.reader(open("countries.csv"),  delimiter=";")
countries = dict ((row[1], row[0]) for row in reader)

And once you're really confident (and if you're a
fan of one-liners) you can get away with this:

import csv
countries = dict (
  (name, code) for \
(code, name) in \
csv.reader (open ("countries.csv"), delimiter=";")
)


BTW, I tend to open csv files with "rb" as it seems to
avoid line-ending issues with the csv module. YMMV.

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


[Tutor] simple text replace

2009-07-26 Thread j booth
Hello,

I am scanning a text file and replacing words with alternatives. My
difficulty is that all occurrences are replaced (even if they are part of
another word!)..

This is an example of what I have been using:

for line in fileinput.FileInput("test_file.txt",inplace=1):
> line = line.replace(original, new)
> print line,
> fileinput.close()


original and new are variables that have string values from functions..
original finds each word in a text file and old is a manipulated
replacement. Essentially, I would like to replace only the occurrence that
is currently selected-- not the rest. for example:

python is great, but my python knowledge is limited! regardless, I enjoy
> pythonprogramming


returns something like:

snake is great, but my snake knowledge is limited! regardless, I enjoy
> snakeprogramming


thanks so much!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simple text replace

2009-07-26 Thread Che M


> I am scanning a text file and replacing words with alternatives. My 
> difficulty 
> is that all occurrences are replaced (even if they are part of another 
> word!)..

Could you search for the string ' word ' with the white spaces around it?  
Shouldn't
that only replace words that are not part of another word?

> Essentially, I would like to replace only the occurrence that is currently 
> selected-- not the rest. for example:


What do you mean by a word being "currently selected"?  That phrase and
"scanning a text file" don't make sense to me together.  How is the user 
reading the text to select the word that is to be replaced?  (Or maybe I am
not understanding something?)

CM

_
Bing™ brings you maps, menus, and reviews organized in one place. Try it now.
http://www.bing.com/search?q=restaurants&form=MLOGEN&publ=WLHMTAG&crea=TXT_MLOGEN_Local_Local_Restaurants_1x1___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simple text replace

2009-07-26 Thread j booth
oops, I mean that the script opens a file and splits it into words; Then it
takes each word and searches for an alternative online; with the alternative
now stored in a variable, it simply needs to be written back over the
original word in the same file.

at the moment this might solve the problem, but I need to make sure:

for line in fileinput.FileInput("test_file.txt",inplace=1):
> line = line.replace(original, new, 1)
>
> does this make more sense?

On Sun, Jul 26, 2009 at 6:05 PM, Che M  wrote:

>
> > I am scanning a text file and replacing words with alternatives. My
> difficulty
> > is that all occurrences are replaced (even if they are part of another
> word!)..
>
> Could you search for the string ' word ' with the white spaces around it?
> Shouldn't
> that only replace words that are not part of another word?
>
> > Essentially, I would like to replace only the occurrence that is
> currently
> > selected-- not the rest. for example:
>
> What do you mean by a word being "currently selected"?  That phrase and
> "scanning a text file" don't make sense to me together.  How is the user
> reading the text to select the word that is to be replaced?  (Or maybe I am
> not understanding something?)
>
> CM
>
> --
> Bing™ brings you maps, menus, and reviews organized in one place. Try it
> now.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simple text replace

2009-07-26 Thread Dave Angel

j booth wrote:

Hello,

I am scanning a text file and replacing words with alternatives. My
difficulty is that all occurrences are replaced (even if they are part of
another word!)..

This is an example of what I have been using:

for line in fileinput.FileInput("test_file.txt",inplace=1):
  

line = line.replace(original, new)
print line,
fileinput.close()




original and new are variables that have string values from functions..
original finds each word in a text file and old is a manipulated
replacement. Essentially, I would like to replace only the occurrence that
is currently selected-- not the rest. for example:

python is great, but my python knowledge is limited! regardless, I enjoy
  

pythonprogramming




returns something like:

snake is great, but my snake knowledge is limited! regardless, I enjoy
  

snakeprogramming




thanks so much!

  
Not sure what you mean by "currently selected," you're processing a line 
at a time, and there are multiple legitimate occurrences of the word in 
the line.


The trick is to define what you mean by "word."  replace() has no such 
notion.  So we want to write a function such as:


given three strings, line, inword, and outword.  Find all occurrences of 
inword in the line, and replace all of them with outword.  The 
definition of word is a group of alphabetic characters (a-z perhaps) 
that is surrounded by non-alphabetic characters.


The approach that I'd use is to prepare a translated copy of the line as 
follows:   Replace each non-alphabetic character with a space.  Also 
insert a space at the beginning and one at the end.  Now, take the 
inword, and similarly add spaces at begin and end.  Now search this 
modified line for all occurrences of this modified inword, and make a 
list of the indices where it is found.  In your example line, there 
would be 2 items in the list.


Now, using the original line, use that list of indices to substitute the 
outword in the appropriate places.  Use slices to do it, preferably from 
right to left, so the indices will work even though the string is 
changing.  (The easiest way to do right to left is to reverse() the list.


DaveA

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


Re: [Tutor] First code snipet

2009-07-26 Thread Darth Kaboda

> Good point. It is important to state your goal for the code, preferably 
> in comments in your code, as well as in the message asking us the 
> question. Suggest you include a doc-string for each class and method 
> declaration.
> 
> But it's important to tell us how you expect to use it, as well. If 
> it's for your own learning, then it's pretty good as it is. But if you 
> intend to show it to prospective employers, there are a lot of ways to 
> clean it up.
> 
> 
> So...
> 
> Unlike Java, not everything needs to be in a class. This shuffler class 
> accomplishes nothing that the module doesn't already do. The only 
> instance attribute you use is rgen, and that could just as readily have 
> been a global (visible within the entire module).
> 
> Naming is important. I think I would have factored it into three 
> functions cut() and ripple(). shuffle() simply calls cut(), then ripple().
> 
> You need to know the library better. Andreas already mentioned the std 
> library random.shuffle(), and you correctly explained why you didn't use 
> it. But there are other library functions that would make your code 
> more concise, more readable, and maybe faster.
> 
> Starting with shuffle() (which I'd call ripple())
> 
> Because Python makes it easy to swap two variables in-place, it's common 
> to swap arguments directly, rather than copy them to local attributes. 
> So I'd replace the first 4 lines with:
> if self.rgen.randint(0,1): #randomly decide which pile is shuffled 
> down first
> inpile2, inpile1 = inpile1, inpile2
> 
> len() is very fast, so there's no need for a separate variable to keep 
> track of the lengths of inpile1 and inpile2. So eliminate all refs to 
> pile1c and pile2. In the while, just use
> while len(inpile1) and len(inpile2):
> 
> Lists have no type associated with them. Each object in a list has its 
> own type. So there's no meaning to constructing an empty list out of 
> another one.
> rpile = []
> 
> pop(0) is slow, compared with pop(-1). If you used the latter, you 
> would have to do a reverse on the list when you were done to keep the 
> realism. And that would make the code less readable. So I think this 
> is an unnecessary optimization. But keep it in mind if you're ever 
> dealing with thousands of items in a list. Peeling them off from the 
> front one at a time will be slow.
> 
> The logic of popping a random number of cards from one list, and 
> appending them to the result could be done the same way you do the 
> cut(), using slices. I think it would be worth it if you made a 
> separate function out of it, to call from whichever deck was being 
> operated on.
> 
> Where you do the if i < pile1c you could instead use the min() 
> function.
> i = min(len(inpile1), self.rgen.randint(1,4))
> 
> At the end of the function, the if pile1c: elif ... logic could be 
> replaced by
> rpile.extend(inpile1).extend(inpile2)
> 
> as there's no harm in extending with an empty list.
> 
> HTH, DaveA
> 


Dave and Alan,

 

Thank you for the advice and showing me some of the small nuances I haven't 
quite figured out yet. I used both of your suggestions to change the class the 
updated code is attached if you'd like to see.

 

I tried putting the two extends in the same line and that didn't work as extend 
doesn't return anything so ended up putting them on consecutive lines without 
the if statement. 

 

Instead of doing the pop method I took your advice and tried it with slices 
instead along with extends. Shortened the code a bit. One note on pop method is 
pop() and pop(-1) the same thing? Looks like it based on what I've read but not 
100% confident in that answer. 

 

On the class versus module I wasn't sure where I'd end up taking this idea so 
went ahead and coded it as a class. If I actually do much more with this, other 
then just as a coding exercise to help learn Python, I might be adding things 
to this or using it as a superclass. Examples of expansion ability to queue up 
decks, have multiple shufflers going at the same time in a program etc... So 
without knowing all the options in Python figured the class gave me the 
greatest flexibility. Yeah otherwise I'd have just made a module and still 
might switch it if I expand on this depending on what the needs turn out to be.

 

Again thanks to everyone for looking at my code and the quick and helpful 
feedback. Hoping to do start coding a larger project soon so you'll probably 
get some questions from me.

 

Thanks,

Brian
import random

class shuffler(object):
def __init__(self):
self.rgen = random.Random()
def shuffle(self, inpile1, inpile2):
"""Shuffles two lists of items in the same manner as a real deck of 
cards is shuffled. This function will not change the passed in variables of 
piles."""
if self.rgen.randint(0,1):  #randomly decide which pile is shuffled 
down first
(pile1,pile2)=(inpile1,inpile2)
else:
(pile1,pile2)=(inpile2,inpile1)
rp

Re: [Tutor] Reading and Manipulating XML Data

2009-07-26 Thread Luis Galvan
Hi Alan,
I'm liking how clean Element tree is, thanks for the quick reply!  Nice
definition by the way, I think its a bit clearer now.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor