Re: [Tutor] Ooer, OT Lisp

2005-01-21 Thread Danny Yoo


On Thu, 20 Jan 2005, Bill Mill wrote:

> There is no "standard" implementation of lisp, so sockets and os access
> all vary by implementation. Furthermore, the docs are sketchy and hard
> to read with all of the lisps I've tried.

Hi Liam,

Scheme is a recent dialect of Lisp that seems to be well-regarded.
DrScheme is one of the very active implementations of Scheme:

http://www.drscheme.org/

and has a comprehensive set of documentation:

http://download.plt-scheme.org/doc/


> > 5) Are you able to point me towards a simplified explanation of how
> > the 'syntaxless' language can write programmes?

Brian mentioned one of my favorite books: "Structure and Interpretation of
Computer Programs":

http://mitpress.mit.edu/sicp/

If you want to do a crash course into how Lisp-languages work, I can't
think of a faster way than to look at the first few pages of it.

http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html

pretty much shows the core of Lisp programs.  There's even a set of video
lectures from the SICP authors that's freely available:

http://swiss.csail.mit.edu/classes/6.001/abelson-sussman-lectures/


The neat thing about Scheme is that, once you get beyond the syntax, it
starts to feel a bit like Python.  *grin* Perhaps that should be the other
way around.


Best of wishes to you!

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


[Tutor] Combination

2005-01-21 Thread Guillermo Fernandez Castellanos
Hi,

I'm trying to take a list and find all the unique combinations of that list.

I mean:
if I enter (1,2,3,4,5) and I watn combinations of 3, I want to find:
(1,2,3) but then not (2,1,3), (3,1,2),...
(1,2,4)
(1,2,5)
(2,3,5)
(3,4,5)

The thing is, I want to do it as a generic function, where I pass a
list, and the length of the combination I want,

For the pervious example, it would be:
createComb([1,2,3,4,5],3)

I have no idea how to do it in a generic way.
For a given list and a length of 4 I did this:
def createComb(positions):
"""Returns all possible combinations of position of nbUnit units"""
uniq={}
result=[]
for p1 in positions:
for p2 in positions:
for p3 in positions:
for p4 in positions:
uniq[p1]=0
uniq[p2]=0
uniq[p3]=0
uniq[p4]=0
if len(uniq)==4:
result.append([p1,p2,p3,p4])
uniq={}
return result

but is not very elegant...

Any suggestion?

Thanks,

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


Re: [Tutor] Combination

2005-01-21 Thread Kent Johnson
This question comes up regularly on comp.lang.python. Search the archives for 'combinations' to find 
*many* discussions of how to do it. Also there are several recipes in the cookbook.
http://groups-beta.google.com/group/comp.lang.python?hl=en&lr=&ie=UTF-8&c2coff=1
http://aspn.activestate.com/ASPN/Cookbook/Python

Kent
Guillermo Fernandez Castellanos wrote:
Hi,
I'm trying to take a list and find all the unique combinations of that list.
I mean:
if I enter (1,2,3,4,5) and I watn combinations of 3, I want to find:
(1,2,3) but then not (2,1,3), (3,1,2),...
(1,2,4)
(1,2,5)
(2,3,5)
(3,4,5)
The thing is, I want to do it as a generic function, where I pass a
list, and the length of the combination I want,
For the pervious example, it would be:
createComb([1,2,3,4,5],3)
I have no idea how to do it in a generic way.
For a given list and a length of 4 I did this:
def createComb(positions):
"""Returns all possible combinations of position of nbUnit units"""
uniq={}
result=[]
for p1 in positions:
for p2 in positions:
for p3 in positions:
for p4 in positions:
uniq[p1]=0
uniq[p2]=0
uniq[p3]=0
uniq[p4]=0
if len(uniq)==4:
result.append([p1,p2,p3,p4])
uniq={}
return result
but is not very elegant...
Any suggestion?
Thanks,
G
___
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] Ooer, OT Lisp

2005-01-21 Thread Kent Johnson
Liam Clarke wrote:
Oops, 

