[Tutor] Introducing myself.

2013-05-13 Thread Natal Ngétal
Hi,

I'm new to the mailing list, I think it is interesting to present. I'm a
developer, I use Python and Perl yes it is also a great language. I use
Python to work, but I also love the language for its simplicity, its
community, and its clean syntax. Lacks a more advanced pypi like CPAN,
that parses the pydoc to show documentation, there readthedocs but it's
different, it is also interesting that pypi launches module tests, there
travis.ci but it is yet another platform, something centralized would
be more practical.

Otherwise, I am registered on the ml to help if I can, and I'd also like
to know the kind of question that can be asked, or stops the beginner
level, because I think remain an eternal beginner. What are the other ml
can advise you on the language in general ? Otherwise nothing to do, but
is it that there would be people who would need help for develop on open
source projects in Python, whether it interests me.

My best regards

-- 
\0/ Hobbestigrou
site web: erakis.eu
L'Europe est trop grande pour être unie. Mais elle est trop petite pour
être
divisée. Son double destin est là
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] creating a corpus from a csv file

2013-05-13 Thread Treder, Robert

Message: 1
Date: Fri, 03 May 2013 23:05:32 +0100
From: Alan Gauld 
To: tutor@python.org
Subject: Re: [Tutor] creating a corpus from a csv file
Message-ID: 
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

On 03/05/13 21:48, Treder, Robert wrote:

> I'm very new to python and am trying to figure out how to
 > make a corpus from a text file.

Hi, I for one have no idea what a corpus is or looks like so you will need to 
help us out a little before we can help you.

> I have a csv file (actually pipe '|' delimited) where each row 
> corresponds to a different text document.

> Each row contains a communication note.
 > Other columns correspond to categories of types of communications.

> I am able to read the csv file and print the notes column as follows:
>
> import csv
> with open('notes.txt', 'rb') as infile:
>  reader = csv.reader(infile, delimiter = '|')
>  i = 0
>  for row in reader:
>  if i <= 25: print row[8]
>  i = i+1

You don't need to manually manage 'i'.

you could do this instead:

with open('notes.txt', 'rb') as infile:
  reader = csv.reader(infile, delimiter = '|')
  for count, row in enumerate(reader):
  if count <= 25: print row[8]  # I assume indented?
  else: break   # save time if its a big file

> I would like to convert this to a categorized corpus with
 > some of the other columns corresponding to the categories.

You might be able to use a dictionary but for now I'm still not clear what you 
mean. Can you show us some sample input and output data?

 > documentation on how to use csv.reader with PlaintextCorpusReader

never heard of the latter - is it an external module?

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




Message: 7
Date: Sat, 04 May 2013 10:29:57 +0200
From: Peter Otten <__pete...@web.de>
To: tutor@python.org
Subject: Re: [Tutor] creating a corpus from a csv file
Message-ID: 
Content-Type: text/plain; charset="ISO-8859-1"

Treder, Robert wrote:

> I'm very new to python and am trying to figure out how to make a corpus
> from a text file. I have a csv file (actually pipe '|' delimited) where
> each row corresponds to a different text document. Each row contains a
> communication note. Other columns correspond to categories of types of
> communications. I am able to read the csv file and print the notes column
> as follows:
>  
> import csv
> with open('notes.txt', 'rb') as infile:
> reader = csv.reader(infile, delimiter = '|')
> i = 0
> for row in reader:
> if i <= 25: print row[8]
> i = i+1
> 
> I would like to convert this to a categorized corpus with some of the
> other columns corresponding to the categories. All of the columns are text
> (i.e., strings). I have looked for documentation on how to use csv.reader
> with PlaintextCorpusReader but have been unsuccessful in finding a 
> example similar to what I want to do. Can someone please help?

This mailing list is for learning Python. For problems with a specific 
library you should use the general python list 



or a forum dedicated to that library



If you ask on a general forum you should give some context -- the name of 
the library would be the bare minimum.

The following comes with no warranties as I'm not an nltk user:

import csv
from nltk.corpus.reader.plaintext import CategorizedPlaintextCorpusReader
from itertools import islice, chain

LIMIT_SIZE = 25 # set to None if not debugging

