Re: [Tutor] Zipfile and File manipulation questions.

2006-10-17 Thread Kent Johnson
Chris Hengge wrote:
> I chose the way I used the names because to me...
> 
> outFile = open(aFile.lower(), 'w') # Open output buffer for writing.
> = open a file with lowercase name for writing.
> it is implied that aFile is from the zip, since it is created in the 
> loop to read the zip..
> 
> outFile.write(zFile.read(insideZip)) # Write the file.
> = write what is read from inside the zip file.

This sub-thread seems to have turned into "let's beat on Chris for the 
way he names things" which certainly isn't what I intended. Ultimately 
it is up to the program author to use the names that he thinks 
communicate most clearly.

But I think the actual naming was secondary to the my main point which 
is that the value for 'insideZip' is read from the zip, if you assign to 
that name and keep it in that name the code is easier to follow because 
the value that doesn't change stays in a name that doesn't change.

So using your names, it would read
 for insideZip in zFile.namelist():
 for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']:
 if insideZip .lower().endswith(ext):
 if "/" in insideZip :
   aFile = aFile.rsplit('/', 1)[-1]
 elif  "\\" in insideZip :
   aFile = aFile.rsplit('\\', 1)[-1]
 else:
   aFile = insideZip

This way inzideZip is always the name from inside the zip, and aFile is 
always the name of the file to write.
> 
> I guess for declaration it isn't very clear, but thats what comments are 
> for?

The comments about comments have been on the mark, I think. A helpful 
guideline I use is, when I think I need a comment, look at the names I 
am using and see if I can create a function whose name conveys what I 
wanted to say in the comment.

Kent


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


[Tutor] Importing module - file system requests

2006-10-17 Thread Bernard Lebel
Hello,

When I import a module in Python, I see that 6 file system operation
are being made. All requests are for opening.
I know very well what are the .py and and .pyc files. But I'm not so
sure what are .pyd and .pyw, and why it's looking for a dll. Anyone
can shed some light on this?

Also, if I have a .pyd version of modules, will it skip the other requests?

Here are the requests, in order:
file directory
.pyd file
.dll file
.py file
.pyw file
.pyc file



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


Re: [Tutor] Zipfile and File manipulation questions.

2006-10-17 Thread Luke Paireepinart
Kent Johnson wrote:
> Chris Hengge wrote:
>   
>> I chose the way I used the names because to me...
>>
>> outFile = open(aFile.lower(), 'w') # Open output buffer for writing.
>> = open a file with lowercase name for writing.
>> it is implied that aFile is from the zip, since it is created in the 
>> loop to read the zip..
>>
>> outFile.write(zFile.read(insideZip)) # Write the file.
>> = write what is read from inside the zip file.
>> 
>
> This sub-thread seems to have turned into "let's beat on Chris for the 
> way he names things" which certainly isn't what I intended. Ultimately 
> it is up to the program author to use the names that he thinks 
> communicate most clearly.
>   
Well, yes, and it's up to the auto mechanic to use the parts he thinks 
are best when he fixes your car.
However, one hopes that he has training in how to determine which parts 
are the most durable, safest, etc, etc.
Similarly, while it's up to you to choose variable names, we still hope 
that you know why you're choosing certain names.
> But I think the actual naming was secondary to the my main point which 
> is that the value for 'insideZip' is read from the zip, if you assign to 
> that name and keep it in that name the code is easier to follow because 
> the value that doesn't change stays in a name that doesn't change.
>
> So using your names, it would read
>  for insideZip in zFile.namelist():
>  for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']:
>  if insideZip .lower().endswith(ext):
>  if "/" in insideZip :
>aFile = aFile.rsplit('/', 1)[-1]
>  elif  "\\" in insideZip :
>aFile = aFile.rsplit('\\', 1)[-1]
>  else:
>aFile = insideZip
>
> This way inzideZip is always the name from inside the zip, and aFile is 
> always the name of the file to write.
>   
I think it'd be most clear if you did something like:
ext = ['.cap','.hex','.fru','.cfg','.sdr']
for zipFile in zFile.namelist():
   if os.path.splitext(zipFile)[-1] in ext:
  outFile = os.path.split(zipFile)[-1]

but that's just me :)

I've gone back and read your code.
The problem Kent was pointing out was that your for loop was iterating 
over a variable called aFile,
and you were changing this variable during the loop.  This is generally 
considered Bad Practice.
That's all he meant.
I think.

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


[Tutor] python applets

2006-10-17 Thread Picio
Hello,
I'm evaluating a way to build applets in python.
Actually google told me that I can use
Grail
Jython

Can you add/suggest other ways?
The more easy to learn wins !!!

thanks a lot for any answer.
Picio
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python applets

2006-10-17 Thread Kent Johnson
Picio wrote:
> Hello,
> I'm evaluating a way to build applets in python.
> Actually google told me that I can use
> Grail
> Jython

Grail is a very old, very dead project to write a web browser in Python. 
Your users would have to use Grail for this to work.

You can write Java applets in Jython, see www.jython.org to get started.

Kent

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


[Tutor] Help me abt this error

2006-10-17 Thread Asrarahmed Kadri
I am trying to write to a file, but I am getting this errror.
 
IOError: (0, 'Error')
 
Can someone explain what is it and whats the solution?? 
Thanks.
 
Regards,
Asrar
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] distribution

2006-10-17 Thread Joel Levine
I am writing code that people I work with want to pick up "instantly" for their own machines.  BUT they may be using different platforms and different installations on those platforms. 

I'm writing on a Mac, using Python 2.4, numpy, and Tkinter.  They are using Macs and PC's, who-knows-what vintage Python, with or without numpy, numeric, and Tkinter.

