Re: [Tutor] Request for help learning the right way to deal with listsin lists

2010-07-13 Thread Alan Gauld


"Siren Saren"  wrote

say I have a list that's a composite of two elements:
books and key pages / albums and favorite tracks /
medicines and times taken, whatever.


Thats a good scenario for using a dictionary containing
a list or tuple per key.


To make a program that does something to the
first set of elements based on the second set of elements,


I'm not quite sure what you mean by this though...?


if I am planning to, for example, tear out these key
pages and make a wall hanging. Am I right to think
that I want to get them into a form that clearly relates
them to each other from the outset?


Yes, you should always try to find a data structure that
reflects the problem. It will naturally lead to simpler algorithms
and cleaner code.


Does a dictionary make sense-- I've read that I should
expect to put a lot of my data into dictionaries?


Yes a dictionary is a good structure for random lookups
based on a unique key that returns related data.


a. Make a sublist of the Books.


You don't need a sublist, just use the dictionary.


b. Look each up book in the main list to get an index values


You don't need index values, just use the dictionary directly.


For book in Books:
A dictionary should map the book to a list of all the elements
in the main list that fall between the book's index value and
the next book's index value


The dictionary returns the list of pages directly.


I keep coming up with embedded loops to express this
but I simultaneously feel like I am missing a third layer


You need a loop over the dictionary and possibly a loop over the 
pages:


for book, pages in Books.items():
   print book
   for page in pages:
print 'page: ', page

If the data gets more complex you could put the data into a class:

class Book:
 def __init__(self, title, pages=[]):
 self.title = title
 self.pages = pages

Books = [ Book('War & Peace", [3,56,88]),
  Book("Huck Finn", [2,5,19]) ]

for book in Books:
print book.title, book.pages

Thre are many options, you need to decide which best suits your 
problem.


HTH,


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





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


[Tutor] Help

2010-07-13 Thread Dipo Elegbede
I was trying to write a code that prints prime numbers between 1 and 20.

I have by myself seen that something is wrong with my code and also my
brain.

Could anyone be kind enough to tell me what to do

Where I am confused is how to test for other numbers without one and the
number itself. It turns out that all numbers pass the condition I set so
that would presuppose that all numbers are prime which is not.

How exactly can I get it to run checks with other numbers such that it
doesn't include the number itself and 1.

The code is as follows:

for i in range(1,20):

if float(i) % 1 == 0 and float(i) % i == 0:
print i, 'is a prime number'


-- 
Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise Application
Development
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2010-07-13 Thread Nitin Pawar
Hi,

You have two different problems
1) Easiest algorithm to find a prime number
2) and then coding the algorithm

By my knowledge,The Sieve of Eratosthenes algorithm is the fastest to find a
prime number.
The algorithm works on the basis that if a number n is prime, then all
multiples of it are not prime

so based on that you can code

Thanks,
Nitin


On Tue, Jul 13, 2010 at 3:20 PM, Dipo Elegbede wrote:

> I was trying to write a code that prints prime numbers between 1 and 20.
>
> I have by myself seen that something is wrong with my code and also my
> brain.
>
> Could anyone be kind enough to tell me what to do
>
> Where I am confused is how to test for other numbers without one and the
> number itself. It turns out that all numbers pass the condition I set so
> that would presuppose that all numbers are prime which is not.
>
> How exactly can I get it to run checks with other numbers such that it
> doesn't include the number itself and 1.
>
> The code is as follows:
>
> for i in range(1,20):
>
> if float(i) % 1 == 0 and float(i) % i == 0:
> print i, 'is a prime number'
>
>
> --
> Elegbede Muhammed Oladipupo
> OCA
> +2348077682428
> +2347042171716
> www.dudupay.com
> Mobile Banking Solutions | Transaction Processing | Enterprise Application
> Development
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


Re: [Tutor] Help

2010-07-13 Thread Andre Engels
On Tue, Jul 13, 2010 at 11:50 AM, Dipo Elegbede  wrote:
> I was trying to write a code that prints prime numbers between 1 and 20.
>
> I have by myself seen that something is wrong with my code and also my
> brain.
>
> Could anyone be kind enough to tell me what to do
>
> Where I am confused is how to test for other numbers without one and the
> number itself. It turns out that all numbers pass the condition I set so
> that would presuppose that all numbers are prime which is not.
>
> How exactly can I get it to run checks with other numbers such that it
> doesn't include the number itself and 1.
>
> The code is as follows:
>
> for i in range(1,20):
>
>     if float(i) % 1 == 0 and float(i) % i == 0:
>     print i, 'is a prime number'

Your code only checks whether the number divides by 1 and itself. It
should check the numbers in between, and if _any_ divides the number,
decide it is not a prime number. This is best done in a separate
function (note: I am writing it here for clarity of the underlying
algorithm, there are various ways in which it could be made faster,
shorter or more Pythonic):