def pairs(filename):
"""Generate (filename, list_of_categories) pairs from a csv file
"""
with open(filename, "rb") as infile:
rows = islice(csv.reader(infile, delimiter="|"), LIMIT_SIZE)
for row in rows:
# assume that columns 10 and above contain categories
yield row[8], row[9:]

if __name__ == "__main__":
import random
FILENAME = "notes.txt"

# assume that every filename occurs only once in the file
file_to_categories = dict(pairs(FILENAME))

files = list(file_to_categories)

all_categories = 
set(chain.from_iterable(file_to_categories.itervalues()))

reader = CategorizedPlaintextCorpusReader(".", files, 
cat_map=file_to_categories)

# print words for a random category
category = random.choice(list(all_categories))
print "words for category {}:".format(category)
print sorted(set(reader.words(categories=category)))

--
Alan, Peter, 

Thanks for your responses. Sorry about the lack of context and module 
information in my initial post. Peter got the context right - creating python 
object(s) from a collection of text documents (the corpus) in preparation to 
doing text mining and modeling. The modified script from Peter follows. I 
dropped the size limitation and have included some test data below. 

Problems still exist. The code attempts to read files with names based on 
concatena

Re: [Tutor] Introducing myself.

2013-05-13 Thread Alan Gauld

On 13/05/13 13:36, Natal Ngétal wrote:

Welcome,


Otherwise, I am registered on the ml to help if I can, and I'd also like
to know the kind of question that can be asked, or stops the beginner
level, because I think remain an eternal beginner.


The audience of the list is people learning Python. It is deliberately 
open ended, you decide when you are no longer a beginner :-)


We cover the Python language, idioms and the standard library.
Occasionally we will branch into non standard packages, especially the 
better known ones (wxPython, NumPy, Django etc) but generally those are 
better targeted at their own fora.


Finally, we also diverge into general computing theory, tools and other 
non Python topics that might be of value to beginners.


Read the posts and reply when you feel able to contribute.

--
Alan G
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] Introducing myself.

2013-05-13 Thread Natal Ngétal
On 05/13/13 16:36, Alan Gauld wrote:
> The audience of the list is people learning Python. It is
> deliberately open ended, you decide when you are no longer a
> beginner :-)
Ok thanks for your response. As said, I think being a beginner eternal.

> We cover the Python language, idioms and the standard library.
> Occasionally we will branch into non standard packages, especially
> the better known ones (wxPython, NumPy, Django etc) but generally
> those are better targeted at their own fora.
Ok cool, yes you're right it's better to use their own mailing-list. But
small projects is not necessarily their own mailing list.

> Finally, we also diverge into general computing theory, tools and
> other non Python topics that might be of value to beginners.
Cool.

> Read the posts and reply when you feel able to contribute.
Ok thanks again.

-- 
\0/ Hobbestigrou
site web: erakis.eu
L'Europe est trop grande pour être unie. Mais elle est trop petite pour être
divisée. Son double destin est là

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


[Tutor] First Python module I publish.

2013-05-13 Thread Natal Ngétal
Hi,

Sorry for this little pub, some time ago that I published my first
Python module on pypi. This is a port of a Perl module is a very simple
text localization system. I am very happy to have your opinion, ideas
and feedback. I have also a question I use % for the display of
the chain, but I think I understand it is now recommended to use format
or template, but i'm not sure.

This repository on github:

https://github.com/hobbestigrou/Pylocwolowitz

My best regards


-- 
\0/ Hobbestigrou
site web: erakis.eu
L'Europe est trop grande pour être unie. Mais elle est trop petite pour être
divisée. Son double destin est là

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


[Tutor] under, under

2013-05-13 Thread Stafford Baines
Please explain the significance of __some term__.  For example  __name__ as
in 

If __name__ == '__main__':

  main()

 

When is the under, under used?

 

Regards,

 

Stafford

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


Re: [Tutor] under, under

2013-05-13 Thread Natal Ngétal
On 05/13/13 17:21, Stafford Baines wrote:
> When is the under, under used?
It depends the context, for example __name__ represent the name of the current
package. The __init__ it's object methode to initialize the object, and
so on.

-- 
\0/ Hobbestigrou
site web: erakis.eu
L'Europe est trop grande pour être unie. Mais elle est trop petite pour être
divisée. Son double destin est là

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