Any suggestions for keeping my sanity?  Is there something in particular I should be reading?

Thanks,
Joel Levine ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Zipfile and File manipulation questions.

2006-10-17 Thread Chris Hengge
I find your example rather amusing, since it makes it sound like you want this fictional mechanic to pick his parts by the brand name, rather then by how well the part works (in description vs context)... Your analogy seems to push that the brand name would inherently give the descriptive name which is fine..  Personally.. I dont care if you call it a motor or anything else... a motor is a motor because of its functionality... not because "motor" itself has some great descriptive meaning. We only understand what motor means because its been the standard to describe the hunk of metal, rubber, and plastic under the hook of an automobile. now.. if I've never heard of a motor... I'd learn what it is be getting some basic understanding of its functionality... it wouldn't matter what you called it if I've never heard the word, I'd have to know what it does to understand what distiguishes it from a bicycle. The only exception is when new terminology isn't defined for an object, such as "motor-carriage"(still have that darn motor word that I dont understand without knowing atleast basic functionality) or "auto-mobile"...(so... is this a bike that peddles itself? and flying machine? a cellphone that beams me to work automagically at 9:00am? We call them cars? why? because its what people stuck with from "motor-'car'riage" after adapting to the new machine.. You want to add to the mess... A truck is defined as a tool to move items around... mentally, I think of something more like a wheel-barrel.. but wait.. wheel-barrels dont look like barrels... either way... poor naming =P 
Names are nothing more then a distinguishing mark to define something that hasn't already been defined.. Humans are great because they wrap huge functional and contextual definitions to names and dont even realise it.. Think of  your own name.. if that is all I used to describe you I'd never understand what was different between you and anyone else with your name.. but when I think of "you"( aka you in context), I can list tons of stuff that makes you who you are.. Try and imagine your name if I took it completely out of context and functionality... You'd have some name more like "Brian, slacker of the eastside, teller of the great jokes, driver of the SUV, son of Marry and George, birth-father of little billy, owner of many pc's"... vs the guy that lives in another neighborhood who'd have to be named "Brian, civil servant of the eastside, impressor of women, driver of the sports car, Adopted,birth father to many across the town, owner of no pc's" if you wanted to describe someone. 
Rambling aside... I was just trying to take a light hearted spin because the poor mechanic we have subjected for abuse in this debate struck me funny. On 10/17/06, 
Luke Paireepinart <[EMAIL PROTECTED]> wrote:
Kent Johnson wrote:> Chris Hengge wrote:>>> I chose the way I used the names because to me... outFile = open(aFile.lower(), 'w') # Open output buffer for writing.>> = open a file with lowercase name for writing.
>> it is implied that aFile is from the zip, since it is created in the>> loop to read the zip.. outFile.write(zFile.read(insideZip)) # Write the file.>> = write what is read from inside the zip file.
 This sub-thread seems to have turned into "let's beat on Chris for the> way he names things" which certainly isn't what I intended. Ultimately> it is up to the program author to use the names that he thinks
> communicate most clearly.>Well, yes, and it's up to the auto mechanic to use the parts he thinksare best when he fixes your car.However, one hopes that he has training in how to determine which parts
are the most durable, safest, etc, etc.Similarly, while it's up to you to choose variable names, we still hopethat you know why you're choosing certain names.> But I think the actual naming was secondary to the my main point which
> is that the value for 'insideZip' is read from the zip, if you assign to> that name and keep it in that name the code is easier to follow because> the value that doesn't change stays in a name that doesn't change.
>> So using your names, it would read>  for insideZip in zFile.namelist():>  for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']:>  if insideZip .lower().endswith(ext):
>  if "/" in insideZip :>aFile = aFile.rsplit('/', 1)[-1]>  elif  "\\" in insideZip :>aFile = 
aFile.rsplit('\\', 1)[-1]>  else:>aFile = insideZip>> This way inzideZip is always the name from inside the zip, and aFile is> always the name of the file to write.
>I think it'd be most clear if you did something like:ext = ['.cap','.hex','.fru','.cfg','.sdr']for zipFile in zFile.namelist():   if os.path.splitext(zipFile)[-1] in ext:  outFile = 
os.path.split(zipFile)[-1]but that's just me :)I've gone back and read your code.T

Re: [Tutor] Zipfile and File manipulation questions.

2006-10-17 Thread Chris Hengge
I get what you are trying to say.. but I'm looking at the code after changing names, and I think it makes more sense in the code my way because of the following lines..outFile = open(aFile.lower(), 'w')#open 'afile' named with lowercase to 'w'rite
outFile.write(zFile.read(insideZip))#write what you read 'insidezip' This is what I mean by functional names verses descriptive... Your way I'd have a better grasp of the data, my way I feel I have a better grasp of what is going on in my code. When I'm done writing my code and go back through the documentation I'll be adding all the variables used to the docstring, inputs, outputs.. all that jazz. Even if I didn't, and I'd never seen this code before, I'd try to figure out what it is doing before caring what data is being manipulated. Think about it... understanding the purpose in context will give me a better understanding of what the data going in, and coming out should appear to be, then hoping the author picked the right stuff. Perhaps I've adopted this habbit after years of trying to learn from snippets of code online where people use completely generic variable names as references, and kind of started ignoring variable names.. 
Seriously... its just how you look at things... I obviously read code and get my understanding very differently then many people on here. I take more of a top down approach, while it sounds many of you take a bottom up approach.
On 10/17/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
Chris Hengge wrote:> I chose the way I used the names because to me...>> outFile = open(aFile.lower(), 'w') # Open output buffer for writing.> = open a file with lowercase name for writing.
> it is implied that aFile is from the zip, since it is created in the> loop to read the zip..>> outFile.write(zFile.read(insideZip)) # Write the file.> = write what is read from inside the zip file.
This sub-thread seems to have turned into "let's beat on Chris for theway he names things" which certainly isn't what I intended. Ultimatelyit is up to the program author to use the names that he thinks
communicate most clearly.But I think the actual naming was secondary to the my main point whichis that the value for 'insideZip' is read from the zip, if you assign tothat name and keep it in that name the code is easier to follow because
the value that doesn't change stays in a name that doesn't change.So using your names, it would read for insideZip in zFile.namelist(): for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']:
 if insideZip .lower().endswith(ext): if "/" in insideZip :   aFile = aFile.rsplit('/', 1)[-1] elif  "\\" in insideZip :
   aFile = aFile.rsplit('\\', 1)[-1] else:   aFile = insideZipThis way inzideZip is always the name from inside the zip, and aFile is
always the name of the file to write.>> I guess for declaration it isn't very clear, but thats what comments are> for?The comments about comments have been on the mark, I think. A helpful
guideline I use is, when I think I need a comment, look at the names Iam using and see if I can create a function whose name conveys what Iwanted to say in the comment.Kent___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me abt this error

2006-10-17 Thread Luke Paireepinart
Asrarahmed Kadri wrote:
> I am trying to write to a file, but I am getting this errror.
>  
> IOError: (0, 'Error')
>  
> Can someone explain what is it and whats the solution??
No.
Give us the actual source and the full traceback.
Cheers,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] distribution