def isPrime(n):
divisorFound = False
for i in xrange(2, n):
if n % i == 0:
divisorFound = True
return not divisorFound # divisorFound is true if and only if
there is a number i (1http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2010-07-13 Thread Nitin Pawar
Adding to what Andre said,

another way of optimizing the problem would be
storing the prime number in the range you want to check an array and see if
the given number is divisible by any of those prime number

This improves the performance.

Thanks,
nitin

On Tue, Jul 13, 2010 at 3:52 PM, Andre Engels  wrote:

> On Tue, Jul 13, 2010 at 11:50 AM, Dipo Elegbede 
> wrote:
> > I was trying to write a code that prints prime numbers between 1 and 20.
> >
> > I have by myself seen that something is wrong with my code and also my
> > brain.
> >
> > Could anyone be kind enough to tell me what to do
> >
> > Where I am confused is how to test for other numbers without one and the
> > number itself. It turns out that all numbers pass the condition I set so
> > that would presuppose that all numbers are prime which is not.
> >
> > How exactly can I get it to run checks with other numbers such that it
> > doesn't include the number itself and 1.
> >
> > The code is as follows:
> >
> > for i in range(1,20):
> >
> > if float(i) % 1 == 0 and float(i) % i == 0:
> > print i, 'is a prime number'
>
> Your code only checks whether the number divides by 1 and itself. It
> should check the numbers in between, and if _any_ divides the number,
> decide it is not a prime number. This is best done in a separate
> function (note: I am writing it here for clarity of the underlying
> algorithm, there are various ways in which it could be made faster,
> shorter or more Pythonic):
>
> def isPrime(n):
>divisorFound = False
>for i in xrange(2, n):
>if n % i == 0:
>divisorFound = True
>return not divisorFound # divisorFound is true if and only if
> there is a number i (1
> for i in range(2,20):
>if isPrime(i):
> print i, 'is a prime number'
>
> By the way, do note that your cast to float is not a good idea. It
> probably won't hurt you in this case, but it definitely won't improve
> things. You'd much rather check exact equality with integers than with
> floats.
>
> --
> André Engels, andreeng...@gmail.com
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] Help

2010-07-13 Thread Dave Angel

Dipo Elegbede wrote:

I was trying to write a code that prints prime numbers between 1 and 20.

I have by myself seen that something is wrong with my code and also my
brain.

Could anyone be kind enough to tell me what to do

Where I am confused is how to test for other numbers without one and the
number itself. It turns out that all numbers pass the condition I set so
that would presuppose that all numbers are prime which is not.

How exactly can I get it to run checks with other numbers such that it
doesn't include the number itself and 1.

The code is as follows:

for i in range(1,20):

if float(i) % 1 == 0 and float(i) % i == 0:
print i, 'is a prime number'


  
Break the problem down.  Instead of solving the "print all the primes 
from 1 to 20", first solve the "Is a given number prime".


then once you have a solution to that one, write a loop that calls it 20 
times, printing its conclusions.


So suppose you have the number 12.  How would you manually decide if 
it's prime?  You'd find the remainder for all the numbers between 2 and 
11, inclusive, and if *any* of those came out zero, you'd say it's not 
prime.


Write a function isprime() that expresses exactly that, returning False 
if any of the modulos came out zero, and True if they're all okay.  The 
function will have a loop, and inside the loop have a single if statement.


Test the function by calling it explicitly with various values.  Then 
when you're comfortable with that, solve the bigger problem as stated.


DaveA

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


[Tutor] Response to responses about list of lists: a meta exercise in mailinglist recursion

2010-07-13 Thread Siren Saren




I'm not sure if there's a way to submit responses 'live' or
whether it's better to respond to subthreads at once or together, so I'll err
on the side of discretion and just send one response.  Thanks to each of you 
who tried to help me.  I've responded individually below. 

 

To summarize the discussion so far:


I wondered if there was a decent way to sort a list that
contained two lists, where each could be distinguished based on the list's 
sequence and
the elements' data characteristics.  As a subsidiary
question, I wondered if there was a data structure I should aspire to put the
data into once I had it sorted.


In response to the first question: the consensus seems to be
that there is no good way to sort a non-alternating one-to-many list like this, 
so my strategy of deriving
the index numbers of every item, as awkward as it appears, may actually be the
best approach. 

 

In response to the second: a pickle, a dictionary, a
database, and a tuple with a sublist were all proposed.    The choice seems 
somewhat arbitrary, but on
the bright side, I suppose that also confirms that I have a lot of flexibility
in what I choose.  



Specific responses:


Steven,

I apologize for using 'reply,' I've never used a mailing
list before and didn't understand what would happen.  Is there some online 
forum where I could post
a message directly rather than mailing it in? 
I see that other people are somehow responding to my message from the
more real-time updates I can get on activestate, but I don't know how they are
doing it since I haven't received the mailing yet that would include my message
and its responses.  

If my list had a million books in it and 10 million page
numbers, would the approach I've outlined in my initial post be the best for
sorting them?  Like David and Eric you've
given me some good input on a data structure to use.  If I understand you 
right, you'd advocate
using a tuple of the books, bookmarks, where the bookmarks themselves are
sublists.  


David, Yes, I agree it would 
be much better to store the data in a different manner.  The problem is that 
I'm not the creator of
the data.  Maybe you realize that and are
just suggesting the database structure rather than a dictionary or a pickle,
once I get my sorting accomplished?  If
the book example is confusing how about this. 
Say you discovered a bunch of data in a secret code document.  You know the 
sequence of the data relates the
elements to each other.  You also know
there are just two elements and that the sequence is a straightforward function
of say, integers to letters.  So the data
you've discovered looks like:


A 2 3 B 4 7 5 9 1 C 3 2 1 0 0 4 D 3 3 32 44 ...


Once I've sorted the data, I am curious how to best store it
(and why), and your answer does pertain to that-- use sql-- but I am also
curious if there's a less arcane approach than the one I'm using to try to do
the initial sorting.  Any thoughts, given
that I can't fix the way the data arrives? 
Thanks for the database idea regardless.


Eric, I appreciate your input though I'm hard-pressed to
find its applicability.  It may be useful
as a way to store my data for this or any number of other programs though, and
that was a helpful article about the pickling process.  I don't know if pickle 
has any built-in
methods for relating data to other data. 
I'd imagine that if I were designing the data input process, rather than
just taking data that exists and trying to process it, I'd probably go with a
database for a situation like this.  Then
I'd have a more explicit system for referring each value to other values
through records, rather than having to infer them as I'm doing.  Regardless, 
I'm often in the same position of
trying to be helpful without knowing how, and I sincerely do appreciate the
attempt.  It creates a general atmosphere
of friendliness, which is so much better than being told I'm an idiot :)!


Lingering Questions: 

Anyone have a rationale for choosing
one of the data structures proposed? 
Anyone have a better way to do the sorting than the process I outlined
in my first post (a. identify the elements. b. make a list of one of  the 
element groups. c. get the index numbers
of that group in the broader list.  d.
list the other elements as indexes falling between the first group's indexes.  
e. reorganize the data into a more logical
form)


Thanks again to everyone who responded!


Soren


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


[Tutor] Response to Alan re: list of lists response

2010-07-13 Thread Siren Saren
Alan,

Your message appeared on the forum right as I posted my response.  Brief 
unrelated thanks: your website has been a great help to me as I've been 
learning python.  I'm especially grateful to you for making it so easy to 
download in various formats, since my health problems make it hard for me to 
read at my desk and it was lovely to be able to put everything on my 
ebook-reader and work on it on the couch.  If anyone hasn't checked out Alan's 
website, which is more like a book, I highly recommend it.

The idea of making this into an object appeals to me very much, because I've 
been trying to get my head around creating objects as well as just using them.  
Thank you, too, for the example code on how to think about creating such an 
object.  

I'm positive now that my initial message was misleading, given that you also 
responded as though I could affect the way my data arrived.  Oddly,  I've 
already tried to develop a couple of 'programs' dealing with data in this 
form-- lists where the sequence means something but isn't merely alternation.  
I assumed this must be a common problem but maybe programmers mostly deal with 
data that was made for their purposes nowadays.  It's interesting how 
self-referential the world becomes.

Thanks again for taking the time to both build your website and share your 
thoughts directly with me.  Means a lot



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


[Tutor] random graph

2010-07-13 Thread Robert Johansson
Dear all,

 

I'm trying to check the size of a component in a random graph with this code
(by a component I mean a maximal connected sub graph):

 

http://pastebin.com/SzC77HdU

 

I'm not 100 % sure that the code is working as it should but my question is
if there is a better way to design the whole thing. 

 

Basically I start with a empty graph (just a set of nodes represented as the
numbers between 0 and 10 ** 6) and generate random edges as pairs of
integers between 0 and 10 ** 6. Also I keep a dictionary (comps) matching
nodes to component numbers. If one of the nodes of the new edge doesn't
touch an existing component, I just add that node to the dictionary and give
it the same component number as the other node. If no node touches a
component the a new component number is generated and the new nodes are
added to the dict with that number. The problem is when an edge going
between two distinct components are encountered, say that edge (n, m) is
generated going between component i and j. Now I need to change all values
for keys in one of the components to the values of the other component so
that  they merge into a single component. The way I tried to do this is to
have lists of length one as values in the dict and by that (hopefully)
manage to update all values for a whole component just by changing a single
list item (I think of them as pointers to the same list).  

 

Will this work? Is there a better way to update the values of a component
(fast)?

 

/Robert

 

 

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


Re: [Tutor] Path?

2010-07-13 Thread Jim Byrnes

Steven D'Aprano wrote:

My apologizes to Steven and the list, when I replied originally I messed 
up and sent it to him privately which was not my intention.



> On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:
>> I am running Ubuntu.  I downloaded the source code examples for a
>> book I purchased.  Some of the examples load image files located in
>> the same directory as the program.  If I go to the current directory
>> in the terminal the program can use the image files.  However, if I
>> use a launcher or the filemanager it pops up an error dialog saying
>> the file does not exist even though it is in the same directory.
>>
>> The program simply uses the files name.  Is there a way without
>> editing the source and inserting the full path to run the program
>> from a launcher or the filemanager and allow it to see files in the
>> current directory?
>
> What file manager are you using? Nautilus? Konqueror? Something else?

Nautilus. I have it configured to run files with the extension .py when 
they are double clicked.


> What do you mean, "use a launcher"? Use a launcher to do what? What sort
> of launcher?

It runs programs and sits on the panel at the top of my Ubuntu desktop. 
 The command it uses is usr/bin/python2.6.  These are wxPython examples 
I am working with.


> What pops up an error dialog? The launcher?

I am assuming Python. The title bar of the dialog says Python2 Error, 
the message is   Can't load image from file 'wxPython.jpg': file does 
not exist.


> Which file does it claim doesn't exist? Python? The Python script? The
> image file? What is the exact error message it gives?

See above.  The line that triggers the error is:  image = 
wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)