and OT ~ Has anyone used Lisp? I've been reading Paul Graham's essays
on how great Lisp is, and how Python is near to implementing features
Lisp had in the 60's. Also found the concept of macros interesting.
I've dabbled a bit with Lisp in school and I read most of the Wizard book (see other posts for 
references). Another good book for learning the basics is "The Little Schemer".

Learning Lisp and reading the Wizard book will definitely broaden your perspective of programming 
languages. And using recursion will never be a problem again.

My personal opinion and preference is for Python, but that shouldn't be a 
surprise :-)
The rest of this post is my opinion as a Python bigot and Lisp newbie...
Lisp is kind of minimalist. It gives you a few *extremely* powerful tools, a little bit of syntax to 
glue it together, and lets you build whatever you want on top of that.

To me, it ended up seeming like an awful lot of work, like everything is built from scratch. Python 
has more syntax and less power. To me it has enough power to do what I want to do and I like the syntax.

This blog entry  
says of Python,
"It's like they stole Lisp, and give it sh*tty syntax!" and
"perhaps Python was the subset of Lisp that was understandable by C++ 
programmers"
To me it's not sh*tty syntax, it's usable syntax. And it is the subset of Lisp that I need to get 
real work done.

I've read some of Paul Graham's stuff and I'm pretty sure a Lisp bigot would tell me I just haven't 
learned enough Lisp to appreciate it. I'm even willing to concede that he might be right :-) but 
Python works for me.

This page gives a good taste of the debate... 
http://c2.com/cgi/wiki?SmugLispWeenie
Kent
Queries - 

1) Anyone here familiar with both?
2) If so, which would you rate as more powerful?
3) What's with all those parentheses?
4)  Perhaps the powerful question's a bit vague, how about ease of
use? I like that the simplest Lisp expression is - , but those
brackets
5) Are you able to point me towards a simplified explanation of how
the 'syntaxless' language can write programmes?
Sorry to play 20 questions.
Regards, 

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


Re: [Tutor] Unexpected result from decimal

2005-01-21 Thread Jacob S.
Okay, so how do I get decimal to set precision of *significant digits*?
Why have a decimal.getcontext().prec if it doesn't provide a useful result?
The number of digits in a number is irrelevant to that numbers value.
It just doesn't make sense to me.
I tried quantize the other day and it didn't work -- gave some sort of 
error,
I don't remember what it was, and I can't get it to do it again today.
So, I guess it works now and I can go back to wondering why
getcontext().prec = a
is not equal to
quantize("0."+"0"*(a-1)+"1")

Thanks,
Jacob
Comments to everyone's post below.
>>> import decimal
>>> decimal.getcontext().prec = 2
>>> a = decimal.Decimal(2)
>>> b = decimal.Decimal(3)
>>> 100*a/b
Decimal("67")
>>> print 100*a/b
This prints "67".
try -
a=decimal.Decimal(2.0)
This will not work.  You can't convert a float directly to a 
decimal.Decimal
(I believe this is so that you are forced to understand that there are
precision issues involved).  'a = decimal.Decimal("2.0")' will do what you
meant, though.
Decimal is a totally different type from integers and floats. It is not 
affected by float
division problems. It is not my type, it is in the standard distribution of 
python 2.4
You have to represent floats as strings, because if you don't, then a float 
with lost precision is
used instead of the exact precision.
For example -- 
If I pass 1.1 to decimal.Decimal, it will receive 1.101 or something 
like that so it can try to
keep perfect precision on a float that started from the beginning without 
it. This is what decimal is
trying to resolve in the first place!
However, if I pass a string, strings aren't affected by binary floating 
point problems and they can
be kept in perfect precision from the beginning.

b = decimal.Decimal(3)
print 100*a/b
However, this will print out "67", just as the above did.  The reason is 
the
one that Tim outlined: precision isn't the number of digits after the
decimal place - when I was at school the latter was called "decimal 
places"
and precision was "significant digits".