2006-10-17 Thread Luke Paireepinart
Joel Levine wrote:
> I am writing code that people I work with want to pick up "instantly" 
> for their own machines. BUT they may be using different platforms and 
> different installations on those platforms.
>
> I'm writing on a Mac, using Python 2.4, numpy, and Tkinter. They are 
> using Macs and PC's, who-knows-what vintage Python, with or without 
> numpy, numeric, and Tkinter.
>
> Any suggestions for keeping my sanity? Is there something in 
> particular I should be reading?
Use the os module a lot, and harrass them until they install numpy(or 
don't use it.)
Feel free to use TKInter, it's part of the python distribution (Unless 
they have pre-1.5 or something, in which case they should upgrade anyway !)
:)
HTH,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me abt this error

2006-10-17 Thread Danny Yoo
> I am trying to write to a file, but I am getting this errror.
>
> IOError: (0, 'Error')
>
> Can someone explain what is it and whats the solution??

Hi Asrarahmed,

Did you read my response from the last few days?

 http://mail.python.org/pipermail/tutor/2006-October/049958.html

Did you find it helpful?  I thought it directly addressed the question you 
had on:

 http://mail.python.org/pipermail/tutor/2006-October/049937.html

If it doesn't apply, at least please mention that it didn't work for you; 
at least we'll be able to cross off that possibility.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me abt this error

2006-10-17 Thread Luke Paireepinart

Oops, I replied off-list.  Forwarding to list.


--- Begin Message ---

Mike Hansen wrote:
 

  

-Original Message-
From: [EMAIL PROTECTED] 
[mailto:[EMAIL PROTECTED] On Behalf Of Luke Paireepinart

Sent: Tuesday, October 17, 2006 11:50 AM
To: Asrarahmed Kadri
Cc: pythontutor
Subject: Re: [Tutor] Help me abt this error

Asrarahmed Kadri wrote:


I am trying to write to a file, but I am getting this errror.
 
IOError: (0, 'Error')
 
Can someone explain what is it and whats the solution??
  

No.
Give us the actual source and the full traceback.
Cheers,
-Luke



Luke, don't fall to the dark side. You must be a kind Python Jedi.
E-mail is a strange communication tool in that the reader doesn't see
your kind Python Jedi disposition but instead can interpret your
bluntness as being mean and Sith-like. 
  

Haha.
At least you didn't say that Vader quote I hear oh-so-much.
"Luke, I am your father!"
Uh,
1) You're not my father, so it doesn't make sense, and
2) Vader never actually said that.
He said "No.  I am your father."

:O

Yeah, I didn't mean to sound cold.  I thought I put a smiley at the end 
so he'd know I wasn't serious,

but I guess I forgot!
Nevertheless, it's important that the OP asks good questions.
I'm pretty sure I know what caused his error, but I don't want to 
encourage him to ask incomplete questions,

so I'm withholding an answer. :)
-Luke


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


Re: [Tutor] A puzzle for you

2006-10-17 Thread Terry Carroll
On Sat, 14 Oct 2006, John Fouhy wrote:

> >From the python_dev LiveJournal community ---
> 
> Predict the outcome of the following code:
> 
> ##
> from random import *
> seed()
> [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0]
> ##

On ActivePython 2.4.3:

>>> from random import *
>>> seed()
>>> [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0]
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\Python24\Lib\random.py", line 249, in choice
return seq[int(self.random() * len(seq))]  # raises IndexError if seq is 
empty
KeyError: 0
>>>


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


Re: [Tutor] A puzzle for you

2006-10-17 Thread John Fouhy
On 18/10/06, Terry Carroll <[EMAIL PROTECTED]> wrote:
> On Sat, 14 Oct 2006, John Fouhy wrote:
>
> > >From the python_dev LiveJournal community ---
> >
> > Predict the outcome of the following code:
> >
> > ##
> > from random import *
> > seed()
> > [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0]
> > ##
>
> On ActivePython 2.4.3:
>
> >>> from random import *
> >>> seed()
> >>> [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0]
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "C:\Python24\Lib\random.py", line 249, in choice
> return seq[int(self.random() * len(seq))]  # raises IndexError if seq is 
> empty
> KeyError: 0
> >>>

Does that always happen?

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


Re: [Tutor] extracting numbers from a list