> There's probably a way to tell the launcher which working directory to
> use, but of course that depends on the answers to the above questions.
>

If I use the terminal to start the program it has no problem using the 
file.  There are multiple files in multiple directories so I was looking 
for a way to just double click them and have them run.  If it turns out 
that I must make changes to or for each of the files it will be easier 
to just keep using the terminal.  I've only been using Ubuntu for a few 
months so I was surprised that the program could not see a file that is 
in the same directory.


Regards,  Jim

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


Re: [Tutor] Path?

2010-07-13 Thread Adam Bark
On 13 July 2010 14:43, Jim Byrnes  wrote:

> Steven D'Aprano wrote:
>
> My apologizes to Steven and the list, when I replied originally I messed up
> and sent it to him privately which was not my intention.
>
>
>
> > On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:
> >> I am running Ubuntu.  I downloaded the source code examples for a
> >> book I purchased.  Some of the examples load image files located in
> >> the same directory as the program.  If I go to the current directory
> >> in the terminal the program can use the image files.  However, if I
> >> use a launcher or the filemanager it pops up an error dialog saying
> >> the file does not exist even though it is in the same directory.
> >>
> >> The program simply uses the files name.  Is there a way without
> >> editing the source and inserting the full path to run the program
> >> from a launcher or the filemanager and allow it to see files in the
> >> current directory?
> >
> > What file manager are you using? Nautilus? Konqueror? Something else?
>
> Nautilus. I have it configured to run files with the extension .py when
> they are double clicked.
>
>
> > What do you mean, "use a launcher"? Use a launcher to do what? What sort
> > of launcher?
>
> It runs programs and sits on the panel at the top of my Ubuntu desktop.
>  The command it uses is usr/bin/python2.6.  These are wxPython examples I am
> working with.
>
>
> > What pops up an error dialog? The launcher?
>
> I am assuming Python. The title bar of the dialog says Python2 Error, the
> message is   Can't load image from file 'wxPython.jpg': file does not exist.
>
>
> > Which file does it claim doesn't exist? Python? The Python script? The
> > image file? What is the exact error message it gives?
>
> See above.  The line that triggers the error is:  image =
> wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)
>
>
> > There's probably a way to tell the launcher which working directory to
> > use, but of course that depends on the answers to the above questions.
> >
>
> If I use the terminal to start the program it has no problem using the
> file.  There are multiple files in multiple directories so I was looking for
> a way to just double click them and have them run.  If it turns out that I
> must make changes to or for each of the files it will be easier to just keep
> using the terminal.  I've only been using Ubuntu for a few months so I was
> surprised that the program could not see a file that is in the same
> directory.
>
> Regards,  Jim