Jacob- one slight flaw/quirk in Python is if you want floating point
computations you have to specify a floating point.
[...]
Same as writing 100/3.0 as opposed to 100/3. Try it.
Note that you can do 'from __future__ import division' and 100/3 will be 
the
same as 100/3.0 (and 100//3 will give you 3).
See above
=Tony.Meyer
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unexpected result from decimal

2005-01-21 Thread Kent Johnson
Jacob S. wrote:
Okay, so how do I get decimal to set precision of *significant digits*?
That is exactly what it is doing. getcontext().prec sets how many digits are used to represent the 
mantissa of the number.

Have you taken any physics classes? What is 1000/7 to two significant digits? It is 140, not 142.85, 
which has *5* significant digits. Changing prec has just this effect:
 >>> from decimal import *
 >>> getcontext().prec = 2
 >>> one = Decimal(1)
 >>> seven = Decimal(7)
 >>> one/seven
Decimal("0.14")
 >>> 1000 * one/seven
Decimal("1.4E+2")
 >>> getcontext().prec = 20
 >>> one/seven
Decimal("0.14285714285714285714")
 >>> 1000 * one/seven
Decimal("142.85714285714285714")

Why have a decimal.getcontext().prec if it doesn't provide a useful result?
The number of digits in a number is irrelevant to that numbers value.
It just doesn't make sense to me.
It's just like choosing between float and double in Java or C - it sets the precision of the 
underlying representation. It is a tradeoff between accuracy, speed, and memory use.

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


[Tutor] Importing multiple files as a single module?

2005-01-21 Thread Max Noel
Hi everyone,
	Having learnt OOP with C++, and most of my OOP experience being with 
Java, I'm used to storing my classes in one file for each class. I find 
it tidier and easier to read/debug.
	However, when I try to do the same in Python, each file corresponds to 
a module with a single class in it.

	Is there a way to obtain the same result in Python as in Java? That 
is, I'd like to have the following on my hard drive:

foo/
Bar.py
Baz.py
	Where Bar.py and Baz.py each contain a single class (Bar and Baz). 
Then, from Python, I'd import the foo module (import foo) and then 
access the classes with foo.Bar and foo.Baz (instead of foo.Bar.Bar and 
foo.Baz.Baz, which is what I have now). Being able to use Bar in Baz.py 
would of course be a nice side effect.

	Any ideas? Or am I trying to do things in a very non-Pythonic way? If 
so, how am I supposed to organize my OOP code, especially given the 
absence of a "real" IDE for Python?

Thanks for your attention,
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

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


Re: [Tutor] Importing multiple files as a single module?

2005-01-21 Thread Kent Johnson
I think this will work:
in foo/__init__.py put
from Bar import Bar
from Baz import Baz
or whatever variations of this you like.
Any names defined in the package __init__.py are available to other code as 
package attribute.
Kent
Max Noel wrote:
Hi everyone,
Having learnt OOP with C++, and most of my OOP experience being with 
Java, I'm used to storing my classes in one file for each class. I find 
it tidier and easier to read/debug.
However, when I try to do the same in Python, each file corresponds 
to a module with a single class in it.

Is there a way to obtain the same result in Python as in Java? That 
is, I'd like to have the following on my hard drive:

foo/
Bar.py
Baz.py
Where Bar.py and Baz.py each contain a single class (Bar and Baz). 
Then, from Python, I'd import the foo module (import foo) and then 
access the classes with foo.Bar and foo.Baz (instead of foo.Bar.Bar and 
foo.Baz.Baz, which is what I have now). Being able to use Bar in Baz.py 
would of course be a nice side effect.

Any ideas? Or am I trying to do things in a very non-Pythonic way? 
If so, how am I supposed to organize my OOP code, especially given the 
absence of a "real" IDE for Python?

Thanks for your attention,
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting and 
sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

___
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] Importing multiple files as a single module?

2005-01-21 Thread Ryan Davis
I'm having the same problem, and am eager to hear the responses.  As far as a 
"real" IDE, emacs works pretty well, and check out
Komodo, the ActiveState IDE: 
http://www.activestate.com/Products/Komodo/