2006-10-17 Thread kumar s
In continuation to :
Re: [Tutor] extracting numbers from a list



hello list

I have coordinates for exons (chunks of sequence). For
instance:

10 - 50  A
10 - 20  B
35 - 50  B
60 - 70  A
60 - 70  B
80 - 100 A
80 - 100 B
(The above coordinates and names are easier than in
dat)

Here my aim is to creat chunks of exons specific to A
or B.

For instance:
10 - 20,35 - 50 are common  to both A and B, whereas
21 - 34 is specific only to A.

The desired output for me is :

10 \t 20  A,B
21 \t 34  A
35 \t 50  A,B
60 \t 70  A,B
80 \t 100 A,B

I just learned python frm a friend and he is also a
novice.

What I could get is the break up of chunks. A problem
here I am getting number different from what I need:
[10, 20] [10, 50]
[21, 35] [10, 50]
[36, 50] [10, 50]
[60, 70] [60, 70]
[80, 100] [80, 100]

The list next to chunks is the pairs( the longer
ones).

could any one help me how can I correct [21, 35],[36,
50] to 21 \t 34 , 35 \t 50.  I tried chaning the
indexs in function chunker, it is not working for me.
Also, how can I point chunks to their names.

This is the abstract example of the complex numbers
and their sequence names.  I want to change the simple
code and then go to the complex one.

Thank you very much for your valuable time. 



REsult: what I am getting now:

[10, 20] [10, 50]
[21, 35] [10, 50]
[36, 50] [10, 50]
[60, 70] [60, 70]
[80, 100] [80, 100]



My code:




from sets import Set
dat = ['10\t50\tA', '10\t20\tB', '35\t50\tB',
'60\t70\tA', '60\t70\tB', '80\t100\tA', '80\t100\tB']


# creating a dictionary with coordiates as key and NM_
as value
#

ekda = {}
for j in dat:
cols = j.split('\t')
   
ekda.setdefault(cols[0]+'\t'+cols[1],[]).append(cols[2])
##
#getting tab delim numbers only and not the A,B
bat = []
for j in dat:
cols = j.split('\t')
bat.append(cols[0]+'\t'+cols[1])
pairs = [ map(int, x.split('\t')) for x in bat ]


#
# this function takes pairs (from the above result)and
longer blocks(exons).
# For instance:
# 10 - 20; 14 - 25; 19 - 30; 40 - 50; 45 - 60; 70 - 80
# a =
[[10,20],[14,25],[19,30],[40,50],[45,60],[70,80]]
# for j in exoner(a):
#   print j
#The result would be:
#10 - 30; 40 - 60; 70 - 80
#
def exoner(pairs):
pairs.sort()
i = iter(pairs)
last = i.next()
for current in i:
if current[0] in
xrange(last[0],last[1]):
if current[1] > last[1]:
last = [last[0],
current[1]]
else:
last =
[last[0],last[1]]
else:
yield last
last = current
yield last
lon = exoner(pairs)
#
## Here I am getting all the unique numbers in dat

nums = []
for j in pairs:
for k in j:
nums.append(k)
unm = Set(nums)
unums = []
for x in unm:
unums.append(x)
unums.sort()
#
### This function takes a list of numbers and breaks
it in pieces
## For instance [10,15,20,25,30]
#>>> i = [10,15,20,25,30]
#>>> chunker(i)
#[[10, 15], [16, 20], [21, 25], [26, 30]]


def chunker(lis):
res = []
res.append([lis[0],lis[1]])
for m in range(2,len(lis)):
res.append([lis[m-1]+1,lis[m]])
return res

# Here I take each pair (longer block) and roll over
all the unique numbers ((unums) from dat) and check if
that number is in#the range of pair, if so, I will
break all those set of number in pair range into small
blocks
##
gdic = {}
unums.sort()
for pair in exoner(pairs):
x = pair[0]
y = pair[1]+1
sml = []
for k in unums:
if k in range(x,y):
sml.append(k)
else:
pass
for j in chunker(sml):
print j,pair






__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Searching list items.

2006-10-17 Thread Chris Hengge
contents = readlines(myfile, 'r')Ok, I'm under the impression this is a list of strings (array)How in the world do I cycle through them looking for words?for line in contents: if line.contains("something")
 print lineThats a mock up of what I'm looking for. I tried to figure out how to use re, but that spits out locations in memory or none it seems. Thanks. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching list items.

2006-10-17 Thread Luke Paireepinart
Chris Hengge wrote:
> contents = readlines(myfile, 'r')
> Ok, I'm under the impression this is a list of strings (array)
Nope.  No such thing as arrays in Python.
It is a list of strings, that's it. :)
> How in the world do I cycle through them looking for words?
>
> for line in contents:
>  if line.contains("something")
>  print line
>
> Thats a mock up of what I'm looking for.
> I tried to figure out how to use re, but that spits out locations in 
> memory or none it seems.
You'd use regular expressions or use
if 'astring' in line:

if your use case is simple enough for that.
show us what RE you used that gave you trouble.
It's hard to help when we don't know where you're getting stuck :)
>
> Thanks.
Sure.

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


Re: [Tutor] Searching list items.

2006-10-17 Thread Chris Hengge
I remove those lines, but I was trying to usefor line in contents:    result = re.search("something", line)    print resultthis printed out something like NoneNoneNonehex memory address of goodness
NoneNone...On 10/17/06, Luke Paireepinart <[EMAIL PROTECTED]> wrote:
Chris Hengge wrote:> contents = readlines(myfile, 'r')> Ok, I'm under the impression this is a list of strings (array)Nope.  No such thing as arrays in Python.It is a list of strings, that's it. :)
> How in the world do I cycle through them looking for words?>> for line in contents:>  if line.contains("something")>  print line>> Thats a mock up of what I'm looking for.
> I tried to figure out how to use re, but that spits out locations in> memory or none it seems.You'd use regular expressions or useif 'astring' in line:if your use case is simple enough for that.
show us what RE you used that gave you trouble.It's hard to help when we don't know where you're getting stuck :)>> Thanks.Sure.-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching list items.