The problem is ubuntu doesn't run the script from the directory it's in so
it's looking for wxPython.jpg somewhere else.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Response to responses about list of lists: a meta exercise in mailinglist recursion

2010-07-13 Thread Stefan Behnel

Siren Saren, 13.07.2010 14:40:

I'm not sure if there's a way to submit responses 'live' or
whether it's better to respond to subthreads at once or together, so I'll err
on the side of discretion and just send one response.


It's not generally a problem to send one response like this regarding many 
posts, especially if you use it to summarise the previous discussion. But 
if you do, please take care to actually reply to one of the posts to make 
sure the mail clients and mailing list archives sort the message into the 
right thread. If you don't, you start a new thread (as you did here), which 
will be harder to find in archives.


Stefan

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


Re: [Tutor] LOCATION ISSUES

2010-07-13 Thread Emile van Sebille

On 7/12/2010 11:52 PM Dipo Elegbede said...


Which is what it will do when python is started from that directory.

I actually found the copies that were made by the code in the same
directory but found out that they all had a .thumbnail ext which would not
open and it is understandable.

I have however chaged that part of the code to carry .jpg hoping to let it
make thumbnails with jpg extensions.



How are you starting python?



I am new to python.


:)  What I meant to ask was what are you typing in to actually start 
python and execute your code?  You need to open a command window, 
navigate to the directory where the images are stored, and start python 
from there so that glob will find the files.


HTH,

Emile

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


Re: [Tutor] Help

2010-07-13 Thread bob gailer

You have gotten good advice from others.

My request is that you provide a meaningful subject when you post a 
question. We track by subject. "Help" is not the best subject.


Better would be "How to find prime numbers"

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Response to responses about list of lists: a meta exercise in mailinglist recursion

2010-07-13 Thread David Hutto
On Tue, Jul 13, 2010 at 8:40 AM, Siren Saren  wrote:

> I'm not sure if there's a way to submit responses 'live' or whether it's
> better to respond to subthreads at once or together, so I'll err on the side
> of discretion and just send one response.  Thanks to each of you who tried
> to help me.  I've responded individually below.
>
>
>  To summarize the discussion so far:
>
>
> I wondered if there was a decent way to sort a list that contained two
> lists, where each could be distinguished based on the list's sequence and
> the elements' data characteristics.  As a subsidiary question, I wondered
> if there was a data structure I should aspire to put the data into once I
> had it sorted.
>
>
> In response to the first question: the consensus seems to be that there is
> no good way to sort a non-alternating one-to-many list like this, so my
> strategy of deriving the index numbers of every item, as awkward as it
> appears, may actually be the best approach.
>
>
>  In response to the second: a pickle, a dictionary, a database, and a
> tuple with a sublist were all proposed.The choice seems somewhat
> arbitrary, but on the bright side, I suppose that also confirms that I have
> a lot of flexibility in what I choose.
>
>
> Specific responses:
>
>
> Steven,
>
> I apologize for using 'reply,' I've never used a mailing list before and
> didn't understand what would happen.  Is there some online forum where I
> could post a message directly rather than mailing it in?  I see that other
> people are somehow responding to my message from the more real-time updates
> I can get on activestate, but I don't know how they are doing it since I
> haven't received the mailing yet that would include my message and its
> responses.
>
> If my list had a million books in it and 10 million page numbers, would the
> approach I've outlined in my initial post be the best for sorting them?  Like
> David and Eric you've given me some good input on a data structure to use.
> If I understand you right, you'd advocate using a tuple of the books,
> bookmarks, where the bookmarks themselves are sublists.
>
>
> David, Yes, I agree it would  be much better to store the data in a
> different manner.  The problem is that I'm not the creator of the data.
>

This, again is a newbie statement but maybe importing re or regular
expressions to parse the known files would be helpful.

The way I'm thinking is that you put your books in a directory. Now, that
directory could contain directories of books with the individual text pages
within those book's directories, or something like a pdf.


Within these documents or directories, you search with an app for those
specific files. Now you can either list within the app those books and pages
and then search the directories, or you could search the directories first
and list the books, then specify the page you want to go to.