Thanks,
Ryan 

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Max Noel
Sent: Friday, January 21, 2005 11:33 AM
To: Tutor Tutor
Subject: [Tutor] Importing multiple files as a single module?

Hi everyone,

Having learnt OOP with C++, and most of my OOP experience being with 
Java, I'm used to storing my classes in one file for each class. I find 
it tidier and easier to read/debug.
However, when I try to do the same in Python, each file corresponds to 
a module with a single class in it.

Is there a way to obtain the same result in Python as in Java? That 
is, I'd like to have the following on my hard drive:

foo/
Bar.py
Baz.py

Where Bar.py and Baz.py each contain a single class (Bar and Baz). 
Then, from Python, I'd import the foo module (import foo) and then 
access the classes with foo.Bar and foo.Baz (instead of foo.Bar.Bar and 
foo.Baz.Baz, which is what I have now). Being able to use Bar in Baz.py 
would of course be a nice side effect.

Any ideas? Or am I trying to do things in a very non-Pythonic way? If 
so, how am I supposed to organize my OOP code, especially given the 
absence of a "real" IDE for Python?

Thanks for your attention,
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

___
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] Importing multiple files as a single module?

2005-01-21 Thread Danny Yoo


On Fri, 21 Jan 2005, Kent Johnson wrote:

> I think this will work:
> in foo/__init__.py put
> from Bar import Bar
> from Baz import Baz
>
> or whatever variations of this you like.
>
> Any names defined in the package __init__.py are available to other code
> as package attribute.


Hi Max,

For more information on packages, we can take a look at:

http://www.python.org/doc/tut/node8.html#SECTION00840


Best of wishes!

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


Re: [Tutor] Combination

2005-01-21 Thread Danny Yoo


On Fri, 21 Jan 2005, Guillermo Fernandez Castellanos wrote:

> I'm trying to take a list and find all the unique combinations of that
> list.
>
> I mean:
> if I enter (1,2,3,4,5) and I watn combinations of 3, I want to find:
> (1,2,3) but then not (2,1,3), (3,1,2),...
> (1,2,4)
> (1,2,5)
> (2,3,5)
> (3,4,5)


Hi Guillermo,


There is a clean recursive way to define this.  I'll try to sketch out how
one can go about deriving the function you're thinking of.


Let's say that we have a list L,

 [1, 2, 3]

and we want to create all combinations of elements in that list.  Let's
call the function that does this "createComb()".  How do we calculate
createComb([1, 2, 3])?


We can just start writing it out, but let's try a slightly different
approach.  Imagine for the moment that we can construct createComb([2,
3]):

createComb([2, 3])   -> [[2, 3], [2], [3]]


We know, just from doing things by hand, that createComb([1, 2, 3]) of the
whole list will look like:

createComb([1, 2, 3) -> [[1, 2, 3], [1, 2], [1, 3],
[2, 3],[2],[3]]

If we compare createComb([1, 2, 3]) and createComb([2, 3]), we might be
able to see that they're actually very similar to each other.


Does this make sense so far?  Please feel free to ask questions about
this.



Good luck!

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


Re: [Tutor] Combination

2005-01-21 Thread Danny Yoo


On Fri, 21 Jan 2005, Danny Yoo wrote:

> > I mean:
> > if I enter (1,2,3,4,5) and I watn combinations of 3, I want to find:
> > (1,2,3) but then not (2,1,3), (3,1,2),...
> > (1,2,4)
> > (1,2,5)
> > (2,3,5)
> > (3,4,5)
>
>
> There is a clean recursive way to define this.

Hi Guillermo,


Gaaa; I screwed up slightly.  *grin*

I just wanted to clarify: the function that I'm sketching out is not
exactly the function that you're thinking of.  I'm doing more of a "give
me all the subsets of L" kind of thing.

But if you can understand how to get all the subsets, you should be able
to figure out how to get all the combinations of 'k' elements, because
they're really similar problems.

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


Re: [Tutor] Syntactical question / OT Lisp

2005-01-21 Thread Alan Gauld
> foo.py - 
> 
> import parrot
> 
> class Bar(model.Background):
> 
> def __initialize__(self, event):
>  #Just a pythoncard variant on init
>  self.config=self.loadCfg()
> 
> 
>def loadCfg():
> #get some cfg stuff, return as dict
> return cfgDict
> 
>def on_aBtn_mouseClick(self, event):
>  parrot.Sketch()
> 
> app=Bar(main.application)
> app.mainloop()
> 
> 
> If I wanted the function parrot.Sketch() to access that config
> dictionary, I would reference it as
> 
> foo.app.config?

You could but it would be very bad practice and much better 
to pass the object reference into Sketch.

def on_aBtn_mouseClick(self, event):
  parrot.Sketch(self)

def Sketch(anObject):
   code ...
   configINfo = anObject.config

Even better make the app object return the actual config 
bits that parrot needs via a method:

def Sketch(anObject):
   ... code...
   myConfigItem1,mycOnfig2 = anObject.getSketchConfig()


All of these options make both parrot and the foo object 
more easily reusable and much less liable to break when 
you make changes to the config data.

Alan G
(Back from a week's trainig camp...)

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


Re: [Tutor] Ooer, OT Lisp

2005-01-21 Thread Alan Gauld
> 1) Anyone here familiar with both?

Yes at least two of us - DAnny has used Lisp/Scheme.

> 2) If so, which would you rate as more powerful?

Lisp by a long long way. Its more mature and has every 
bell and whistle going. Of course its much much harder 
to become an expert in Lisp for the same reason.

> 3) What's with all those parentheses?

Read my page on Functional Programming.
Basically every Lisp program statement is an expression, 
and like most complex expressions you need parens...
Basically a Lisp program is just a whole heap of nested 
expressions!

It doesn't really need them of course but its one of the 
things that makes Lisp very regular in a math sense, 
very pure in approach, and why the academics say its 
the only "beautiful" language.

> 4)  Perhaps the powerful question's a bit vague, how about ease of
> use? I like that the simplest Lisp expression is - , but those
> brackets

Its very easy to use once you learn it. But its initially 
different to traditional programming languages (although 
since it was invented in the early 60s - late 50's 
even??? - it is ttraditional in itself!)

> 5) Are you able to point me towards a simplified explanation of how
> the 'syntaxless' language can write programmes?

Try the How To Design Programs (htdp.org) and 
Structure & Interpretation of Computer Programs (sicp.org) 
web sites. Both are excellent books published by MIT for 
free on the web. Both use Scheme which is a close relative 
of Common Lisp.

I strongly recommend you check them out your programming 
in general will improve a lot from reading either book. 
The first is easier for non maths folks, SICP is a 
software engineering classic textbook.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

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


RE: [Tutor] Ooer, OT Lisp

2005-01-21 Thread John Purser
Very interesting sites.  Thank you.

John Purser 

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Alan Gauld
Sent: Friday, January 21, 2005 14:33
To: Liam Clarke; Tutor Tutor
Subject: Re: [Tutor] Ooer, OT Lisp

> 1) Anyone here familiar with both?

Yes at least two of us - DAnny has used Lisp/Scheme.

> 2) If so, which would you rate as more powerful?

Lisp by a long long way. Its more mature and has every 
bell and whistle going. Of course its much much harder 
to become an expert in Lisp for the same reason.

> 3) What's with all those parentheses?

Read my page on Functional Programming.
Basically every Lisp program statement is an expression, 
and like most complex expressions you need parens...
Basically a Lisp program is just a whole heap of nested 
expressions!

It doesn't really need them of course but its one of the 
things that makes Lisp very regular in a math sense, 
very pure in approach, and why the academics say its 
the only "beautiful" language.

> 4)  Perhaps the powerful question's a bit vague, how about ease of
> use? I like that the simplest Lisp expression is - , but those
> brackets