Re: [Tutor] under, under

2013-05-13 Thread Joel Goldstick
I have seen (and enjoy) people calling double underscore as 'Dunder'


On Mon, May 13, 2013 at 12:32 PM, Natal Ngétal wrote:

> On 05/13/13 17:21, Stafford Baines wrote:
> > When is the under, under used?
> It depends the context, for example __name__ represent the name of the
> current
> package. The __init__ it's object methode to initialize the object, and
> so on.
>
> --
> \0/ Hobbestigrou
> site web: erakis.eu
> L'Europe est trop grande pour être unie. Mais elle est trop petite pour
> être
> divisée. Son double destin est là
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



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


[Tutor] under, under

2013-05-13 Thread Stafford Baines
 

Please explain the significance of __some term__.For example  __name__
as in 

If __name__ == '__main__':

  main()

 

When is the under, under used?

 

Regards,

 

Stafford

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


Re: [Tutor] under, under

2013-05-13 Thread Dave Angel

On 05/13/2013 12:21 PM, Stafford Baines wrote:

Please explain the significance of __some term__.  For example  __name__ as
in

If __name__ == '__main__':

   main()

When is the under, under used?



(Please don't start a second thread with identical content 20 minutes 
after the first)


Underscores aren't anything special to the Python language itself, 
whether leading or trailing.  Thus there is no implicit connection 
between __name__ and name, for example.  However there is a convention 
for single and double underscores, and when the latter are at both start 
and end of a symbol, they have the cute nickname of dunder.


Dunder names are ones defined by the language as having special purpose. 
 We should never make up our own such names, as we might conflict with 
a dunder name that gets added in a later version of Python.


There are a few of them that are just data. One example is the __name__ 
builtin, and it is defined automatically by the import mechanism.  And 
since the script itself is "sort-of" imported, it gets a special name of 
a literal "__main__"   This lets you write code that behaves differently 
when run as a script then when it's imported explicitly from another 
module or script.


Most are methods, and these method names are called "special methods." 
The __init__() method for initializing is the most important, since it's 
implicitly called when a class instance is being initialized.  Likewise 
__new__().  Another (__str__()) is called implicitly when you try to 
interpret an object as a string (such as when you print it).


The debugger uses the __repr__() special method.  When you use the 
addition syntax

a + b

you'll be using the __add__() and/or the __radd__() methods.

All these are pre-defined for the built-in types.  And you can see such 
a list of them for a given type by doing something like:

  a = list()
  print dir(a)

In the debugger, you might get:

 dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__', '__doc__', '__eq__', '__format__', '__ge__', 
'__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', 
'__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', 
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', 
'__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 
'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']


A key point is you can defined these in your own classes.  So you can 
define for example what it means for instances to be equal, or how you 
"add" them, or "subscript" them.


Normally, you do not directly call most of these special methods, 
they'll be called implicitly by various other means.  But you do write 
them in your code.



See:
http://docs.python.org/2/reference/datamodel.html#special-method-names

for a start.

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


Re: [Tutor] under, under

2013-05-13 Thread Jonatán Guadamuz Espinoza
On Mon, May 13, 2013 at 10:21 AM, Stafford Baines 
wrote:
>
> Please explain the significance of __some term__.  For example  __name__
as in
>
> If __name__ == ‘__main__’:
>
>   main()
>
> When is the under, under used?

Section 2.3.2
http://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers

Explain as follows:
__*__System-defined names. These names are defined by the interpreter and
its implementation (including the standard library). Current system names
are discussed in the Special method names section and elsewhere. More will
likely be defined in future versions of Python. Any use of __*__ names, in
any context, that does not follow explicitly documented use, is subject to
breakage without warning.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] under, under

2013-05-13 Thread eryksun
On Mon, May 13, 2013 at 1:18 PM, Dave Angel  wrote:
> Underscores aren't anything special to the Python language itself, whether
> leading or trailing.

I'm pretty sure you were just talking about dunder, dunder.
Underscores in general do have special uses in the language. They're
used to enable name mangling and to implicitly control star imports.

In a class definition, a leading dunder without a trailing dunder
enables name mangling with the class name:

class Bar:
def foo(self):
self.__attr = 'spam'

>>> obj = Bar()
>>> obj.foo()
>>> obj._Bar__attr
'spam'