My DB idea would work if you placed in an ID, a page number, then a location
to the text file , or stored the text in the sqlite DB globfield .

> Maybe you realize that and are just suggesting the database structure
> rather than a dictionary or a pickle, once I get my sorting accomplished?
> If the book example is confusing how about this.  Say you discovered a
> bunch of data in a secret code document.  You know the sequence of the
> data relates the elements to each other.  You also know there are just two
> elements and that the sequence is a straightforward function of say,
> integers to letters.  So the data you've discovered looks like:
>
>
> A 2 3 B 4 7 5 9 1 C 3 2 1 0 0 4 D 3 3 32 44 ...
>
>
> Once I've sorted the data, I am curious how to best store it (and why), and
> your answer does pertain to that-- use sql--
>

Not just sql, but maybe, and dicts/lists are not my specialty yet, but
utilize it in the process. The main objective of utilizing the DB, in MHO,
is that it forces you to state the information you want to use, so this
refines your code, by defining the fields you must use to state and store
the data. So you have a book, and a page, and a author, and an id to match
these with.

Now you could use an app to search the 'book' directory, and then  'for each
in' print the book containing folder's name., then open() the page and could
go further to bring up the exact line/paragraph of the individual page.

> but I am also curious if there's a less arcane approach than the one I'm
> using to try to do the initial sorting.  Any thoughts, given that I can't
> fix the way the data arrives?  Thanks for the database idea regardless.
>
>
>
This again would be regular expressions, as far as I'm thinking, import re,
help(re) or dir(re), or pydoc re, or something like that. You parse the
book's file or directory, and look for the tags to read out the book's name,
author or page, and then you can just select the book, type in the page
number, or select from a predetermined list of pages that have explanations
as to why you should visit the page, or read the text.


> Eric

Re: [Tutor] Response to responses about list of lists: a meta exercise in mailinglist recursion

2010-07-13 Thread David Hutto
On Tue, Jul 13, 2010 at 1:20 PM, David Hutto  wrote:

>
>
> On Tue, Jul 13, 2010 at 8:40 AM, Siren Saren  wrote:
>
>>  I'm not sure if there's a way to submit responses 'live' or whether it's
>> better to respond to subthreads at once or together, so I'll err on the side
>> of discretion and just send one response.  Thanks to each of you who
>> tried to help me.  I've responded individually below.
>>
>>
>>  To summarize the discussion so far:
>>
>>
>> I wondered if there was a decent way to sort a list that contained two
>> lists, where each could be distinguished based on the list's sequence and
>> the elements' data characteristics.  As a subsidiary question, I wondered
>> if there was a data structure I should aspire to put the data into once I
>> had it sorted.
>>
>>
>> In response to the first question: the consensus seems to be that there is
>> no good way to sort a non-alternating one-to-many list like this, so my
>> strategy of deriving the index numbers of every item, as awkward as it
>> appears, may actually be the best approach.
>>
>>
>>  In response to the second: a pickle, a dictionary, a database, and a
>> tuple with a sublist were all proposed.The choice seems somewhat
>> arbitrary, but on the bright side, I suppose that also confirms that I have
>> a lot of flexibility in what I choose.
>>
>>
>> Specific responses:
>>
>>
>> Steven,
>>
>> I apologize for using 'reply,' I've never used a mailing list before and
>> didn't understand what would happen.  Is there some online forum where I
>> could post a message directly rather than mailing it in?  I see that
>> other people are somehow responding to my message from the more real-time
>> updates I can get on activestate, but I don't know how they are doing it
>> since I haven't received the mailing yet that would include my message and
>> its responses.
>>
>> If my list had a million books in it and 10 million page numbers, would
>> the approach I've outlined in my initial post be the best for sorting them?
>> Like David and Eric you've given me some good input on a data structure to
>> use.  If I understand you right, you'd advocate using a tuple of the
>> books, bookmarks, where the bookmarks themselves are sublists.
>>
>>
>> David, Yes, I agree it would  be much better to store the data in a
>> different manner.  The problem is that I'm not the creator of the data.
>>
>
> This, again is a newbie statement but maybe importing re or regular
> expressions to parse the known files would be helpful.
>
> The way I'm thinking is that you put your books in a directory. Now, that
> directory could contain directories of books with the individual text pages
> within those book's directories, or something like a pdf.
>
>
> Within these documents or directories, you search with an app for those
> specific files. Now you can either list within the app those books and pages
> and then search the directories, or you could search the directories first
> and list the books, then specify the page you want to go to.
>
> My DB idea would work if you placed in an ID, a page number, then a
> location to the text file , or stored the text in the sqlite DB globfield .
>
>>  Maybe you realize that and are just suggesting the database structure
>> rather than a dictionary or a pickle, once I get my sorting accomplished?
>> If the book example is confusing how about this.  Say you discovered a
>> bunch of data in a secret code document.  You know the sequence of the
>> data relates the elements to each other.  You also know there are just
>> two elements and that the sequence is a straightforward function of say,
>> integers to letters.  So the data you've discovered looks like:
>>
>>
>> A 2 3 B 4 7 5 9 1 C 3 2 1 0 0 4 D 3 3 32 44 ...
>>
>>
>> Once I've sorted the data, I am curious how to best store it (and why),
>> and your answer does pertain to that-- use sql--
>>
>
> Not just sql, but maybe, and dicts/lists are not my specialty yet, but
> utilize it in the process. The main objective of utilizing the DB, in MHO,
> is that it forces you to state the information you want to use, so this
> refines your code, by defining the fields you must use to state and store
> the data. So you have a book, and a page, and a author, and an id to match
> these with.
>
> Now you could use an app to search the 'book' directory, and then  'for
> each in' print the book containing folder's name., then open() the page and
> could go further to bring up the exact line/paragraph of the individual
> page.
>
>> but I am also curious if there's a less arcane approach than the one I'm
>> using to try to do the initial sorting.  Any thoughts, given that I can't
>> fix the way the data arrives?  Thanks for the database idea regardless.
>>
>>
>>
> This again would be regular expressions, as far as I'm thinking, import re,
> help(re) or dir(re), or pydoc re, or something like that. You parse the
> book's file or directory, and look for the tags to read out the book's name,
> author or page, a