2006-10-17 Thread Luke Paireepinart
Chris Hengge wrote:
> I remove those lines, but I was trying to use
> for line in contents:
> result = re.search("something", line)
> print result
I'm pretty sure this isn't how you use regular expressions.
I have to go to class right now but if no one else has replied when I 
get back I'll look into it.
Sorry I can't help right now.
-Luke
>
> this printed out something like
>
> None
> None
> None
> hex memory address of goodness
> None
> None

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


Re: [Tutor] Searching list items.

2006-10-17 Thread Chris Hengge
An article at devshed was using it like that... but the output wasn't what I was looking for.. I was getting the hex address where the result was, but not printing the line.. I think the simple code you recommended in your first reply will do the trick, I'm not looking for anything magical, just need to see a line if it contains what I'm looking for.
I'll do some more checking into regex later, looks very useful...Thanks. On 10/17/06, Luke Paireepinart <
[EMAIL PROTECTED]> wrote:Chris Hengge wrote:> I remove those lines, but I was trying to use
> for line in contents:> result = re.search("something", line)> print resultI'm pretty sure this isn't how you use regular expressions.I have to go to class right now but if no one else has replied when I
get back I'll look into it.Sorry I can't help right now.-Luke>> this printed out something like>> None> None> None> hex memory address of goodness> None
> None
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching list items.

2006-10-17 Thread John Fouhy
On 18/10/06, Chris Hengge <[EMAIL PROTECTED]> wrote:
> I remove those lines, but I was trying to use
> for line in contents:
> result = re.search("something", line)
> print result
>
> this printed out something like
>
> None
> None
> None
> hex memory address of goodness
> None
> None

If you don't need a regular expression, you are probably better off using 'in':

for line in contents:
if 'something' in line:
print line

Otherwise, re.search() and re.match() return either None or a match
object.  So, you can do this:

for line in contents:
m = re.search('something', line)
if m:
print line[m.start():m.end()]

match objects become more powerful when you start using groups or
named groups in your regular expressions.  See the documentation for
more :-)

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


Re: [Tutor] Searching list items.

2006-10-17 Thread Danny Yoo


> I remove those lines, but I was trying to use
> for line in contents:
>   result = re.search("something", line)
>   print result

'result' here is going to either be None, as you've seen, or a "match" 
object.  We have several options available to use once we have a 
match.  Take a look at a few of the methods in here:

 http://www.python.org/doc/lib/match-objects.html

Printing a match object itself won't be too informative.  What would you 
like to show up if there is some match?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me abt this error

2006-10-17 Thread Asrarahmed Kadri
I changed to append mode and it is working.
But the thing is that I have another problem.
I am trying to insert usernames that are unique. Please look at the code and help me.

import sys
fd = open('usr.txt','a')
def chk(str):    global fd    fd.seek(0,0)    print fd    done = 0    list1 = []    answer = True        while not done:        aline = fd.readline
()        if aline == "":    done = 1    else:    list1.append(aline)    print list1    for i in list1:    print i    j = i.split(':')    if str == j[0]:
    answer = False    break    return answer
def make_entry(uname,passwd):    global fd    fd.seek(0,2)    str1 = uname+':'+passwd    fd.write(str1+'\n')    enter_choice()
def die():    sys.exit(0)
def new_user():    uname = raw_input("Enter your desired username")    ans = chk(uname)    print ans    if ans:    passwd = raw_input("Enter your password")    make_entry(uname,passwd)
    else:    showerror('Login Error...','Id already taken')    new_user()
 
def display_menu():    print "-" * 30    print "Select 1 for new user:"    print "Select 2 to exit"    print "-" * 30
def enter_choice():    display_menu()    print    choice = raw_input("Enter your choice")    if choice == '1':    new_user()        else:    die()
enter_choice()
 
The problem is in the chk() function.. It is not reading the file The file is a txt file with colon (:) as the delimiter between username and password.
I cannot understand why its not reading???
Please help...
 
 
 
On 10/17/06, Luke Paireepinart <[EMAIL PROTECTED]
> wrote: 
Asrarahmed Kadri wrote:> I am trying to write to a file, but I am getting this errror.>> IOError: (0, 'Error') 
>> Can someone explain what is it and whats the solution??No.Give us the actual source and the full traceback.Cheers,-Luke-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] My apologyRe: Help me abt this error

2006-10-17 Thread Asrarahmed Kadri
I am so sorry.. if anyone felt offended..
 
I am a bit nervous about teh whole thing.. I am learning the language as well as i have a deadline to complete my project which is on Tkinter..
 
Dont mind.. I acknowledge the help from all the people out here..
Thanks.
God Bless.
 
Regards, 
Asrar 
On 10/17/06, Danny Yoo <[EMAIL PROTECTED]> wrote:
> I am trying to write to a file, but I am getting this errror.>> IOError: (0, 'Error')
>> Can someone explain what is it and whats the solution??Hi Asrarahmed,Did you read my response from the last few days?
http://mail.python.org/pipermail/tutor/2006-October/049958.htmlDid you find it helpful?  I thought it directly addressed the question youhad on:
http://mail.python.org/pipermail/tutor/2006-October/049937.htmlIf it doesn't apply, at least please mention that it didn't work for you;at least we'll be able to cross off that possibility.
-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me abt this error