A subclass with a different name will use a different mangling, so
this provides a semi-private name. The purpose is to protect a private
implementation detail in the base class from being modified by a
subclass, either accidentally or intentionally.  I won't debate the
merits of this. Generally, however, one signals that an attribute is
'private' by using a single leading underscore. This is just a hint to
other programmers.

Name mangling is a compile-time operation. The compiler replaces all
identifiers that have a leading dunder (and no trailing dunder) with
the corresponding mangled name:

>>> Bar.foo.__code__.co_names
('_Bar__attr',)

Another use of underscore is in a star import. To show this, create a module:

>>> import sys, imp
>>> sys.modules['mod'] = mod = imp.new_module(name='mod')

Add two global variables to the module, one with a leading underscore:

>>> mod._foo = 'foo'
>>> mod.bar = 'bar'

Do a star import. Observe that the name with the leading underscore was skipped:

>>> from mod import *
>>> '_foo' in locals()
False
>>> 'bar' in locals()
True

Typically it's better to specify the names used in a star import by
defining __all__:

>>> mod.__all__ = ['_foo', 'bar']
>>> from mod import *
>>> '_foo' in locals()
True
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] variable in format string throwing error

2013-05-13 Thread Jim Mooney
I'm trying variable substitution in a format string that looks like one
that works, but I get an error. What am I doing wrong? tks

x = 40
s = 'John flew to the {0:-^{x}} yesterday'
print(s.format('moon', x))

Error is builtins.KeyError: 'x'

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


Re: [Tutor] variable in format string throwing error

2013-05-13 Thread eryksun
On Mon, May 13, 2013 at 5:51 PM, Jim Mooney  wrote:
> I'm trying variable substitution in a format string that looks like one that
> works, but I get an error. What am I doing wrong? tks
>
> x = 40
> s = 'John flew to the {0:-^{x}} yesterday'
> print(s.format('moon', x))
>
> Error is builtins.KeyError: 'x'

You need to use a keyword argument, x=x:

>>> print(s.format('moon', x=x))
John flew to the --moon-- yesterday

Or change it to use a positional argument:

>>> s = 'John flew to the {0:-^{1}} yesterday'
>>> print(s.format('moon', x))
John flew to the --moon-- yesterday
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making a Primary Number List generator

2013-05-13 Thread Daniel Magruder
Dear Dave,
I am using python 2.
I am still confused as what return does. What does it mean if a function 
returns True to the caller? What is the caller? 
Your code worked for returning a list of 1000 items of odd numbers, so I then 
tried writing a code to replay isodd to give True or False for isprime. 
However, 
> def isodd(candidate):
>if candidate%2 ==0:
>return False
>else:
>return True
The meaning of this I am still confused about. What does it mean if the value 
is returned as false if it has 0 remainder, what does it mean if it is returned 
as true? Is this like a dictionary with keys and values? 
Also, here is my new code, which still does not work. I have no idea why not, 
and am getting very frustrated by the fact that making a program that 
determines if a number is prime or not is so hard for me. I would appreciate 
any assistance, and a verbal walk through of how to logically determine if a 
number is prime. 

def isprime(x):
test=2
numberinquestion = x
while test < numberinquestion:
if numberinquestion % test == 0:
test += 1
return False
elif numberinquestion / test == int:
test += 1
return False
if test == numberinquestion:
return True

def counting_primes():
prime = 2
primelist=[]
while len(primelist) < 1000:
if isprime(prime):
primelist.append(prime)
prime += 1
return primelist
Sincerely,
Dan
On May 12, 2013, at 6:43 AM, Dave Angel  wrote:

> On 05/11/2013 09:58 PM, Daniel Magruder wrote:
> 
> Please respond to the list, not the individual.  Otherwise you're robbing 
> yourself and others of the possibility of learning from and helping multiple 
> people.  I don't mind if you ALSO reply to me (which is what reply-all does 
> by default), but many people do object.  In Thunderbird, you normally just do 
> Reply-list, and it does the right thing.  But with other email programs, you 
> might do reply-all, and remove whichever recipients you don't need.
> 
>> Dear Dave,
>> I can't tell you how much I appreciate your assistance, however as a novice 
>> I doubt my ability to crawl. I sincerely envy your depth of understanding 
>> about this and in trying to learning would really benefit if you could 
>> please expound on a few notions.
>> Why must I top-level call? What is that actually? Several of the sources I 
>> have seen like learnpython.org suggest that def function(): is sufficient...
> 
> A function is defined by a def, but a program that never calls any of them 
> will do nothing at all (except look for syntax errors and the like).  There 
> are probably tens of thousands of defined functions in the library, but 
> running python will only execute the ones you call.
> 
> Typically at the bottom of every script there needs to be at least one 
> function call that gets things started.  (Unless the script is so trivial 
> that it's written without using any functions).  But in either case, some 
> top-level code is needed.
> 
> That top-level code can be as simple as a single call, or it might define a 
> few variables, and then make the call(s).
> 
>> I thought I had to define prime as f(0) so that it would be a float, not an 
>> integer division. Am I wrong? I am so utterly confused.
> 
> I'm afraid you're wrong in a couple of points.  There's no such function as 
> f() in the standard library.  If you wanted to define a literal float, you 
> could either use 0.0, or use float(0).  But you do not want a float there, 
> everything can be done with ints.
> 
>> In many sample codes I have seen num or int seem to be short hand for 
>> anything that is a number, because I though I was dividing and would receive 
>> a float remainder for non-prime numbers, I wan't to use that as a test.
> 
> int and float are types (and act like functions), and if you needed to check 
> the type of an object, you'd use  isinstance(myvar, int) or isinstance(myvar, 
> float).  You can't just do a comparison with int.  But dividing two ints will 
> give an int in Python 2.x and will give a float in Python 3.x.   And that's 
> regardless of whether it comes out even or not.  Which version of Python are 
> you using?
> 
> Fortunately, there's a much better way of telling if an int can be divided by 
> another int:  The modulo operator, represented by a "%" symbol.
> 
>prime%n   will give the remainder, and if it's zero, you know that prime 
> is evenly divisible by n  (and therefore isn't prime).
> 
> 
>> For your suggestion:
>>> def testprime(candidate)
>>>check all ints between 2 and candidate, and return true if any of them 
>>> divide the candidate evenly
>> I don't mean to be so dependent, but how would I do this? Also what is the 
>> difference between return and print?
>>>Otherwise return false
>>> 
> 
> The return statement is the way a function returns a value to its caller.  
> Let's suppose you wanted a function that returned

Re: [Tutor] variable in format string throwing error

2013-05-13 Thread Mark Lawrence

On 13/05/2013 22:51, Jim Mooney wrote:

I'm trying variable substitution in a format string that looks like one
that works, but I get an error. What am I doing wrong? tks

x = 40
s = 'John flew to the {0:-^{x}} yesterday'
print(s.format('moon', x))

Error is builtins.KeyError: 'x'

--
Jim



Using over complicated modern string formatting?  Stick with the old C 
style % style and it's much easier.  Contrary to popular belief it's not 
going away :)


--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

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


Re: [Tutor] Making a Primary Number List generator

2013-05-13 Thread Alan Gauld

On 14/05/13 00:01, Daniel Magruder wrote:


I am still confused as what return does.

> What does it mean if a function returns True to the caller?
> What is the caller?

The caller is the program code that calls the function.
For example if I write a function

def square(x):
return x*x

and write another function to display the first 5 squares:

def square5():
for n in range(1:6):
result = square(n)
print result

square5() is the caller of square() and the return value (x*x)
is stored in result.

return always terminates a function and the value of
the expression following return is the value of the function.


def isodd(candidate):
if candidate%2 ==0:
return False
else:
return True



The meaning of this I am still confused about.

> What does it mean if the value is returned as false

if it has 0 remainder,
what does it mean if it is returned as true?


The function is answering the question "is candidate odd?"
It returns True if candidate is dd and False if candidate
is even. It determines whether candidate is even by dividing candidate 
by 2 and checking to see if there is a zero remainder. If the remainder 
is zero then candidate is even and isodd returns(evaluates to) False.


We can then use it in an if statement like

x = int(raw_input('number: '))
if isodd(x):
   print x,'is odd'
else:
   print x, 'is even'


Is this like a dictionary with keys and values?


No, it's just the value of the function.