Re: [Tutor] Response to Alan re: list of lists response

2010-07-13 Thread Alan Gauld


"Siren Saren"  wrote

unrelated thanks: your website has been a great help


Thanks for the kind words :-)


The idea of making this into an object appeals to me
very much, because I've been trying to get my head around
creating objects as well as just using them.


It has some advantages since it is possible to write functions
that are used when sorting so you can sort complex data sets
relatively easily at the macro scale of using the objects. The
comparison functions useed to sort may of course be arbitrarily
complex - but at least the higher level application code is kept
simple..


I'm positive now that my initial message was misleading,
given that you also responded as though I could affect
the way my data arrived.


You gave no clue whatsoever how the data arrived.
Is it in a file? a data stream? a database?
The first thing to do in any data processing application is to read
the data into the data format that you want it to be in to do the
processing.


Oddly, I've already tried to develop a couple of 'programs' dealing
with data in this form-- lists where the sequence means something
but isn't merely alternation.


I'm still not sure I understand what you mean by that. Your book/pages
and crypto examples seemed straighforward but you didn't give any
examples of what the sorted v unsorted data would look like.


I assumed this must be a common problem but maybe
programmers mostly deal with data that was made for their
purposes nowadays.


Not at all but the first thing you do in any data processing problem
is take the input data and store it how you want it, not how it 
arrives!

But how you want it will depend on what you are trying to do with it!
That's why the many responses vary - it depends on how you want
to manipulate it.

HTH,


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


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


Re: [Tutor] Path?

2010-07-13 Thread Jim Byrnes

Adam Bark wrote:

On 13 July 2010 14:43, Jim Byrnes  wrote:


Steven D'Aprano wrote:

My apologizes to Steven and the list, when I replied originally I messed up
and sent it to him privately which was not my intention.




On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:

I am running Ubuntu.  I downloaded the source code examples for a
book I purchased.  Some of the examples load image files located in
the same directory as the program.  If I go to the current directory
in the terminal the program can use the image files.  However, if I
use a launcher or the filemanager it pops up an error dialog saying
the file does not exist even though it is in the same directory.

The program simply uses the files name.  Is there a way without
editing the source and inserting the full path to run the program
from a launcher or the filemanager and allow it to see files in the
current directory?


What file manager are you using? Nautilus? Konqueror? Something else?


Nautilus. I have it configured to run files with the extension .py when
they are double clicked.



What do you mean, "use a launcher"? Use a launcher to do what? What sort
of launcher?


It runs programs and sits on the panel at the top of my Ubuntu desktop.
  The command it uses is usr/bin/python2.6.  These are wxPython examples I am
working with.



What pops up an error dialog? The launcher?


I am assuming Python. The title bar of the dialog says Python2 Error, the
message is   Can't load image from file 'wxPython.jpg': file does not exist.



Which file does it claim doesn't exist? Python? The Python script? The
image file? What is the exact error message it gives?


See above.  The line that triggers the error is:  image =
wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)



There's probably a way to tell the launcher which working directory to
use, but of course that depends on the answers to the above questions.



If I use the terminal to start the program it has no problem using the
file.  There are multiple files in multiple directories so I was looking for
a way to just double click them and have them run.  If it turns out that I
must make changes to or for each of the files it will be easier to just keep
using the terminal.  I've only been using Ubuntu for a few months so I was
surprised that the program could not see a file that is in the same
directory.

Regards,  Jim



The problem is ubuntu doesn't run the script from the directory it's in so
it's looking for wxPython.jpg somewhere else.



OK, I mistakenly thought that double-clicking on file in Nautilus would 
take care of the path info.


In my reply above I also mentioned that I tried by dropping it on a 
Launcher on the top panel and that the command the launcher uses is 
usr/bin/python2.6.  Is there a way that the command can be changed so 
that it will look in the same directory the python script is in for any 
file it needs?


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


Re: [Tutor] Path?

2010-07-13 Thread Adam Bark
On 13 July 2010 23:27, Jim Byrnes  wrote:

> Adam Bark wrote:
>
>> On 13 July 2010 14:43, Jim Byrnes  wrote:
>>
>>  Steven D'Aprano wrote:
>>>
>>> My apologizes to Steven and the list, when I replied originally I messed
>>> up
>>> and sent it to him privately which was not my intention.
>>>
>>>
>>>
>>>  On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:

> I am running Ubuntu.  I downloaded the source code examples for a
> book I purchased.  Some of the examples load image files located in
> the same directory as the program.  If I go to the current directory
> in the terminal the program can use the image files.  However, if I
> use a launcher or the filemanager it pops up an error dialog saying
> the file does not exist even though it is in the same directory.
>
> The program simply uses the files name.  Is there a way without
> editing the source and inserting the full path to run the program
> from a launcher or the filemanager and allow it to see files in the
> current directory?
>

 What file manager are you using? Nautilus? Konqueror? Something else?

>>>
>>> Nautilus. I have it configured to run files with the extension .py when
>>> they are double clicked.
>>>
>>>
>>>  What do you mean, "use a launcher"? Use a launcher to do what? What sort
 of launcher?