2006-10-17 Thread Luke Paireepinart
Asrarahmed Kadri wrote:
>
> I changed to append mode and it is working.
> But the thing is that I have another problem.
> I am trying to insert usernames that are unique. Please look at the 
> code and help me.
>
> import sys
>
> fd = open('usr.txt','a')
>
append mode is write-only.
more comments further down.
>
>
> def chk(str):
> global fd
> fd.seek(0,0)
> print fd
> done = 0
> list1 = []
> answer = True
>
> while not done:
>
> aline = fd.readline ()
>
> if aline == "":
> done = 1
> else:
> list1.append(aline)
> print list1
> for i in list1:
> print i
> j = i.split(':')
> if str == j[0]:
> answer = False
> break
> return answer
>
Can I politely request that you don't add color to your functions?
It makes it harder for me to read them.
I know you're trying to place emphasis on which functions are giving you 
problems, but if you were to just comment them
instead I'd be happy :)

For your problem about reading the file, I would suggest that you keep 
the contents in memory, or read the file each time and close it, instead 
of trying to keep an open copy of it around and seeking and such.  Since 
you're opening the file in append mode, you aren't able to do reads.
you could use 'a+', but I don't recommend it.
You'll probably run into weird behavior, and maybe only on certain 
inputs (I.E. scary bugs that you might not notice till your program is 
in use already.)

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


Re: [Tutor] My apologyRe: Help me abt this error

2006-10-17 Thread Luke Paireepinart
Asrarahmed Kadri wrote:
> I am so sorry.. if anyone felt offended..
I don't think anyone was offended :)
>  
> I am a bit nervous about teh whole thing.. I am learning the language 
> as well as i have a deadline to complete my project which is on Tkinter..
Why do you have a deadline?
Is it a school project or a work project?

They expected you to learn Python and TKInter while you had a project 
looming over you?
That's not a good way to go about it!


Well, in any case, good luck.
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] followup on python cookies/sessions (fwd)

2006-10-17 Thread Danny Yoo


-- Forwarded message --
Date: Mon, 16 Oct 2006 14:19:53 -0700 (PDT)
From: anil maran <[EMAIL PROTECTED]>
To: Danny Yoo <[EMAIL PROTECTED]>
Subject: followup on python cookies/sessions

Dear Danny

My login code looks like this for session and cookie i dont know how to combine 
both and save session id in cookie,


SESSION CODE


class login:


 @checkaccess()


 def GET(self):


 web.render('login.html')





 @checkaccess()


 def POST(self):


 user = web.storify({


 'id':1,


 'username':'mark',


 'password':'userss',


 'groups':'admin'


 })


 inp = web.input()


 if inp.username == user.username and inp.password == user.password:


 dologin(user)


 web.redirect('/')


 else:


 web.render('login.html')





class logout:


 @checkaccess()


 def GET(self):


 dologout()


 web.redirect('/')





class login:


 @checkaccess()


 def GET(self):


 web.render('login.html')





 @checkaccess()


 def POST(self):


 user = web.storify({


 'id':1,


 'username':'anil',


 'password':'toper',


 'groups':'admin'


 })


 inp = web.input()


 if inp.username == user.username and inp.password == user.password:


 dologin(user)


 web.redirect('/')


 else:


 web.render('login.html')





class logout:


 @checkaccess()


 def GET(self):


 dologout()


 web.redirect('/')


COOKIE CODE

def check_password(raw_password, enc_password):


 """


 Returns a boolean of whether the raw_password was correct. Handles


 encryption formats behind the scenes.


 """


 algo, salt, hsh = enc_password.split('$')


 if algo == 'sha1':


 return hsh == sha.new(salt+raw_password).hexdigest()


 elif algo == 'md5':


 import md5


 return hsh == md5.new(salt+raw_password).hexdigest()


 raise ValueError, "Got unknown password algorithm type in password."