def isprime(x):
 test=2
 numberinquestion = x
 while test < numberinquestion:
 if numberinquestion % test == 0:
 test += 1
 return False


Down to here is fine. All you need now is to
return True if you get to the end of the while loop.
(actually you probably don't want/need to increment
test here either but that's a nicety)


 elif numberinquestion / test == int:


But this doesn't work because int is a type not a value.
I'm not quite sure what you think it might be doing but in practice it 
won't work because you are comparing a numeric value to a type.

(type is an object in Python) You could do it like:

 elif type(numberinquestion / test) == int:

But for various reasons isinstance() is the preferred method.


 test += 1
 return False




 if test == numberinquestion:
 return True


You don't really need the if test here since you only exit the while 
loop if test == numberinquestion



def counting_primes():
 prime = 2
 primelist=[]
 while len(primelist) < 1000:
 if isprime(prime):
 primelist.append(prime)
 prime += 1
 return primelist


That seems OK but it would be simpler with a for loop:

def counting_primes():
   primelist = []
   for prime in range(2,1000):
  if isprime(prime):
 primelist.append(prime)
   return primelist

And even shorter with a list comprehension

def counting_primes():
return [n for n in range(2,1000) if isprime(n)]

HTH
--
Alan G
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] Making a Primary Number List generator

2013-05-13 Thread Marc Tompkins
On Mon, May 13, 2013 at 4:01 PM, Daniel Magruder  wrote:

> Dear Dave,
> I am using python 2.
> I am still confused as what return does. What does it mean if a function
> returns True to the caller? What is the caller?
>

You've defined a function - isodd - but it doesn't automatically execute.
It has to be invoked - "called" - from the main process of your script.
Generically, "the caller" is the process that invoked the function.

When you call a function, you pass input to it - "arguments" or
"parameters" - and you (optionally) get back a result.  The way the
function delivers that result is via "return".  The function can "return"
whatever you want it to; this is Python, and you are in control.  True and
False (NOT the same as the strings "True" and "False", by the way!) are two
special values that we use for clarity; you could substitute ANY true
statement for True, and ANY false statement for False.
In fact, you could shorten your isodd() function to:
> def isodd(candidate):
>return candidate%2 !=0:
and it would function identically.



> Your code worked for returning a list of 1000 items of odd numbers, so I
> then tried writing a code to replay isodd to give True or False for
> isprime. However,
> > def isodd(candidate):
> >if candidate%2 ==0:
> >return False
> >else:
> >return True
> The meaning of this I am still confused about. What does it mean if the
> value is returned as false if it has 0 remainder, what does it mean if it
> is returned as true?


If you divide a number by 2 and there's no remainder, it's even.  If there
IS a remainder, it's odd.
Since we're trying to see whether the number "is odd", we return False in
the first case, and True in the second.


Is this like a dictionary with keys and values?
> Also, here is my new code, which still does not work. I have no idea why
> not, and am getting very frustrated by the fact that making a program that
> determines if a number is prime or not is so hard for me. I would
> appreciate any assistance, and a verbal walk through of how to logically
> determine if a number is prime.
>

There are two truisms of education that I consider absolutely vital:
-  If you can't explain it simply, you don't fully understand it yourself
-  The best way to learn something is to try to teach someone else.

When you write a program, you are explaining the problem - in the simplest
possible terms - to a student who truly knows NOTHING of what you're
talking about.  So it is absolutely vital that you understand it
yourself... but at the same time, once you've finished your program you
will understand the problem better than before you started.

A prime number is one whose only integer factors are itself and 1.

Anyway, a very simplistic test for whether X is prime:
a -  2 is the first prime.  Add it to your list of primes.
b -  starting from 3, take a number Y and try to divide it by every item in
the list of primes.
   -  for each item in the list, if the remainder is 0 then Y is not prime
   -  if you reach the end of the list and haven't had a 0 remainder, add Y
to the list.
c -  if Y is equal to or greater than X, you've finished building your list.
d -  if X is in the list, it's prime.

As you can see, this method requires testing every number UP TO X* in order
to determine whether X is prime; your job is actually simpler - you can
stop at c).

* Actually, you only need to test numbers up to the square root of X, but
let's keep it simple for the moment.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making a Primary Number List generator