>>>
>>> It runs programs and sits on the panel at the top of my Ubuntu desktop.
>>>  The command it uses is usr/bin/python2.6.  These are wxPython examples I
>>> am
>>> working with.
>>>
>>>
>>>  What pops up an error dialog? The launcher?

>>>
>>> I am assuming Python. The title bar of the dialog says Python2 Error, the
>>> message is   Can't load image from file 'wxPython.jpg': file does not
>>> exist.
>>>
>>>
>>>  Which file does it claim doesn't exist? Python? The Python script? The
 image file? What is the exact error message it gives?

>>>
>>> See above.  The line that triggers the error is:  image =
>>> wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)
>>>
>>>
>>>  There's probably a way to tell the launcher which working directory to
 use, but of course that depends on the answers to the above questions.


>>> If I use the terminal to start the program it has no problem using the
>>> file.  There are multiple files in multiple directories so I was looking
>>> for
>>> a way to just double click them and have them run.  If it turns out that
>>> I
>>> must make changes to or for each of the files it will be easier to just
>>> keep
>>> using the terminal.  I've only been using Ubuntu for a few months so I
>>> was
>>> surprised that the program could not see a file that is in the same
>>> directory.
>>>
>>> Regards,  Jim
>>>
>>
>>
>> The problem is ubuntu doesn't run the script from the directory it's in so
>> it's looking for wxPython.jpg somewhere else.
>>
>>
> OK, I mistakenly thought that double-clicking on file in Nautilus would
> take care of the path info.
>
> In my reply above I also mentioned that I tried by dropping it on a
> Launcher on the top panel and that the command the launcher uses is
> usr/bin/python2.6.  Is there a way that the command can be changed so that
> it will look in the same directory the python script is in for any file it
> needs?
>
> Thanks,  Jim


Not sure if you got my previous email but you could try writing the bash
script I posted (with the $1 line to get the path) and setting that as your
launcher, I think it should work.

Let me know if you didn't get it or it doesn't work.

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


Re: [Tutor] Response to responses about list of lists: a meta exercise in mailinglist recursion

2010-07-13 Thread Steven D'Aprano
On Tue, 13 Jul 2010 10:40:44 pm Siren Saren wrote:
> I'm not sure if there's a way to submit responses 'live' or
> whether it's better to respond to subthreads at once or together, so
> I'll err on the side of discretion and just send one response. 

Generally it's better, or at least more common, to respond to each 
response individually. But that's generally because people on mailing 
lists receive individual pieces of mail instead of a single giant 
digest containing the entire day's email traffic.


> In response to the first question: the consensus seems to be
> that there is no good way to sort a non-alternating one-to-many list
> like this, so my strategy of deriving the index numbers of every
> item, as awkward as it appears, may actually be the best approach.

No, a better approach is to split the list into separate lists:

mixedlist = [
 'Crime and punishment', 10, 40, 30, 
 "Brother's Karamazov", 22, 55, 9000, 
 "Father's and Sons", 100,
 'Anna Karenina', 1, 2, 4, 7, 9,
]

# untested
current_book = None
current_pages = []
result = []
for item in mixedlist:
# Is it a title, or an integer page?
if isinstance(item, str):
# It's a title.
if current_book is not None:
result.append( (current_book, current_pages) )
current_book = item
current_pages = []
else:
# It's a page number.
current_pages.append(item)

This will split the mixed list of titles, page numbers into a 
consolidated list of (title, list-of-page-numbers) like this:

booklist = [
 ("Crime and punishment", [10, 40, 30]),
 ("Brother's Karamazov", [22, 55, 9000]),
 ("Father's and Sons", [100]),
 ("Anna Karenina", [1, 2, 4, 7, 9]),
]

It's easy to adapt it to use a dictionary instead of a list. Change 
result to an empty dict {} instead of an empty list [], and change the 
line:

result.append( (current_book, current_pages) )

into:

result[current_book] = current_pages



One other thing... it's possible that your data is provided to you in 
text form, so that you have a single string like:

"Crime and punishment, page 10, page 40, page 30, ..."

instead of the more useful list of titles and integers. Some people have 
suggested using regular expressions to process the page numbers. That's 
fine, but it's rather overkill, like using a bulldozer to move a 
shovelful of dirt. Here's an (untested) filter to convert the one long 
string into a list of titles and integer pages:

result = []
for item in long_string.split(','):
item = item.strip()  # get rid of leading and trailing spaces
if item.startswith('page '):
item = int(item[5:])
result.append(item)

This assumes the data is well-formed, there are no typos such as "pgae 
15" in the data, and most importantly, no commas in the book titles.

This can be written as a two-liner, at the cost of some readability:

items = [item.strip() for item in long_string.split(',')]
result = [int(s[5:]) if s.startswith('page ') else s for s in items]

Making it into a one-liner is left as an exercise for the masochistic.


This demonstrates the basic principle of data processing of this kind. 
You start with a bunch of data in one form, and you transform it into 
another, slightly different and more useful form, using a series on 
individual filters or transformation functions:

Start with one long string.
Divide it into a list of substrings.
Transform it into a list of strings and integers.
Collate the integers with the string they belong to.
Do something useful with the pairs of (string, list-of-integers)


[...]
> I apologize for using 'reply,' I've never used a mailing
> list before and didn't understand what would happen.

Using rely is fine, but trim your response! Think of it like this. 
Suppose you received dozens of letters each day, from many different 
people, but the post office consolidated it all into a single envelope 
and delivered it once a day (a "digest"). If you wanted to reply to 
something from Fred, you wouldn't photocopy the entire day's collection 
of mail, all two hundred letters, and stick it at the bottom of your 
reply, would you? Well, that's what your mail program does, by default. 
It only takes a second to delete that excess baggage from your reply 
before hitting send.