class login:


   def POST(self):


 login = web.input()


 thisuser = web.query('select * from users where email = $login.email', 
vars=locals())





 if thisuser:


   thisuser = thisuser[0]


   if login.email== thisuser.email and check_password(login.passwd, 
thisuser.password):


 web.setcookie('username', thisuser.email)


 else:


   web.setcookie('rss_flash_message', 'Please try again with correct email 
and password')


 web.redirect('/')





class logout:


   def GET(self):


 web.setcookie('username', '')


 web.redirect('/')

Please help me out thanks

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


Re: [Tutor] Tutor Digest, Vol 32, Issue 72

2006-10-17 Thread Pine Marten

(in reference to a question I had about how to simply save the content of a 
textCtrl to a text file)

>#Okay, here is the function we need to change.
>
>
> def OnSaveButton(self, event):
> #from John's save(event) function:
> #
> #savefile = open(self.filename, 'w')
> #savefile.write(myTextBox.GetValue())
> #savefile.close()
>
> savefile = open('test.txt','w')
> #if you don't want 'test.txt' try using a variable.
>
>
> savefile.write(self.textCtrl1.GetValue())
> #textCtrl1 is an attribute of your Frame1 class.
>
>
>
> savefile.close()
> #then we just save it.
>
>Do you understand which parts of John's examples were changed and why?
>Hope That Helps,
>-Luke

I tried it and it did work this time, thanks so much.  Your effort may keep 
me trying bit by bit to gain a little profiency.

And yes, I believe I see how much of this ought to work now.  I am just 
going to keep going over how one assigns a variable like savefile to a built 
in function like open() but then attaches a method to it such as when you 
write savefile.write.  I think if I work with that enough I will come to see 
it as intuitive; for now it still is unintuitive.   Thanks again.

_
Stay in touch with old friends and meet new ones with Windows Live Spaces 
http://clk.atdmt.com/MSN/go/msnnkwsp007001msn/direct/01/?href=http://spaces.live.com/spacesapi.aspx?wx_action=create&wx_url=/friends.aspx&mkt=en-us

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


Re: [Tutor] extracting numbers from a list

2006-10-17 Thread Danny Yoo


On Mon, 16 Oct 2006, kumar s wrote:

> I have a simple question to ask tutors:
>
> list A :
>
> a = [10,15,18,20,25,30,40]


Hi Kumar,

If you're concerned about correctness, I'd recommend that you try thinking 
about the problem inductively.  An inductive definition for what you're 
asking is straightforward to state in about three or four lines of code. 
I'll try to go through it slowly so you see what the reasoning behind it 
is.  The code sketch above uses a technique that you should already know 
called "mathematical induction."

 http://en.wikipedia.org/wiki/Mathematical_induction


Let's say we're designing a function called getSpans().  Here are some 
sample behavior we'd like from it:

 getSpans([10, 15]) = [(10, 15)]
 getSpans([10, 15, 18]) = [(10, 15), (16, 18)]
 getSpans([10, 15, 18, 20]) = [(10, 15), (16, 18), (19, 20)]

Would you agree that this is reasonable output for a function like this? 
getSpans() takes a list of numbers, and returns a list of pairs of 
numbers.


There is one "base" case to this problem.  The smallest list we'd like to 
consider is a list of two elements.  If we see that, then we're happy, 
because the answer is really simple:

 getSpans([a, b]) = [(a, b)]


Otherwise, let's imagine a list that's a bit longer, with three elements. 
Concretely, we know that this is going to look like:

 getSpans([a, b, c]) = [(a, b), (b+1, c)]

But another way to say this, though is that:

 getSpans([a, b, c]) = [(a, b)] + getSpans([b+1, c])

That is, we try to restate the problem in terms of smaller subproblems.



Let's look at what the case for four elements might look like:

 getSpans([a, b, c, d]) = [(a, b), (b+1, c), (c+1, d)]

Concretely, we know that that's the list of spans we'd like to see.  But 
if we think about it, we might also restate this as:

 getSpans([a, b, c, d]) = [a, b] + getSpans([b+1, c, d])

because getSpans([b+1, c, d]) is going to give us:

 [(b+1, c), (c+1, d)]

All we need to do is add on [(a, b)] to that to get the complete answer to 
getSpans([a, b, c, d]).


Generally, for any particular list L that's longer than two elements:

 getExons(L) = [L[0:2]] + getExons([L[1] + 1] + L[2:])

When we work inductively, all we really need to think about is "base case" 
and "inductive case": the solution will often just fall through from 
stating those two cases.  An inductively-designed function is going to 
look something like:

 def solve(input):
 if input looks like a base-case:
 handle that directly in a base-case way
 else:
 break up the problem into smaller pieces
 that we assume can be solve()d by induction

The inductive definition above is slightly inefficient because we're doing 
physical list slicing.  Rewriting it to use loops and list indicies 
instead of slicing is a little harder, but not much harder.

Another example: how do we add up a list of numbers?  If there's just one 
number, that must be the sum.  Otherwise, we can add up the first number 
to the sum of the rest of the numbers.

#
def mysum(L):
 if len(L) == 1:
 return L[0]
 else:
 return L[0] + mysum(L[1:])
#

It's a funky way of doing this, but this is a real definition that works 
(modulo limits in Python's recursion implementation).  It's inefficient, 
but it's easy to state and reason about.  I'm assuming you're more 
interested in correctness than efficiency at the moment.  Get it correct 
first, then if you really need to, work to get it fast.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 32, Issue 72

2006-10-17 Thread Luke Paireepinart

> I tried it and it did work this time, thanks so much.  Your effort may keep 
> me trying bit by bit to gain a little profiency.
>   
I'm glad that you're not going to give up just yet!  Don't worry, I have 
much more effort in store for you :)
> And yes, I believe I see how much of this ought to work now.  I am just 
> going to keep going over how one assigns a variable like savefile to a built 
> in function like open() but then attaches a method to it such as when you 
> write savefile.write.  I think if I work with that enough I will come to see 
> it as intuitive; for now it still is unintuitive.   Thanks again.
>   
Okay, I think I can explain this :)

Starting from the beginning:
a variable is a name that refers to an object.
it's nothing more than this.
It can refer to any type of object, a class, a class instance, a class 
method, a function, a class attribute,
a list, a tuple, whatever.  It's just a way that the programmer can tie 
a name to an object so it can be used later.

A function is a collection of expressions.
There are different types of functions.
This is what they do:
Takes zero to many inputs, and returns (outputs) one object.
Takes zero to many inputs, and modifies something outside of the function.
Takes zero to many inputs, and modifies something outside of the 
function, and returns (outputs) one object.

The first kind is the most conventional function.
The second kind is called a null or void function, because it doesn't 
return anything.
The point of these functions are their side-effects.
The third kind is something that you should avoid, which is a function 
that has side-effects as well as a return.

Here are examples of these:

#first type
def add_five(aNumber):
return aNumber + 5

#second type
def append_five(aList):
aList.append(5)

#third type
def append_and_add_five(aList):
aList.append(5)
return aList[0] + 5

#---

And testing them:
 >>> add_five(5)
10
 >>> a_list = [1,2,3,4]
 >>> append_five(a_list)
 >>> print a_list
[1,2,3,4,5]
 >>> a_list = [1,2,3,4]
 >>> append_and_add_five(a_list)
6
 >>> print a_list
[1,2,3,4,5]


#-