2013-05-13 Thread Marc Tompkins
On Mon, May 13, 2013 at 5:13 PM, Marc Tompkins wrote:

> In fact, you could shorten your isodd() function to:
> > def isodd(candidate):
> >return candidate%2 !=0:
> and it would function identically.
>

Sorry - that should be
> def isodd(candidate):
>return candidate%2 !=0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making a Primary Number List generator

2013-05-13 Thread Dave Angel

On 05/13/2013 07:01 PM, Daniel Magruder wrote:

Dear Dave,
I am using python 2.
I am still confused as what return does.   What does it mean if a

> function returns True to the caller? What is the caller?

Have you ever used (called) a function?  If so, you've written a caller. 
 For example, if you want the absolute value of an integer, you might do:


import math

x = float(raw_input("Type an integer"))
y = math.fabs(x)#Here I'm calling the function
print "Absolute value is", y

Now, somewhere in the Python library, a function was defined called 
fabs(), and it had a return statement with the value you want.



Your code worked for returning a list of 1000 items of odd numbers, so I then 
tried writing a code to replay isodd to give True or False for isprime. However,

def isodd(candidate):
if candidate%2 ==0:
return False
else:
return True

The meaning of this I am still confused about. What does it mean if the value 
is returned as false if it has 0 remainder, what does it mean if it is returned 
as true? Is this like a dictionary with keys and values?


I don't have a clue what you're confused about.  Do you not understand 
remainders?  If the remainder is 1 then the number is odd, while if the 
remainder is 0 then the number is even.  That's math, not programming.




Also, here is my new code, which still does not work. I have no idea why not, 
and am getting very frustrated by the fact that making a program that 
determines if a number is prime or not is so hard for me. I would appreciate 
any assistance, and a verbal walk through of how to logically determine if a 
number is prime.

def isprime(x):
 test=2
 numberinquestion = x
 while test < numberinquestion:
 if numberinquestion % test == 0:
 test += 1
 return False
 elif numberinquestion / test == int:


Here you go again;  int is a type, not a value. Anyway, all the testing 
you needed was already done, if there's a nonzero remainder you already 
returned a False.  If there is a remainder, there's nothing more to test 
for this value of 'test'.  So increment and loop around.



 test += 1
 return False
 if test == numberinquestion:


This is also unneeded.  If the while has finished, then you can return True.


 return True

def counting_primes():
 prime = 2
 primelist=[]
 while len(primelist) < 1000:
 if isprime(prime):
 primelist.append(prime)
 prime += 1
 return primelist
Sincerely,
Dan




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


Re: [Tutor] under, under

2013-05-13 Thread Steven D'Aprano

On 14/05/13 02:21, Stafford Baines wrote:

Please explain the significance of __some term__.  For example  __name__ as
in

If __name__ == '__main__':

   main()



When is the under, under used?



Underscores are legal characters in names. So you can write:

some_term = whatever()

and it is a legal name.

*Leading* underscores have a special meaning. A single leading underscore is considered 
to be "private":

_name = 42

means that _name should be considered "private, hands off". Or at least, "if you 
break it, you bought it". No guarantees are valid if you change a private value and things 
break.

Names with Double leading and trailing UNDERscores ("dunder") are reserved for 
Python's internal use. They get used for special methods, and a few other things. For 
example, to override the + operator, you write a class that defines __add__ and __radd__ 
methods. To override the == operator, you write a class that defines a __eq__ method. 
There are many examples of such, you can read the docs for a current list:

http://docs.python.org/2/reference/datamodel.html#special-method-names


__name__ is a special variable automatically created by Python. Modules and packages are 
automatically given a variable called __name__ which contains their name. When you are 
executing a module as a script, that variable gets set to the special value 
"__main__" instead of the module's actual name. So you can detect whether your 
code is being run as a script with a tiny bit of boilerplate code:


if __name__ == '__main__':
...


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


Re: [Tutor] Making a Primary Number List generator

2013-05-13 Thread Dave Angel

On 05/13/2013 07:55 PM, Alan Gauld wrote:

On 14/05/13 00:01, Daniel Magruder wrote:


   




That seems OK but it would be simpler with a for loop:

def counting_primes():
primelist = []
for prime in range(2,1000):
   if isprime(prime):
  primelist.append(prime)