> Is there some 
> online forum where I could post a message directly rather than
> mailing it in?

I don't think there's an online forum, because this is an email mailing 
list, not a web forum.

If you're starting a new discussion, or raising a new question, make a 
fresh, blank email, put a descriptive title in the subject line, and 
put tutor@python.org as the To address. 

If you're replying to an existing message, using reply is fine, but just 
trim the quoted text. You have a delete key -- learn how to use it :)


> I see that other people are somehow responding to my message from the
> more real-time updates I can get on activestate, but I don't know how
> they are doing it since I haven't received the maili

Re: [Tutor] Path?

2010-07-13 Thread Jim Byrnes

Adam Bark wrote:




If I use the terminal to start the program it has no problem using the
file.  There are multiple files in multiple directories so I was looking
for
a way to just double click them and have them run.  If it turns out that
I
must make changes to or for each of the files it will be easier to just
keep
using the terminal.  I've only been using Ubuntu for a few months so I
was
surprised that the program could not see a file that is in the same
directory.

Regards,  Jim




The problem is ubuntu doesn't run the script from the directory it's in so
it's looking for wxPython.jpg somewhere else.



OK, I mistakenly thought that double-clicking on file in Nautilus would
take care of the path info.

In my reply above I also mentioned that I tried by dropping it on a
Launcher on the top panel and that the command the launcher uses is
usr/bin/python2.6.  Is there a way that the command can be changed so that
it will look in the same directory the python script is in for any file it
needs?

Thanks,  Jim



Not sure if you got my previous email but you could try writing the bash
script I posted (with the $1 line to get the path) and setting that as your
launcher, I think it should work.

Let me know if you didn't get it or it doesn't work.

HTH,
Adam.



I got it, got sidetracked and then forgot to look at it again.  Thanks 
for reminding me.  Your idea works, but with one little downside.  The 
directories I am working with are chapters in a book.  So as I move from 
chapter to chapter I will need to change the bash script, but this seems 
to be less typing than using the terminal.


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


Re: [Tutor] Help

2010-07-13 Thread bob gailer

On 7/13/2010 5:50 AM, Dipo Elegbede wrote:

I was trying to write a code that prints prime numbers between 1 and 20.


Other suggestions
 - you need only test divisors up to the square root of the candidate.
- you can easily eliminate all even numbers and numbers divisible by 3.

for i in range(0,7,3):
  isPrime(i-1)
  isPrime(i+1)

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Help

2010-07-13 Thread Shashwat Anand
On Tue, Jul 13, 2010 at 3:20 PM, Dipo Elegbede wrote:

> I was trying to write a code that prints prime numbers between 1 and 20.
>
> I have by myself seen that something is wrong with my code and also my
> brain.
>
> Could anyone be kind enough to tell me what to do
>
> Where I am confused is how to test for other numbers without one and the
> number itself. It turns out that all numbers pass the condition I set so
> that would presuppose that all numbers are prime which is not.
>
> How exactly can I get it to run checks with other numbers such that it
> doesn't include the number itself and 1.
>
> The code is as follows:
>
> for i in range(1,20):
>
> if float(i) % 1 == 0 and float(i) % i == 0:
> print i, 'is a prime number'
>

Do you realize that all the numbers are divisible by 1. Hence float(i) % 1
_will be always zero_.
Now again, Do you realize that every number is divisible by itself. So
float(i) % i will also always be zero.
Also are you using float when dealing with integers.
Steps:
* You should probably check whether a number is prime.
* Then you should add extra loop to check whether in a given range of
numbers how many are prime.
* Now you optimize the code for lesse number of calculations, say for n
check for divisibility only until sqrt(n)
* Now you read wiki, read about sieve and apply sieve of erastothenes, to
make the code fast.
* Again memoize your code, so that it becomes more fast.
With all this done, you have a pretty handy code with yourself, coded by
you.
* Now solve this problem - https://www.spoj.pl/problems/PRIME1/ , which
can't be solved unless your code is highly optimized.
* If you have more curiosity, look for sieve of atkin.

Finish these and you are well off with primes :)

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


[Tutor] Handling 'None' (null) values when processing sqlite cursor results

2010-07-13 Thread Monte Milanuk

Hello all,

I'm struggling a bit trying to find the right way to deal with null 
values in my sqlite database when querying it and processing the results 
in python.


If my cursor.fetchall() results return the following:

(104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin Av.', 
u'Liberal', u'VT', u'24742', u'1-135-197-1139', 
u'vehicula.pellentes...@idmollis.edu', u'2010-07-13 22:52:50', 
u'2010-07-13 22:52:50')


At first I was having fits as str.join() was giving me a 'NoneType 
error'.  I found one way around that, by processing the results so the 
'None' values got omitted from the list by the time they got to str.join().


I thought that was the end of that, until I tried working with the 
returned records in another fashion and found that having the 'None' 
values omitted really messed with the list order which I was depending 
on i.e. list[5] could be different fields depending on how many 'None' 
values had been omitted.  And if I didn't omit them, when I printed out 
the user name in the format 'first''middle''last' from the above record, 
I got 'Sylvester''None''Evans' rather than just 'Sylvester''Evans' (i.e. 
with no middle initial).


So... I guess my question is, is there a good/proper way to handle the 
'None' values as returned by sqlite from a table that may have some null 
values in individual records?  Basically I want not have the None/Null 
values show up but to keep them as place holders to make sure i get the 
values in the right spots...


TIA,

Monte

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