Some things to note:
You have a list a_list in the global scope that has the value [1,2,3,4].
when you pass it to the append_five function as 'aList',
and then print it out, a_list is [1,2,3,4,5].
This is because python doesn't pass _copies_ of variables to functions,
it passes what that variable is referring to, UNLESS the variable is 
immutable (you can't change it.)
For immutable variables, a new object will be created to contain the value.
This only makes a difference with lists, because lists are mutable.
A good way to rationalize this:

#since integers are immutable, these actually refer to two separate 
copies of an int object containing a 5.
 >>> a = b = 5
 >>> a += 5
 >>> a
10
 >>> b
5

#since lists are mutable, these refer to the same object.
 >>> a = b = ['hello,']
 >>> a.append('world!')
 >>> a
['hello,','world!']
 >>> b
['hello,','world!']

So think of it like this:

aVariable = 1
def aFunction(anotherVariable):
print anotherVariable
#... other useful stuff

When you make the call aFunction(aVariable)
what's happening is this:

anotherVariable = aVariable
print anotherVariable
#  other useful stuff -

It's slightly more complicated than this, (namespaces and such), but 
that's the main idea.

so this example:

aList = [1,2,3,4]
def aFunction(anotherList):
print anotherList
#... other useful stuff 

when you make the call aFunction(aList)
it's doing
anotherList = aList
print anotherList
# --- other useful stuff 

and as we saw above, if you do a = b, and b = a list, then a is the SAME 
list, not a COPY of that list.
Hope that makes sense.

Also, note that 'print' is in itself a side-effect, because it's 
modifying things that are outside the function,
so if you have a function printing things, you shouldn't have that 
function return anything.
Or so I've been told after a year of Computer Science courses :)


The reason I explained this is to hopefully make the next section I'll 
explain more clear.

>going to keep going over how one assigns a variable like savefile to a built 
>in function like open() but then attaches a method to it such as when you 
>write savefile.write.  I think if I work with that enough I will come to see 
>it as intuitive; for now it still is unintuitive.   Thanks again.

Okay, you're thinking of this in the wrong way.

#given this definition,
def aFunction(a):
print a

 >>> myFunction = aFunction
 >>> myFunction

 >>> aFunction


That is what assigning a variable to a function looks like.
What I was doing was something completely different.

 >>> myFunction = aFunction('hello') #notice the parenthesis!
hello

Do you see what the difference is?
Because functions are objects, you can assign variables to them if you want!
You can do a = b= c= d= e= aFunction
and call all of these the same way.
However, they are just references to the 

Re: [Tutor] Searching list items.

2006-10-17 Thread Chris Hengge
Not sure if you were challenging me to think, or asking me, but I was wanting to "line" to be printed... as in the string from the list. What I got with re was what I'm assuming was a memory address. 
On 10/17/06, Danny Yoo <[EMAIL PROTECTED]> wrote:
> I remove those lines, but I was trying to use> for line in contents:>   result = re.search("something", line)>   print result'result' here is going to either be None, as you've seen, or a "match"
object.  We have several options available to use once we have amatch.  Take a look at a few of the methods in here: http://www.python.org/doc/lib/match-objects.html
Printing a match object itself won't be too informative.  What would youlike to show up if there is some match?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A puzzle for you

2006-10-17 Thread Bob Gailer
John Fouhy wrote:
> >From the python_dev LiveJournal community ---
>
> Predict the outcome of the following code:
>
> ##
> from random import *
> seed()
> [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0]
> ##
>
>   
Well the discussion did not go very far! You got my "prediction" and one 
execution.

It appears that (despite the docs) a dict is OK as an argument. choice 
uses len() to get the # of elements, picks a number between 0 and 
len()-1, and uses [] to access the chosen element. len() and [] both 
work with dicts.

So you have built a dict of 1000 items with keys between 1 and 1000, all 
values 0. Then you have give choice 693 tries to pick a key value other 
than 0. One 0 raises a key not found exception. No 0s raises no 
exception and the expression returns 0.

-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] Searching list items.

2006-10-17 Thread Luke Paireepinart
Chris Hengge wrote:
> Not sure if you were challenging me to think, or asking me, but I was 
> wanting to "line" to be printed... as in the string from the list. 
> What I got with re was what I'm assuming was a memory address.
What you got was an object.  If you try to print an object, all you get 
is the name of the object and the memory address of the object.
def aFunction():
print 'hi'

 >>> x = aFunction
 >>> print x


This is pretty useless, as Danny said.
what you want to do is actually use the object.
 >>> x()
hi

or without the intermediate variable:
 >>> aFunction()
hi

When you do a re search, you get a match object, which has methods such 
as...
well, Danny already gave you the site.
>
> match.  Take a look at a few of the methods in here:
>
>  http://www.python.org/doc/lib/match-objects.html
> 
>

Does this explanation help?

so if you just want to print the line, all you would do is check whether 
the re.search() call returned None or a match object.

As John Fouhy said:

for line in contents:
m = re.search('something', line)
if m:
print line[m.start():m.end()]

This example prints the portion of the line that matched the string you're 
searching for.

if you just want to print the line if it matches,
simply change the last line in the example to 'print line'.
note that the line
'if m'
could be rewritten
'if m != None:'

Or even (this may be Too Much Magic, so beware ;) )
'if m is not None'

For more advanced matching, you can actually use the match object that 
is returned.
but if you're just searching for a substring, then this will work.
Another good reason to use regular expressions is if you wanted to find, 
say,
the substring 'substring' with a 2-digit number on the end,
you'd have to do something like
substrs = ['substring'+str(a).zfill(2) for a in range(0,100)]

then
for item in substrs:
if item in line:
   print line

Whereas with a regular expression, you'd just do
regexp = re.compile('something\d\d')

then
if regexp.search(line):
print line

Computationally the last example should be much more efficient.
clearly it's also more complicated if you don't know regular expressions 
very well.
However, the substrs example is not too great either when it comes to 
readability.

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