return primelist


Actually no, since the OP's looking for the first 1000 primes not for 
all the primes under 1000.


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


Re: [Tutor] Making a Primary Number List generator

2013-05-13 Thread Dave Angel
(Please don't top-post.  And don't reply privately, as I'm not the only 
one reading this thread.  Post the reply to the list, as you did last 
time with your reply-all)


On 05/13/2013 09:45 PM, Daniel Magruder wrote:

Dear Dave,


I don't have a clue what you're confused about.  Do you not understand 
remainders?  If the remainder is 1 then the number is odd, while if the 
remainder is 0 then the number is even.  That's math, not programming.


I understand remainders, I am confused with some of the innate functions of 
python, such as what it assumes. For example here is my code, and maybe this 
well help explain where I am confused...

def isprime(x): # this is a function to find out if a number, x, is prime
 test=2 # this number will test to see if x is prime by exhaustive division
 numberinquestion = x
 while test < numberinquestion: # so long as test is less than the number I 
am testing, then I will compute the following block
 if numberinquestion % test == 0: # if the the remainder is zero then 
the number is not prime
 test += 1 # I am increasing test by one to make sure I 
exhaustively go through all the numbers
# between test and x


Well that increment is misplaced, since you're about to return,  Who 
cares what test is since it's discarded upon function returning?


 I am unsure if the while loop would automatically increase test
if I did not specify +=1. While 6%5 gives a remainder, 15% 5 does not, 
but 15%6 does.


If just one case has no remainder, you've found a non-prime and you can 
return.  Who cares if some of the others have remainders?



 return False # if this condition is met, then the number is not 
prime.  How do i know that false is assigned to x not test?


It's False, not false, and it's not assigned to any local variables. 
It's returned.  So in your case, the caller is testing it for True, 
since the caller is in an if test.  The caller will then skip his 
append(), and the value won't be added to the list.


At this point, you're missing the other increment of test.  This is 
where thetest += 1 is needed.



 return True # I am unsure why this works, does it only get to this point 
after going through the while, so test = x?


Yes.

 How do I know that this works?

That's the definition of a while loop.  it won't fall out of the loop as 
long as the condition is true.  So at this point, we can be sure that 
test is not less than numberinquestion.  Since it was incremented by 
only 1 each time, it must be equal to numberinquestion.


I mean, couldn't the interpreter go through the while and then assign 
true to a non-prime number?


No, because if the number was non-prime then one of the numberinquestion 
%test  would have been zero, and we would already have returned from the 
function without getting to this line.


 Also, since before this is an if statement, that means if x % test != 
0 then it automatically


No idea what you mean by "it" in this question.  Nowhere is there an 
assignment to True in this function.  Returning False does not assign 
anything, and it also ends the function.



is assigned to true, even if the test number is 4 and x is 15. So wouldn't this 
not go to 5 and find the remainder? How do I know this will continue to test 
every possibility?  HERE IS MY CONFUSION.



When x is 15, it has already exited before it gets to 4.  So let's 
pretend you're asking about x being 25.


when test is 4 and x is 25, it will skip the return False, increment 
test (once you move that line), and go back to the while statement. 
That time around it will find a zero remainder, and return False.


def counting_primes(): # a function to create a list of primes
 prime = 2 # two is the first prime and can problematic so starting at two
 primelist=[] # I want to start with an empty list
 while len(primelist) < 1000: # I want a list with 1000 items in it, so to 
do that, I will use while the length is less than 1000
 if isprime(prime): # conditional calling is prime function
 primelist.append(prime) # appending the variable prime to 
primelist if the value is true, but I am worried if this will give false 
positives based on my previous comments above


No, by definition, you trust the function above. If it's broken, fix it, 
don't worry about it here.



 prime += 1 # check the next number to see if it is prime
 return primelist # still not totally sure what return is doing, it doesn't 
print, so is it the same as primelist = primelist? is it reassigning my empty 
primelist at the start of the function to what ever it is now at the end of the 
conditional?


Here you go again;  int is a type, not a value.

I was thinking that if you do something like 15%4, there is a remainder 3 which 
is an int, and as primes got excessively large that ==0 may not be enough to 
recognize primes that are (except two) odd


You can't explain a return without mentioning the caller