Its very easy to use once you learn it. But its initially 
different to traditional programming languages (although 
since it was invented in the early 60s - late 50's 
even??? - it is ttraditional in itself!)

> 5) Are you able to point me towards a simplified explanation of how
> the 'syntaxless' language can write programmes?

Try the How To Design Programs (htdp.org) and 
Structure & Interpretation of Computer Programs (sicp.org) 
web sites. Both are excellent books published by MIT for 
free on the web. Both use Scheme which is a close relative 
of Common Lisp.

I strongly recommend you check them out your programming 
in general will improve a lot from reading either book. 
The first is easier for non maths folks, SICP is a 
software engineering classic textbook.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
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] Re: Fw: Please submit to tutor list: dictionary update prob

2005-01-21 Thread Jacob S.
Just one question...
Why are you off the list?
I see no point.
If you want to stop getting the mail, you can change the options of your 
list account online...
That's the only reason I see...

Let's see -- reasons
1. Cost -- No, it's free
2. Security -- If you were subscribed to it once, it's too late to worry 
about that (Though there is no reason to)
   a. There is an option (in Outlook Express at least) to make your name 
invisible to others when emailing
   b. You can make your name invisible on the subscriber's list on the 
website by using the options in your account page

Anyone want to comment --  maybe a link to get him to the subscriber's 
option page?

HTH,
Jacob Schmidt 

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


[Tutor] glob or filter help

2005-01-21 Thread Jay Loden
I have the following code in my updates script (gets the five most recent 
updated files on my site)

def get_fles(exts, upd_dir):
 '''return list of all the files matching any extensions in list exts'''
 fle_list = [] 
 for each in exts:
  cmd = upd_dir + "*." + each
  ext_ls = glob.glob(cmd)
  fle_list = fle_list + ext_ls
 return filter(notlink, fle_list)

I wanted to just get one list, of all the .htm and .exe files in my upd_dir.  
I was trying to make a far more elegant solution that what's above, that 
could generate a list through a filter.  Is there a way to trim the code down 
to something that does ONE sort through the directory and picks up the .htm 
and .exe files? (note, it is not necessary for this to recurse through 
subdirectories in the upd_dir).  I have cmd defined above because calling
"glob.glob(upd_dir + "*." + each) returned the error "cannot concatenate 
string and list objects" - is this the only way around that, or is there a 
better way?

Also in the above code, "notlink" is just a function that returns True if 
"islink()" returns truethere has to be a better way to use this with 
filter(), how can i make filter use "if islink()!=true" as its condition?

The script is working now, (I know, I know, if it ain't broke, don't fix 
it...) but I want to be a better programmer so more elegant solutions are 
accepted gratefully. 
-Jay
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] read line x from a file

2005-01-21 Thread J. M. Strother
I have  a text file containing 336 records.
I can read and print out the whole file without any problem.
What I want to do is read and print out one record only (chosen at 
random). So I need to get to record x, select it, and then print it (or 
store it in a variable).
Can anyone tell me now to do this?

I'm new to Python and programming, so sorry if this is very basic. Thanks.
jon
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] read line x from a file

2005-01-21 Thread Orri Ganel




J. M. Strother wrote:
I have  a
text file containing 336 records.
  
I can read and print out the whole file without any problem.
  
What I want to do is read and print out one record only (chosen at
random). So I need to get to record x, select it, and then print it (or
store it in a variable).
  
Can anyone tell me now to do this?
  
  
I'm new to Python and programming, so sorry if this is very basic.
Thanks.
  
  
jon
  
___
  
Tutor maillist  -  Tutor@python.org
  
http://mail.python.org/mailman/listinfo/tutor
  
  

Well, one way to do this is to count newlines, assuming you know what
newline character your system uses.  For example (UNTESTED):

>>> test = open("test.txt","r")   ##
open the file
>>> newline = []
>>> tfile = test.read()
>>> for i in range(len(tfile)):   ## instead of 'for char in
tfile'
       if tfile[i] == '\n':      ## to make the index of each newline
          newline.append(i)      ## easier to find
>>> import random
>>> newl = random.choice(newline)
>>> print tfile[newl:tfile[newl:].index('\n')]   ## prints
tfile from the
## randomly selected newline index to the next newline index, or one
line
## prints data here
>>> test.close()

Now, this might not work, depending on whether or not '\n' is treated
as a single character in this case. If not, you have to do a whole lot
of the same sort of slicing as i did on the print line in order to find
each successive newline (with tfile.index("\n")).


HTH,
Orri

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


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


Re: [Tutor] read line x from a file

2005-01-21 Thread Jay Loden
One simple solution is to do: 

fle = open(file)
contents = file.readlines()
file.close()
print contents[x]  #or store this in a variable, whatever

-Jay

On Friday 21 January 2005 11:22, J. M. Strother wrote:
> I have  a text file containing 336 records.
> I can read and print out the whole file without any problem.
> What I want to do is read and print out one record only (chosen at
> random). So I need to get to record x, select it, and then print it (or
> store it in a variable).
> Can anyone tell me now to do this?
>
> I'm new to Python and programming, so sorry if this is very basic. Thanks.
>
> jon
> ___
> 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] read line x from a file

2005-01-21 Thread Orri Ganel




Jay Loden wrote:

  One simple solution is to do: 

fle = open(file)
contents = file.readlines()
file.close()
print contents[x]  #or store this in a variable, whatever

-Jay

On Friday 21 January 2005 11:22, J. M. Strother wrote:
  
  
I have  a text file containing 336 records.
I can read and print out the whole file without any problem.
What I want to do is read and print out one record only (chosen at
random). So I need to get to record x, select it, and then print it (or
store it in a variable).
Can anyone tell me now to do this?

I'm new to Python and programming, so sorry if this is very basic. Thanks.

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

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

Whoops! Sorta took the hard way on that one. readlines()
is by all means a much better way of doing this.
-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


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


[Tutor] Re: glob or filter help

2005-01-21 Thread Javier Ruere
Jay Loden wrote:
> I have the following code in my updates script (gets the five most recent 
> updated files on my site)
> 
> def get_fles(exts, upd_dir):
>  '''return list of all the files matching any extensions in list exts'''
>  fle_list = [] 
>  for each in exts:
>   cmd = upd_dir + "*." + each
>   ext_ls = glob.glob(cmd)
>   fle_list = fle_list + ext_ls
>  return filter(notlink, fle_list)
> 
> I wanted to just get one list, of all the .htm and .exe files in my upd_dir.  
> I was trying to make a far more elegant solution that what's above, that 
> could generate a list through a filter.  Is there a way to trim the code down 
> to something that does ONE sort through the directory and picks up the .htm 
> and .exe files? (note, it is not necessary for this to recurse through 
> subdirectories in the upd_dir).  I have cmd defined above because calling
> "glob.glob(upd_dir + "*." + each) returned the error "cannot concatenate 
> string and list objects" - is this the only way around that, or is there a 
> better way?

  How about:

>>> import os
>>> exts = ('gz', 'conf')
>>> upd_dir = '.'
>>> filter(lambda fn : fn.split('.')[-1] in exts, os.listdir(upd_dir))

  Do you like this better. It doesn't use glob and is terse.

> Also in the above code, "notlink" is just a function that returns True if 
> "islink()" returns truethere has to be a better way to use this with 
> filter(), how can i make filter use "if islink()!=true" as its condition?

  If the filter criteria is complex, it deserves it's own function:

>>> import os
>>> import os.path
>>> def get_files(exts, upd_dir):
... def criteria(filename):
... return filename.split('.')[-1] in exts \
... and not os.path.islink(filename)
... return filter(criteria, os.listdir(upd_dir))
...
>>> get_files(('gz', 'conf'), '.')
['dynfun.pdf.gz', 'twander-3.160.tar.gz', 'PyCon2004DocTestUnit.pdf.gz',
'arg23.txt.gz', '.fonts.conf']


Javier

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