Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Νίκος

Στις 28/9/2013 4:59 πμ, ο/η Chris Angelico έγραψε:

On Sat, Sep 28, 2013 at 8:06 AM, Νίκος  wrote:

Well to tell the truth no matter what you say to me if something can be
written in less lines than another implementation but still retain its
simplicity and straightforward logic behind it i would prefer it!
I don't know why you think otherwise, especially people who are used to
write Perl code(me being one of them) would agree with me!


It's high time you stopped trying to write Perl code that runs under
the Python interpreter, and started writing Python code that runs
under the Python interpreter.

There are rules. You first learn the rules and learn to code within
them; then later, once you actually achieve some measure of
competence, you begin learning when to break the rules.

ChrisA
χεχεf
I agree with everything you say, but i also have to say that even 
writing compact code which still retain its simplicity and understanding 
its preferred to me and to other coders too.



For example i wouldn't change this line for anything in my code no 
matter how simple you can get it look..


#check if date entered as intented, format it properly for MySQL
lastvisit = datetime.strptime(lastvisit, '%d %m %Y').strftime('%Y-%m-%d')

why write it in 2-3 lines when you cna have it written in 1-liner?

Isn't it clear as it is now?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Νίκος

Στις 28/9/2013 1:26 πμ, ο/η Dave Angel έγραψε:

On 27/9/2013 18:06, Νίκος wrote:




city = "Άγνωστη Πόλη"
host = "Άγνωστη Προέλευση"

If they were to have the same string assigned to them it should be okey
but they do not.

Or perhaps you can even still think of writing the above into 1-liner
whatsoever!


I already did earlier in this thread.  And you must have read the
message, because you replied to other parts of it.  it's the one where I
referred to code golf, and to APL.  About 12 hours ago, at 6:43 my time.

city, host = "Άγνωστη Πόλη", "Άγνωστη Προέλευση"

I still think it's foolish, but be my guest.


Perhaps i wasn't clear when i expresses my self.

Sure the 1-liner you provided assign different strings to each variable 
respectively, which is nice, but i was referring to have 1-liner that 
had the ability to assign the appropriate string to the variable that 
failed to get a value.


ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or 
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )

try:
gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat')
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
city = "Άγνωστη Πόλη"
host = "Άγνωστη Προέλευση"

In the above code no matter which variable fails to grab a value(gi 
excluded in check) we assign city and host 2 differnt values, while we 
want to assign a value only to the varibale that failed in the try block.


Is there a way to write the except block in 1-liner?
That woudl require that we actually identify which variable failed in try:

This could work:

ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or 
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )

city = "Άγνωστη Πόλη"
host = "Άγνωστη Προέλευση"
try:
gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat')
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except:
pass

but in this case we assign values to the variables BEFORE the try:

It woould be nice if we could write it as:

ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or 
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )

try:
gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat')
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
	if city failed assign to it "Άγνωστη Πόλη" while if host failed assign 
it "Άγνωστη Προέλευση"


but without an if statement and in 1 single line.




--
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Chris Angelico
On Sat, Sep 28, 2013 at 7:33 PM, Νίκος  wrote:
> It woould be nice if we could write it as:
>
>
> ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
> os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
> try:
> gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat')
> city = gi.time_zone_by_addr( ipval )
> host = socket.gethostbyaddr( ipval ) [0]
> except socket.gaierror as e:
> if city failed assign to it "Άγνωστη Πόλη" while if host failed
> assign it "Άγνωστη Προέλευση"
>
> but without an if statement and in 1 single line.

[ROLL] Rosuav rolls his eyes: 1, 1, totalling 2.

Then split your try blocks! You've already been told this.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What's the best way to extract 2 values from a CSV file from each row systematically?

2013-09-28 Thread Luca Cerone
> I'd really appreciate any suggestions or help, thanks in advance!

Hi Alex if you know that you want only columns 3 and 5, you could also use list 
comprehension to fetch the values:

import csv

with open('yourfile.csv','rU') as fo: 
 #the rU means read using Universal newlines
 cr = csv.reader(fo)
 values_list = [(r[2],r[4]) for r in cr] #you have a list of tuples containing 
the values you need

Cheers,
Luca
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: card dealer

2013-09-28 Thread Ned Batchelder

On 9/28/13 2:01 AM, Steven D'Aprano wrote:

On Fri, 27 Sep 2013 17:40:46 -0400, Ned Batchelder wrote:


On 9/27/13 12:10 PM, Denis McMahon wrote:

On Fri, 27 Sep 2013 12:08:33 +, Dave Angel wrote:


i recall
writing a shuffle function in C decades ago, which took an array of
(52) unique items and put them in random order.

Whenever I tried to write shuffles I came up against a fairly
fundamental limit:

52! > prng states

Granted prngs seem to be better on the importing entropy from elsewhere
front these days.



Python's PRNG holds plenty of state to handle card shuffling. Python's
random number generator has a period of 2**19337-1, so it has that many
states.  That is much larger than 52!, about 10**5933 times larger.
(Unless I've botched the math...)

There's a warning about that in the docs:

http://docs.python.org/3/library/random.html#random.shuffle

[quote]
Note that for even rather small len(x), the total number of permutations
of x is larger than the period of most random number generators; this
implies that most permutations of a long sequence can never be generated.
[end quote]

If I've done that maths right, it turns out that 2025 is the largest
number of items that a list can have for Python's default PRNG to
generate every possible shuffle. But does it really matter? For most
purposes, I'd say No. Even if you generated one trillion shuffles per
second, you would have to keep shuffling for more than a trillion years
before repeating yourself.

To be pedantic: a *lot* more than a trillion years. Approximately
10**5789 trillion years. That's about a:

trillion trillion trillion trillion trillion trillion trillion trillion
trillion trillion trillion trillion trillion trillion trillion trillion
trillion trillion trillion trillion trillion trillion trillion trillion
... and so on for 57 more lines ... years.


So in practice it's not really relevant that some shuffles won't be
generated. They'll be randomly distributed throughout the space of all
possible shuffles, which is so large that you really won't notice the
missing ones.




I've thought that way about it too: there are so many shuffles any way, 
it won't be a problem.  But think about it like this:  if you shuffle a 
deck of 52 cards with a default Python random object, then once you have 
dealt out only 28 cards, the entire rest of the deck is completely 
determined.  That is, given the sequence of the first 28 cards, there's 
only one choice for how the remaining 24 will be dealt.  Depending on 
what you need from your deck of cards, that could be a complete disaster.


Is it a problem for a card game simulation?  No.  Is it a problem for a 
program that analyze correlations between the start of the deck and the 
end of the deck?  Maybe.


--Ned.
--
https://mail.python.org/mailman/listinfo/python-list


ANN: psutil 1.1.0 released

2013-09-28 Thread Giampaolo Rodola'
Hi there folks,
I'm pleased to announce the 1.1.0 release of psutil:
http://code.google.com/p/psutil/

=== About ===

psutil is a module providing an interface for retrieving information on all
running processes and system utilization (CPU, memory, disks, network,
users) in a portable way by using Python, implementing many functionalities
offered by command line tools such as ps, top, free, netstat, lsof and
others.
It supports Linux, Windows, OSX, FreeBSD and Solaris with Python versions
from 2.4 to 3.4.


=== New features ===

The main addition included in this new release is the possibility to set
process resource limits on Linux (see "man prlimit").
This functionality is similar to what you can already do with stdlib
resource module (http://docs.python.org/2/library/resource.html) but it is
extended to all processes.
For example, you might limit the number of files which may be opened by a
process:

>>> p = psutil.Process(pid)
>>> p.set_rlimit(psutil.RLIMIT_NOFILE, (128, 128))
>>> files = []
>>> for x in range(200):
... files.append(open('/tmp/foo'))
...
Traceback (most recent call last):
  File "", line 2, in 
IOError: [Errno 24] Too many open files: '/tmp/foo'

...or the maximum size of files that the process may create:

>>> p.set_rlimit(psutil.RLIMIT_FSIZE, (1024, 1024))
>>> f = open('/tmp/foo', 'w')
>>> f.write('x' * 1024)
>>> f.flush()
>>> f.write('x')
>>> f.flush()
Traceback (most recent call last):
  File "", line 1, in 
IOError: [Errno 27] File too large
>>>


=== Main bugfixes ===

* Process.as_dict() return value couldn't be serialized to JSON.
* [Windows] fixed a pretty serious memory leak in Process.get_memory_info().
* [Windows] Process get_children() and "name" property are an order of
magnitude faster.



=== Other changes ===

* STATUS_* and CONN_* constants (returned by Process' status() and
get_connections() methods respectively) have been turned from constant
objects to plain Python strings.
* source and Windows binary files are now hosted on PyPi

Complete list of bugfixes and enhancements is here:
https://psutil.googlecode.com/hg/HISTORY


=== Links ===

* Home page: http://code.google.com/p/psutil
* Downloads:
https://pypi.python.org/pypi?:action=display&name=psutil#downloads
* API Reference: http://code.google.com/p/psutil/wiki/Documentation


Please try out this new release and let me know if you experience any
problem by filing issues on the bug tracker.

All the best,


--- Giampaolo Rodola'

http://code.google.com/p/pyftpdlib/
http://code.google.com/p/psutil/
http://code.google.com/p/pysendfile/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Weird bahaviour from shlex - line no

2013-09-28 Thread Andreas Perstinger

On 28.09.2013 08:26, Daniel Stojanov wrote:

Can somebody explain this. The line number reported by shlex depends
on the previous token. I want to be able to tell if I have just popped
the last token on a line.


[SNIP]


second = shlex.shlex("word1 word2,\nword3")


Punctuation characters like the comma are not considered as word 
characters by default and thus are seen as different tokens (consisting 
of only a single character):


>>> lexer = shlex.shlex("foo, bar, ...")
>>> token = lexer.get_token()
>>> while token != lexer.eof:
...   print token
...   token = lexer.get_token()
...
foo
,
bar
,
.
.
.

If you want to treat them as "word" characters you need to add them to 
the string "wordchars" (a public attribute of the "shlex" instance):


>>> lexer = shlex.shlex("foo.bar, baz")
>>> lexer.wordchar += '.,'
>>> print lexer.get_token()
foo.bar,
>>> print lexer.get_token()
baz

There is also a "debug" attribute (with three different levels: 1, 2, 3; 
default value 0 means no debug output):


>>> lexer = shlex.shlex("foo, bar, ...")
>>> lexer.debug = 1
>>> print lexer.get_token()
shlex: token='foo'
foo
>>> print lexer.get_token()
shlex: popping token ','
,

Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Robert Kern

On 2013-09-27 11:43, Dave Angel wrote:


You should study APL.  Many functions were written in one line, with
twenty lines of explanation.  The function itself was considered
unreadable nonsense. And if a function stopped working, general wisdom
was to throw it out, and re-implement the explanation. I studied it
briefly in class in 1970, and have no idea if there are current
implementations.


You are in luck! GNU APL 1.0 was just released!

  http://www.gnu.org/software/apl/

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

--
https://mail.python.org/mailman/listinfo/python-list


Re: card dealer

2013-09-28 Thread Dave Angel
On 28/9/2013 06:31, Ned Batchelder wrote:


>
> I've thought that way about it too: there are so many shuffles any way, 
> it won't be a problem.  But think about it like this:  if you shuffle a 
> deck of 52 cards with a default Python random object, then once you have 
> dealt out only 28 cards, the entire rest of the deck is completely 
> determined.  That is, given the sequence of the first 28 cards, there's 
> only one choice for how the remaining 24 will be dealt.  Depending on 
> what you need from your deck of cards, that could be a complete disaster.
>
> Is it a problem for a card game simulation?  No.  Is it a problem for a 
> program that analyze correlations between the start of the deck and the 
> end of the deck?  Maybe.
>

Only if there is some correlation between the random number algorithm
and whatever properties you're checking between start and end of deck. 
And if there is, then you've just struck one of the limitations of a
*pseudo* random gen.

I have no idea what sheme is actually used in Python's generator, but
one approach that helps avoid such troubles is to keep a pool of the
"next" P random numbers (where P might be a few hundred).  Then use an
*independent* random number generator (which could be very simple) to
select which item of the pool to use next (followed by replacement from
the first).

it's kind of a local-shuffle of the very long stream of numbers.

Even fairly poor random number generators, if they generate close to
2**n values (for a int size of n) generally become very good when
shuffled this way.


-- 
DaveA


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Νίκος

Στις 28/9/2013 1:19 μμ, ο/η Chris Angelico έγραψε:

On Sat, Sep 28, 2013 at 7:33 PM, Νίκος  wrote:

It woould be nice if we could write it as:


ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
try:
 gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat')
 city = gi.time_zone_by_addr( ipval )
 host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
 if city failed assign to it "Άγνωστη Πόλη" while if host failed
assign it "Άγνωστη Προέλευση"

but without an if statement and in 1 single line.


[ROLL] Rosuav rolls his eyes: 1, 1, totalling 2.

Then split your try blocks! You've already been told this.

ChrisA


No we didn't have said this. if you are referring to this:

ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or 
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )

city = "Άγνωστη Πόλη"
host = "Άγνωστη Προέλευση"
try:
gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat')
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
	print( "metrites.py => (%s): " % lastvisit, repr( sys.exc_info() ), 
file=open('/tmp/err.out', 'w') )


this is not the case, because we want the string to beassigned to the 
variables in the except clause not before the try/except block.


And in 1-liner after the except: too, and value must take only which var 
has failed to be assigned one from within try.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Weird bahaviour from shlex - line no

2013-09-28 Thread Dave Angel
On 28/9/2013 02:26, Daniel Stojanov wrote:

> Can somebody explain this. The line number reported by shlex depends
> on the previous token. I want to be able to tell if I have just popped
> the last token on a line.
>

I agree that it seems weird.  However, I don't think you have made
clear why it's not what you (and I) expect.

import shlex

def parseit(string):
print
print "Parsing -", string
first = shlex.shlex(string)
token = "dummy"
while token:
token = first.get_token()
print token, " -- line", first.lineno

parseit("word1 word2\nword3") #first
parseit("word1 word2,\nword3")#second
parseit("word1 word2,word3\nword4")
parseit("word1 word2+,?\nword3")

This will display the lineno attribute for every token.

shlex is documented at:

http://docs.python.org/2/library/shlex.html

And lineno is documented on that page as:

"""shlex.lineno
Source line number (count of newlines seen so far plus one).
"""

It's not at all clear what "seen so far" is intended to mean, but in
practice, the line number is incremented for the last token on the
line. Thus your first example

Parsing - word1 word2
word3
word1  -- line 1
word2  -- line 2
word3  -- line 2
  -- line 2

word2 has the incremented line number.

But when the token is neither whitespace nor ASCII letters, then it
doesn't increment lineno.  Thus second example:

Parsing - word1 word2,
word3
word1  -- line 1
word2  -- line 1
,  -- line 1  #we would expect this to be "line 2"
word3 -- line 2 -- line 2

Anybody else have some explanation or advice for Daniel, other than
preprocessing the string by stripping any non letters off the end of the
line?

-- 
DaveA


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Weird bahaviour from shlex - line no

2013-09-28 Thread Peter Otten
Dave Angel wrote:

> On 28/9/2013 02:26, Daniel Stojanov wrote:
> 
>> Can somebody explain this. The line number reported by shlex depends
>> on the previous token. I want to be able to tell if I have just popped
>> the last token on a line.
>>
> 
> I agree that it seems weird.  However, I don't think you have made
> clear why it's not what you (and I) expect.
> 
> import shlex
> 
> def parseit(string):
> print
> print "Parsing -", string
> first = shlex.shlex(string)
> token = "dummy"
> while token:
> token = first.get_token()
> print token, " -- line", first.lineno
> 
> parseit("word1 word2\nword3") #first
> parseit("word1 word2,\nword3")#second
> parseit("word1 word2,word3\nword4")
> parseit("word1 word2+,?\nword3")
> 
> This will display the lineno attribute for every token.
> 
> shlex is documented at:
> 
> http://docs.python.org/2/library/shlex.html
> 
> And lineno is documented on that page as:
> 
> """shlex.lineno
> Source line number (count of newlines seen so far plus one).
> """
> 
> It's not at all clear what "seen so far" is intended to mean, but in
> practice, the line number is incremented for the last token on the
> line. Thus your first example
> 
> Parsing - word1 word2
> word3
> word1  -- line 1
> word2  -- line 2
> word3  -- line 2
>   -- line 2
> 
> word2 has the incremented line number.
> 
> But when the token is neither whitespace nor ASCII letters, then it
> doesn't increment lineno.  Thus second example:
> 
> Parsing - word1 word2,
> word3
> word1  -- line 1
> word2  -- line 1
> ,  -- line 1  #we would expect this to be "line 2"
> word3 -- line 2 -- line 2
> 
> Anybody else have some explanation 

The explanation seems obvious: a word may be continued by the next character 
if that is in wordchars, so the parser has to look at that character. If it 
happens to be '\n' the lineno is immediately incremented. Non-wordchars are 
returned as single characters, so there is no need to peek ahead and the 
lineno is not altered.

In short: this looks like an implementation accident. 

OP: I don't see a usecase for the current behaviour -- I suggest that you 
file a bug report.

> or advice for Daniel, other than
> preprocessing the string by stripping any non letters off the end of the
> line?

The following gives the tokens' starting line for your examples

def shlexiter(s):
p = shlex.shlex(s)
p.whitespace = p.whitespace.replace("\n", "")
while True:
lineno = p.lineno
token = p.get_token()
if not token:
break
if token == "\n":
continue
yield lineno, token

def parseit(string):
print("Parsing - {!r}".format(string))
for lineno, token in shlexiter(string):
print("{:3} {!r}".format(lineno, token))
print("")

but I have no idea about the implications for more complex input.

-- 
https://mail.python.org/mailman/listinfo/python-list


Neurolab // "No module named .."

2013-09-28 Thread FiveHydroxy Tryptamine
Hiya
A word of warning, I am a complete beginner.
My problem goes like this:: I've been trying to "import neurolab as nl"(a 
neural network library)and I keep getting the "No module named.." error in my 
Python 2.7.3 shell. There is definitely something wrong with my Python path, 
although everything looks fine (to me). I also appended the sys.path with 
"C:/Python27/neurolab-0.2.3/neurolab" and I still get that error. What am I 
missing?
Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Andreas Perstinger
Νίκος  wrote:

>Στις 28/9/2013 1:19 μμ, ο/η Chris Angelico έγραψε:
>> [ROLL] Rosuav rolls his eyes: 1, 1, totalling 2.
>>
>> Then split your try blocks! You've already been told this.
>>
>No we didn't have said this. if you are referring to this:

At least Denis told you about 24 hours ago:
https://mail.python.org/pipermail/python-list/2013-September/656318.html

So either do it like that (which is the reasonable way) or look for
another programming language.

Bye, Andreas
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Antoon Pardon

Op 28-09-13 00:06, Νίκος schreef:

Στις 27/9/2013 8:00 μμ, ο/η Grant Edwards έγραψε:

On 2013-09-27, ??  wrote:


Sure your method follows the the logic in a straighforward way
step-by-step but i just dont want to spent almost 20 lines of code just
to calculate 2 variables(city and host).


Does your provider charge you per line of code?

If all that matters is the number of lines of code then use this:

   city,host = 0,0

Only _1_ nice short line of code.

Happy?



Well to tell the truth no matter what you say to me if something can be
written in less lines than another implementation but still retain its
simplicity and straightforward logic behind it i would prefer it!
I don't know why you think otherwise, especially people who are used to
write Perl code(me being one of them) would agree with me!


The problem is, as it stands you seem to make it a priority to write
compact code over correct code, wasting everybody's time.

If you hadn't been insisting on trying to reduce the number of lines
of the various given proposals, you might already have a working
solution and be working on something else.

As it is all your attempts to reduce the number of lines while retaining
its simplicity and straightforward logic behind it have only resulted in
you producing code that didn't work.

People like you who judge code in one language by how much it resembles
code in an other language are like people who used to work with glue but
need to work with hammer and nails for some reason and are surprised
they just can't subtituted nails for glue and fail to see they may have
to rethink the design. So they just keep trying glue solutions with
nails and every nail solution that is offered by people who have
experience with nails, they will adapt until it looks like it could be
a glue solution. In the mean time all these glue solutions fail and
much time is wasted.

--
Antoon Pardon

--
https://mail.python.org/mailman/listinfo/python-list


Re: card dealer

2013-09-28 Thread Antoon Pardon

Op 28-09-13 12:31, Ned Batchelder schreef:

On 9/28/13 2:01 AM, Steven D'Aprano wrote:

On Fri, 27 Sep 2013 17:40:46 -0400, Ned Batchelder wrote:


On 9/27/13 12:10 PM, Denis McMahon wrote:

On Fri, 27 Sep 2013 12:08:33 +, Dave Angel wrote:


i recall
writing a shuffle function in C decades ago, which took an array of
(52) unique items and put them in random order.

Whenever I tried to write shuffles I came up against a fairly
fundamental limit:

52! > prng states

Granted prngs seem to be better on the importing entropy from elsewhere
front these days.



Python's PRNG holds plenty of state to handle card shuffling. Python's
random number generator has a period of 2**19337-1, so it has that many
states.  That is much larger than 52!, about 10**5933 times larger.
(Unless I've botched the math...)

There's a warning about that in the docs:

http://docs.python.org/3/library/random.html#random.shuffle

[quote]
Note that for even rather small len(x), the total number of permutations
of x is larger than the period of most random number generators; this
implies that most permutations of a long sequence can never be generated.
[end quote]

If I've done that maths right, it turns out that 2025 is the largest
number of items that a list can have for Python's default PRNG to
generate every possible shuffle. But does it really matter? For most
purposes, I'd say No. Even if you generated one trillion shuffles per
second, you would have to keep shuffling for more than a trillion years
before repeating yourself.

To be pedantic: a *lot* more than a trillion years. Approximately
10**5789 trillion years. That's about a:

trillion trillion trillion trillion trillion trillion trillion trillion
trillion trillion trillion trillion trillion trillion trillion trillion
trillion trillion trillion trillion trillion trillion trillion trillion
... and so on for 57 more lines ... years.


So in practice it's not really relevant that some shuffles won't be
generated. They'll be randomly distributed throughout the space of all
possible shuffles, which is so large that you really won't notice the
missing ones.




I've thought that way about it too: there are so many shuffles any way,
it won't be a problem.  But think about it like this:  if you shuffle a
deck of 52 cards with a default Python random object, then once you have
dealt out only 28 cards, the entire rest of the deck is completely
determined.  That is, given the sequence of the first 28 cards, there's
only one choice for how the remaining 24 will be dealt.  Depending on
what you need from your deck of cards, that could be a complete disaster.


I don't see it. Unless given those 28 cards you can actually predict
those 24 other cards or at least can devise some betting strategy that
will allow you to beat the odds I don't see how this could lead to a
disaster.


Is it a problem for a card game simulation?  No.  Is it a problem for a
program that analyze correlations between the start of the deck and the
end of the deck?  Maybe.


Well if a program would actually find a correlation between the start of
the deck and the end, that may indeed be a cause for worry. But what
evidence is there for that possibility?

--
Antoon Pardon

--
https://mail.python.org/mailman/listinfo/python-list


Re: Neurolab // "No module named .."

2013-09-28 Thread Joel Goldstick
On Sat, Sep 28, 2013 at 10:55 AM, FiveHydroxy Tryptamine <
lilithsol...@gmail.com> wrote:

> Hiya
> A word of warning, I am a complete beginner.
> My problem goes like this:: I've been trying to "import neurolab as nl"(a
> neural network library)and I keep getting the "No module named.." error in
> my Python 2.7.3 shell. There is definitely something wrong with my Python
> path, although everything looks fine (to me). I also appended the sys.path
> with "C:/Python27/neurolab-0.2.3/neurolab" and I still get that error. What
> am I missing?
> Thanks.
> --
> https://mail.python.org/mailman/listinfo/python-list
>

How exactly did you install python?  And how did you install neurolab?
Also, its best to actually cut and paste the traceback rather than
paraphrase it.  Since you don't know what is wrong, you may not be
providing the information necessary to solve the problem

-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


replace only full words

2013-09-28 Thread cerr
Hi,

I have a list of sentences and a list of words. Every full word that appears 
within sentence shall be extended by  i.e. "I drink in the house." Would 
become "I  in the ." (and not "I  in the .")I have 
attempted it like this:
  for sentence in sentences:
for noun in nouns:
  if " "+noun+" " in sentence or " "+noun+"?" in sentence or " "+noun+"!" 
in sentence or " "+noun+"." in sentence:
sentence = sentence.replace(noun, '<' + noun + '>')
  
print(sentence)

but what if The word is in the beginning of a sentence and I also don't like 
the approach using defined word terminations. Also, is there a way to make it 
faster?

Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Joel Goldstick
On Sat, Sep 28, 2013 at 9:53 AM, Antoon Pardon  wrote:

> Op 28-09-13 00:06, Νίκος schreef:
>
>  Στις 27/9/2013 8:00 μμ, ο/η Grant Edwards έγραψε:
>>
>>> On 2013-09-27, ??  wrote:
>>>
>>>  Sure your method follows the the logic in a straighforward way
 step-by-step but i just dont want to spent almost 20 lines of code just
 to calculate 2 variables(city and host).

>>>
>>> Does your provider charge you per line of code?
>>>
>>> If all that matters is the number of lines of code then use this:
>>>
>>>city,host = 0,0
>>>
>>> Only _1_ nice short line of code.
>>>
>>> Happy?
>>>
>>>
>> Well to tell the truth no matter what you say to me if something can be
>> written in less lines than another implementation but still retain its
>> simplicity and straightforward logic behind it i would prefer it!
>> I don't know why you think otherwise, especially people who are used to
>> write Perl code(me being one of them) would agree with me!
>>
>
> The problem is, as it stands you seem to make it a priority to write
> compact code over correct code, wasting everybody's time.
>
> If you hadn't been insisting on trying to reduce the number of lines
> of the various given proposals, you might already have a working
> solution and be working on something else.
>
> As it is all your attempts to reduce the number of lines while retaining
> its simplicity and straightforward logic behind it have only resulted in
> you producing code that didn't work.
>
> People like you who judge code in one language by how much it resembles
> code in an other language are like people who used to work with glue but
> need to work with hammer and nails for some reason and are surprised
> they just can't subtituted nails for glue and fail to see they may have
> to rethink the design. So they just keep trying glue solutions with
> nails and every nail solution that is offered by people who have
> experience with nails, they will adapt until it looks like it could be
> a glue solution. In the mean time all these glue solutions fail and
> much time is wasted.
>
>
> --
> Antoon Pardon
>
> --
> https://mail.python.org/**mailman/listinfo/python-list
>

Its funny how the guy who wants the one line of code has the longest
threads that meander endlessly in the mailing list.  He's a write only
machine -- don't think he reads or understands or has any interest in
understanding what people here explain to him.  This whole goofy exercise
is to try to figure out where the visitor to the website come from -- the
geo ip stuff, etc.  Now back last month there was another endless thread
where is was pointed out that you can't really be sure where someone is
reading from.

Next we'll get more questions about how to screw up unicode, and how to
write code that deals with apache and linux shell with the caveat that the
OP has no interesting in learning how those things work.  He just wants the
one  line.

Troll is maybe too respectable a label to put on this guy.

-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Νίκος

Στις 28/9/2013 6:02 μμ, ο/η Andreas Perstinger έγραψε:

Νίκος  wrote:


Στις 28/9/2013 1:19 μμ, ο/η Chris Angelico έγραψε:

[ROLL] Rosuav rolls his eyes: 1, 1, totalling 2.

Then split your try blocks! You've already been told this.


No we didn't have said this. if you are referring to this:


At least Denis told you about 24 hours ago:
https://mail.python.org/pipermail/python-list/2013-September/656318.html

So either do it like that (which is the reasonable way) or look for
another programming language.

Bye, Andreas


I know what he has said bit this is now what i need.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Help me with Python please (picture)

2013-09-28 Thread dvghana
On Saturday, September 28, 2013 12:43:42 AM UTC, jae...@gmail.com wrote:
> http://imgur.com/E6vrNs4
> 
> 
> 
> 
> 
> Can't seem to be getting an output.

All the comments about using an image to ask for help over here is extremely 
valid so I hope you accept it in good faith. I am a noob like you so I can 
tolerate it and see if I can help you.

So here we  go:
1. random.randit will only return an integer but it sounds to me like you are 
trying to return one of the elements in "chars"

If my understanding is correct try using random.choice instead.

To return a random character from the alphabets you can try:

>> import string
>> char = random.choice(string.ascii_lowercase) 
   #string.ascii_uppercase for uppercace

2. you may not need the main() function.
and you didn't have any 'print' statement so when you run the code you won't 
see anything. You are simply generating random characters and throwing them away

try:
print (random_characters(8))

3. but if you run the code as it stands it won't generate 8 random charaters so 
you'll actually have to be appending it on a list.

So instead of:
new_string = ''
try:
new_string = []

4. Finally, join the elements in the list once they are generated like this:
return "".join(new_string)
but don't forget to append each character anytime the loop runs this way:
new_string.append(random.choice(string.ascii_lowercase))

Overall I wrote my own version of the code and this is what I got:


**
import string
import random

def random_characters(number):
i = 0
new_string = []

while (i < number) :
new_string.append(random.choice(string.ascii_lowercase))
i = i + 1
return "".join(new_string)


print(random_characters(3))
***
-- 
https://mail.python.org/mailman/listinfo/python-list


Which Python Framework for REST API and Facebook Wrapper?

2013-09-28 Thread harry . andrei
I will be designing a REST based API for a cross-platform back end that will 
serve both desktop Facebook users as well as mobile users. It will handle 
operations such as user creation, retrieval of user and other data, payment 
verification and in the case of the desktop side, handle the html/css template 
customization. The database back end is MySQL and I do need a cache system.

Currently we were using Codeigniter (PHP) for our codebase but as CI seems on 
the way out, I do not wish to start a new project based on it. I was looking at 
Laravel for PHP, but, Python is very attractive to me as a language and since 
the introduction of WSGI, I am confident it can make a difference in 
performance and code maintainability over PHP while being able to plug in to 
our dedicated server infrastructure. 

Since I am not experienced with Python frameworks (though learning curve is not 
much of an issue for me) I look to the community to understand which Python 
framework can rival or surpass Codeigniter in terms of performance in heavy 
traffic backend solutions (over 1M requests per day, with up to 100 req/sec at 
peak). I really want to make the switch from PHP to Python as I believe that 
Python can solve more problems with less code and faster execution time, not to 
mention freedom from brackets and semicolons.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which Python Framework for REST API and Facebook Wrapper?

2013-09-28 Thread Joel Goldstick
On Sat, Sep 28, 2013 at 12:20 PM,  wrote:

> I will be designing a REST based API for a cross-platform back end that
> will serve both desktop Facebook users as well as mobile users. It will
> handle operations such as user creation, retrieval of user and other data,
> payment verification and in the case of the desktop side, handle the
> html/css template customization. The database back end is MySQL and I do
> need a cache system.
>
> Currently we were using Codeigniter (PHP) for our codebase but as CI seems
> on the way out, I do not wish to start a new project based on it. I was
> looking at Laravel for PHP, but, Python is very attractive to me as a
> language and since the introduction of WSGI, I am confident it can make a
> difference in performance and code maintainability over PHP while being
> able to plug in to our dedicated server infrastructure.
>
> Since I am not experienced with Python frameworks (though learning curve
> is not much of an issue for me) I look to the community to understand which
> Python framework can rival or surpass Codeigniter in terms of performance
> in heavy traffic backend solutions (over 1M requests per day, with up to
> 100 req/sec at peak). I really want to make the switch from PHP to Python
> as I believe that Python can solve more problems with less code and faster
> execution time, not to mention freedom from brackets and semicolons.
> --
> https://mail.python.org/mailman/listinfo/python-list
>

While there several others with smaller footprint, django is probably the
elephant in the room

-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Neurolab // "No module named .."

2013-09-28 Thread Dave Angel
On 28/9/2013 10:55, FiveHydroxy Tryptamine wrote:

> Hiya
> A word of warning, I am a complete beginner.
> My problem goes like this:: I've been trying to "import neurolab as nl"(a 
> neural network library)and I keep getting the "No module named.." error in my 
> Python 2.7.3 shell. There is definitely something wrong with my Python path, 
> although everything looks fine (to me). I also appended the sys.path with 
> "C:/Python27/neurolab-0.2.3/neurolab" and I still get that error. What am I 
> missing?
> Thanks.

Welcome to the forum, and to Python.

First point:  when you have a problem, especially an import problem, in
some (unnamed) shell, make sure the same symptoms happen at a command
line or the Python interpreter, whichever is appropriate. If the
problem only occurs in the shell, it's a shell problem, or probably a
configuration one.

Second point:  Include the source file you use, hopefully stripped to
the essential minimum.

Third point: include a transcript of all, or the significant portions of
the session (using cut and paste, not paraphrasing). The error
(exception) message is a minimum of 3 lines long,  You show part of the
last line.  The full error message starts with "Traceback" and ends with
some textual summary error message.

Fourth:  indicate how you may have customized your system.  At a
minimum, you must think you installed the neurolab module.  Whatever
that is, whereever you found it.  You should supply the link.

But perhaps you downloaded it and copied it, without actually running
any install program. The directory you specify is NOT the conventional
place for foreign modules.

For example:

davea@think2:~/temppython$ python
Python 2.7.3 (default, Apr 10 2013, 06:20:15) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import unknown
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named unknown
>>> 



-- 
DaveA


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me with Python please (picture)

2013-09-28 Thread Joel Goldstick
On Sat, Sep 28, 2013 at 12:17 PM,  wrote:

> On Saturday, September 28, 2013 12:43:42 AM UTC, jae...@gmail.com wrote:
> > http://imgur.com/E6vrNs4
> >
> >
> >
> >
> >
> > Can't seem to be getting an output.
>
> All the comments about using an image to ask for help over here is
> extremely valid so I hope you accept it in good faith. I am a noob like you
> so I can tolerate it and see if I can help you.
>
> So here we  go:
> 1. random.randit will only return an integer but it sounds to me like you
> are trying to return one of the elements in "chars"
>
> If my understanding is correct try using random.choice instead.
>
> To return a random character from the alphabets you can try:
>
> >> import string
> >> char = random.choice(string.ascii_lowercase)
>#string.ascii_uppercase for uppercace
>
> 2. you may not need the main() function.
> and you didn't have any 'print' statement so when you run the code you
> won't see anything. You are simply generating random characters and
> throwing them away
>
> try:
> print (random_characters(8))
>
> 3. but if you run the code as it stands it won't generate 8 random
> charaters so you'll actually have to be appending it on a list.
>
> So instead of:
> new_string = ''
> try:
> new_string = []
>
> 4. Finally, join the elements in the list once they are generated like
> this:
> return "".join(new_string)
> but don't forget to append each character anytime the loop runs this way:
> new_string.append(random.choice(string.ascii_lowercase))
>
> Overall I wrote my own version of the code and this is what I got:
>
>
> **
> import string
> import random
>
> def random_characters(number):
> i = 0
> new_string = []
>
> while (i < number) :
> new_string.append(random.choice(string.ascii_lowercase))
> i = i + 1
> return "".join(new_string)
>
>
> print(random_characters(3))
> ***
> --
> https://mail.python.org/mailman/listinfo/python-list
>

 I'm guessing this is homework since its kind of a contrived exercise.  If
you do any reading of python tutorials or books for beginners I don't
think  you will see this sort of loop used in python:

   while i < number:
  do_something ...
  i += 1

This is even weirder:

  while (i < number):



Its not that you can't do that.  But it is much more common to see in other
languages (like C or maybe PHP, others ?).  So either the instructor is
promoting this kind of loop because he knows a little about another
language and not so much about python,  or the student has some knowledge
of another language.

I prefer:
  for i in range(number):
  do_something...


and finally

plus + on the calling out of using images to post code.  I'm guessing the
OP is a computer user in the sense of running word, or watching you-tube
videos, etc.  Most non-programmers never used a plain text editor.   If you
want to learn how to write code, and you are a beginner, use the simplest
text editor on your computer, learn to open a shell and run python
interactively and run programs that you saved with your text editors.  Be
glad for simplicity.  And happy you don't write code on these:
http://en.wikipedia.org/wiki/Hollerith_cards


-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: replace only full words

2013-09-28 Thread Tim Chase
On 2013-09-28 09:11, cerr wrote:
> I have a list of sentences and a list of words. Every full word
> that appears within sentence shall be extended by  i.e. "I
> drink in the house." Would become "I  in the ." (and
> not "I  in the .")

This is a good place to reach for regular expressions.  It comes with
a "ensure there is a word-boundary here" token, so you can do
something like the code at the (way) bottom of this email.  I've
pushed it off the bottom in the event you want to try and use regexps
on your own first.  Or if this is homework, at least make you work a
*little* :-)

> Also, is there a way to make it faster?

The code below should do the processing in roughly O(n) time as it
only makes one pass through the data and does O(1) lookups into your
set of nouns.  I included code in the regexp to roughly find
contractions and hyphenated words.  Your original code grows slower
as your list of nouns grows bigger and also suffers from
multiple-replacement issues (if you have the noun-list of ["drink",
"rink"], you'll get results that you don't likely want.

My code hasn't considered case differences, but you should be able to
normalize both the list of nouns and the word you're testing in the
"modify()" function so that it would find "Drink" as well as "drink"

Also, note that some words serve both as nouns and other parts of
speech, e.g. "It's kind of you to house me for the weekend and drink
tea with me."

-tkc

































import re

r = re.compile(r"""
  \b# assert a word boundary
  \w+   # 1+ word characters
  (?:   # a group
   [-']  # a dash or apostrophe
   \w+   # followed by 1+ word characters
   )?# make the group optional (0 or 1 instances)
  \b# assert a word boundary here
  """, re.VERBOSE)

nouns = set([
  "drink",
  "house",
  ])

def modify(matchobj):
  word = matchobj.group(0)
  if word in nouns:
return "<%s>" % word
  else:
return word

print r.sub(modify, "I drink in the house")
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: replace only full words

2013-09-28 Thread MRAB

On 28/09/2013 17:11, cerr wrote:

Hi,

I have a list of sentences and a list of words. Every full word that appears within sentence shall be extended by  i.e. "I 
drink in the house." Would become "I  in the ." (and not "I  in the 
.")I have attempted it like this:
   for sentence in sentences:
 for noun in nouns:
   if " "+noun+" " in sentence or " "+noun+"?" in sentence or " "+noun+"!" in sentence or 
" "+noun+"." in sentence:
sentence = sentence.replace(noun, '<' + noun + '>')

 print(sentence)

but what if The word is in the beginning of a sentence and I also don't like 
the approach using defined word terminations. Also, is there a way to make it 
faster?


It sounds like a regex problem to me:

import re

nouns = ["drink", "house"]

pattern = re.compile(r"\b(" + "|".join(nouns) + r")\b")

for sentence in sentences:
sentence = pattern.sub(r"<\g<0>>", sentence)
print(sentence)

--
https://mail.python.org/mailman/listinfo/python-list


automated unit test generation

2013-09-28 Thread skunkwerk
Hi,
   I've been working on an open source project to auto-generate unit tests for 
web apps based on traces collected from the web server and static code 
analysis.  I've got an alpha version online at www.splintera.com, and the 
source is at https://github.com/splintera/python-django-client.  I'd love to 
get some feedback from the community and extend it to work with other languages 
as well.  

  I wrote it originally because I was sick of coming into companies where I had 
to inherit tens of thousands of lines of code without any tests, and never had 
time to write them manually - being careful to mock out dependencies, specify 
the correct inputs and outputs, and figure out which path it was taking through 
the code.

   I'd like to get some sense of:
- how difficult/tedious is writing unit tests, and why?
- do you wish you had better code coverage?
- how important is testing to you?

thanks,
imran
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me with Python please (picture)

2013-09-28 Thread Dave Angel
On 28/9/2013 12:17, dvgh...@gmail.com wrote:

> On Saturday, September 28, 2013 12:43:42 AM UTC, jae...@gmail.com wrote:
 
 
>> 
>> 
>> 
>> Can't seem to be getting an output.
  

> Overall I wrote my own version of the code and this is what I got:
>
>
> **
> import string
> import random
>
> def random_characters(number):
> i = 0
> new_string = []
>
> while (i < number) :
> new_string.append(random.choice(string.ascii_lowercase))
> i = i + 1
> return "".join(new_string)
>
>
> print(random_characters(3))
> ***

First, I'd clean up the variable name, and use a for loop instead of a
while loop.

import string
import random

def random_characters(number):
new_list = []
for i in range(number):
new_list.append(random.choice(string.ascii_lowercase))
return "".join(new_list)


print(random_characters(8))

Then I'd probably replace the function body with:

def random_characters(number):
return "".join([random.choice(string.ascii_lowercase) for i in
range(number)])

-- 
DaveA


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread rusi
On Friday, September 27, 2013 4:13:52 PM UTC+5:30, Dave Angel wrote:
> You should study APL.  Many functions were written in one line, with
> twenty lines of explanation.  The function itself was considered
> unreadable nonsense. And if a function stopped working, general wisdom
> was to throw it out, and re-implement the explanation. I studied it
> briefly in class in 1970, and have no idea if there are current
> implementations.

>From a certain pov both python and APL have a similar/analogous weakness -- 
>inadequate 'intermediate' structuring constructs.

APL tries to be superman at the expression ie micro level
Likewise what packages and modules are to python, workspaces are to APL (not 
used myself but I know that APLers swear by them) -- call that the macro level

The intermediate level is the issue.  Functional languages have the let/where 
clause to convert a block of defs into a single value. Even gcc extends C 
similarly:
http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html#Statement-Exprs

I do occasionally miss something like that in python
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: replace only full words

2013-09-28 Thread Jussi Piitulainen
MRAB writes:

> On 28/09/2013 17:11, cerr wrote:
> > Hi,
> >
> > I have a list of sentences and a list of words. Every full word
> > that appears within sentence shall be extended by  i.e. "I
> > drink in the house." Would become "I  in the ." (and
> > not "I  in the .")I have attempted it like this:
>
> >for sentence in sentences:
> >  for noun in nouns:
> >if " "+noun+" " in sentence or " "+noun+"?" in sentence or " 
> > "+noun+"!" in sentence or " "+noun+"." in sentence:
> > sentence = sentence.replace(noun, '<' + noun + '>')
> >
> >  print(sentence)
> >
> > but what if The word is in the beginning of a sentence and I also
> > don't like the approach using defined word terminations. Also, is
> > there a way to make it faster?
> >
> It sounds like a regex problem to me:
> 
> import re
> 
> nouns = ["drink", "house"]
> 
> pattern = re.compile(r"\b(" + "|".join(nouns) + r")\b")
> 
> for sentence in sentences:
>  sentence = pattern.sub(r"<\g<0>>", sentence)
>  print(sentence)

Maybe tokenize by a regex and then join the replacements of all
tokens:

import re

def substitute(token):
   if isfullword(token.lower()):
  return '<{}>'.format(token)
   else:
  return token

def tokenize(sentence):
   return re.split(r'(\W)', sentence) 

sentence = 'This is, like, a test.'

tokens = map(substitute, tokenize(sentence))
sentence = ''.join(tokens)

For better results, both tokenization and substitution need to depend
on context. Doing some of that should be an interesting exercise.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: replace only full words

2013-09-28 Thread cerr
On Saturday, September 28, 2013 4:54:35 PM UTC, Tim Chase wrote:
> On 2013-09-28 09:11, cerr wrote:
> 
> > I have a list of sentences and a list of words. Every full word
> 
> > that appears within sentence shall be extended by  i.e. "I
> 
> > drink in the house." Would become "I  in the ." (and
> 
> > not "I  in the .")
> 
> 
> 
> This is a good place to reach for regular expressions.  It comes with
> 
> a "ensure there is a word-boundary here" token, so you can do
> 
> something like the code at the (way) bottom of this email.  I've
> 
> pushed it off the bottom in the event you want to try and use regexps
> 
> on your own first.  Or if this is homework, at least make you work a
> 
> *little* :-)
> 
> 
> 
> > Also, is there a way to make it faster?
> 
> 
> 
> The code below should do the processing in roughly O(n) time as it
> 
> only makes one pass through the data and does O(1) lookups into your
> 
> set of nouns.  I included code in the regexp to roughly find
> 
> contractions and hyphenated words.  Your original code grows slower
> 
> as your list of nouns grows bigger and also suffers from
> 
> multiple-replacement issues (if you have the noun-list of ["drink",
> 
> "rink"], you'll get results that you don't likely want.
> 
> 
> 
> My code hasn't considered case differences, but you should be able to
> 
> normalize both the list of nouns and the word you're testing in the
> 
> "modify()" function so that it would find "Drink" as well as "drink"
> 
> 
> 
> Also, note that some words serve both as nouns and other parts of
> 
> speech, e.g. "It's kind of you to house me for the weekend and drink
> 
> tea with me."
> 
> 
> 
> -tkc
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> import re
> 
> 
> 
> r = re.compile(r"""
> 
>   \b# assert a word boundary
> 
>   \w+   # 1+ word characters
> 
>   (?:   # a group
> 
>[-']  # a dash or apostrophe
> 
>\w+   # followed by 1+ word characters
> 
>)?# make the group optional (0 or 1 instances)
> 
>   \b# assert a word boundary here
> 
>   """, re.VERBOSE)
> 
> 
> 
> nouns = set([
> 
>   "drink",
> 
>   "house",
> 
>   ])
> 
> 
> 
> def modify(matchobj):
> 
>   word = matchobj.group(0)
> 
>   if word in nouns:
> 
> return "<%s>" % word
> 
>   else:
> 
> return word
> 
> 
> 
> print r.sub(modify, "I drink in the house")

Great, only I don't have the re module on my system :(
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: automated unit test generation

2013-09-28 Thread Paul Rubin
skunkwerk  writes:
> - how difficult/tedious is writing unit tests, and why?

The important thing is to write the tests at the same time as the code.
If you do that, it's not too bad.  It means the code is then organized
around the tests and vice versa.  Keeping tests in sync with changes to
code can be annoying and it's easy to let that slip under schedule
pressure.  After that happens enough, you've got a non-TDD program.

Writing tests for code that's already been written without automated
testing in mind is much more difficult and tedious.  Automatically
generating tests for already-written code also seems dubious.

Also, unit tests themselves are fairly easy, but often you also have to
write mock objects to run the tests on and interpret the results.
That's actually taken more thought when I've done it.  I haven't used
the new Python framework for it yet though.

> - do you wish you had better code coverage?

Sure, we could all use that.  On the other hand it slows down
development if you overdo it.  It's a trade-off like anything else.

> - how important is testing to you?

If you mean TDD and automated testing, it's very helpful if you're doing
something intricate, or if it needs frequent changes and redeployment,
etc.  For more straightforward tasks, manually testing while you code is
ok, especially if it's the type of code for which smoke testing is
enough to tell whether the code works.  So like anything else, it's a
trade-off based on the features and priorities of the task at hand.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Mark Lawrence

On 28/09/2013 17:14, Νίκος wrote:


I know what he has said bit this is now what i need.


You actually need the tool that was used on King Edward II.

--
Cheers.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: replace only full words

2013-09-28 Thread MRAB

On 28/09/2013 18:43, cerr wrote:
[snip]

Great, only I don't have the re module on my system :(


Really? It's part of Python's standard distribution.

--
https://mail.python.org/mailman/listinfo/python-list


Re: replace only full words

2013-09-28 Thread Tim Chase
[mercy, you could have trimmed down that reply]

On 2013-09-28 10:43, cerr wrote:
> On Saturday, September 28, 2013 4:54:35 PM UTC, Tim Chase wrote:
>> import re
> 
> Great, only I don't have the re module on my system :(

Um, it's a standard Python library.  You sure about that?

  http://docs.python.org/2/library/re.html

-tkc



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Joel Goldstick
On Sat, Sep 28, 2013 at 1:53 PM, Mark Lawrence wrote:

> On 28/09/2013 17:14, Νίκος wrote:
>
>  I know what he has said bit this is now what i need.
>>
>
> You actually need the tool that was used on King Edward II.
>
>
> --
> Cheers.
>
> Mark Lawrence
>
> --
> https://mail.python.org/**mailman/listinfo/python-list
>

Here's an old chestnut from June:

> BTW both scripts at
> http://superhost.gr/~dauwin/metrites.py
> and at
> http://superhost.gr/~dauwin/cgi-bin/metrites.py
> show the world the passwords to your databases in plain text.

He said he was working on it!  Maybe as soon as that one liner gets
revealed.

-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: replace only full words

2013-09-28 Thread cerr
On Saturday, September 28, 2013 11:07:11 AM UTC-7, MRAB wrote:
> On 28/09/2013 18:43, cerr wrote:
> 
> [snip]
> 
> > Great, only I don't have the re module on my system :(
> 
> >
> 
> Really? It's part of Python's standard distribution.

Oh no, sorry, mis-nformation, i DO have module re available!!! All good!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: replace only full words

2013-09-28 Thread cerr
On Saturday, September 28, 2013 11:17:19 AM UTC-7, Tim Chase wrote:
> [mercy, you could have trimmed down that reply]
> 
> 
> 
> On 2013-09-28 10:43, cerr wrote:
> 
> > On Saturday, September 28, 2013 4:54:35 PM UTC, Tim Chase wrote:
> 
> >> import re
> 
> > 
> 
> > Great, only I don't have the re module on my system :(
> 
> 
> 
> Um, it's a standard Python library.  You sure about that?
> 
> 
> 
>   http://docs.python.org/2/library/re.html
> 

Oh no, sorry, mis-nformation, i DO have module re available!!! All good! 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Zero Piraeus
:

> On Sat, Sep 28, 2013 at 1:53 PM, Mark Lawrence wrote:
> > You actually need the tool that was used on King Edward II.

To be clear, Mark, you are calling for Νίκος to be tortured to death
with a red hot poker, yes?

I'm going to go out on a limb and suggest that such a suggestion is
outside what people generally consider acceptable on this list.

 -[]z.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Mark Lawrence

On 28/09/2013 19:38, Zero Piraeus wrote:

:


On Sat, Sep 28, 2013 at 1:53 PM, Mark Lawrence wrote:

You actually need the tool that was used on King Edward II.


To be clear, Mark, you are calling for Νίκος to be tortured to death
with a red hot poker, yes?

I'm going to go out on a limb and suggest that such a suggestion is
outside what people generally consider acceptable on this list.

  -[]z.



Not tortured, simply murdered so we don't have to put up with his 
completely unacceptable behaviour, which sadly is thriving owing to so 
many people ignoring the "do not feed this moron" signs.


--
Cheers.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Unit Tests

2013-09-28 Thread Terry Reedy

On 9/28/2013 12:52 AM, melw...@gmail.com wrote:
[How can I test...]


import random

intro = 'I have chosen a number from 1-10'
request = 'Guess a number: '
responseHigh = "That's too high."
responseLow  = "That's too low."
responseCorrect = "That's right!"
goodbye = 'Goodbye and thanks for playing!'

print(intro)

def main():
 guessesTaken = 0
 number = random.randint(1, 10)
 while guessesTaken < 5:
 print(request)
 guess = input()
 guess = int(guess)

 guessesTaken = guessesTaken + 1

 if guess < number:
 print(responseLow)

 if guess > number:
 print(responseHigh)

 if guess == number:
 break

 if guess == number:
 guessesTaken = str(guessesTaken)
 print(responseCorrect + '! You guessed my number in ' + 
guessesTaken + ' guesses!')

 if guess != number:
 number = str(number)
 print(goodbye + ' The number I was thinking of was ' + number)



if __name__ == '__main__':
 main()


To expand on Dave's answer, I would refactor main() as below.

Note 1. I add 'allowed' so you can easily change the number or let the 
user decide the difficulty. One can always guess right in at most 4 tries.


Note 2. I am presuming that you are using 3.x.

allowed = 5

def getguess(target, allowed):
  tries = 0
  while tries < allowed:
tries += 1
guess = int(input(request))
if guess < target:
  print(response_low)
elif guess > target:
  print(response_high)
else:
  return guess, tries

def main(target)
  guess, tries = getguess(target, allowed)
  if guess == number:
print(responseCorrect + '! You guessed my number in ' + tries + ' 
guesses!')

  else:
print(goodbye + ' The number I was thinking of was ' + number)

if __name__ == '__main__':
  main(random.randint(1, 10))

To test a function, you must be able to control inputs and access 
outputs. Unfortunately, this makes testing simple beginner programs that 
turn user input and random numbers input into screen output harder, in a 
way, than testing complicated math functions, such as one that 
approximates the derivative of a function as a point.


One way to control user input for getguess is to put something like the 
following (untested) in your test module. (Ignore print for the moment.)


class IntInput:
  "Replace input() that should return int as string."
  def __init__(self, ints, print=None)
"Ints must be a sequence of ints"
self.i = -1  # so 0 after first increment
self.ints = ints
self.print = print
  def input(prompt):
"Maybe save prompt, return str(int)."
if self.print:
  self.print(prompt)
i = self.i + 1
self.i = i
return str(self.ints[i])

In test methods, inject a mock input into the tested module with 
something like

g.input = IntInput((5,3,2,1)).input
where the sequence passed is appropriate for the target and the response 
you want. This will be sufficient to test most of the operation of getguess.


(I am aware that some would say that IntInput should be a context 
manager with an exit method that restores g.input. I do not think that 
this complication is needed for this post.)


To test the getguess prompts and main output, collect output lines with 
something like


class Screen:
  def __init__(self):
self.lines = []
  def print(self, line):
self.lines.append(line)

  screen = Screen()
  g.input = IntInput((5,3,2,1), screen.print).input
  # Test that screen.lines is as it should be.
  # Be careful that actual and expected both have
  # or both do not have terminal \n.

For testing main, in test_xxx methods,
screen = Screen
g.print = screen.print
# test screen.lines in

Another approach is to replace sys.stdin/out as is done in 
test.support.capture_stdin/out, but the latter are considered internal 
functions not for general use, and this method seems more complicated.


random and random.randint could be mocked, but this in not needed for 
this program with the randint call moved out of main().


---
Terry Jan Reedy


--
https://mail.python.org/mailman/listinfo/python-list


Re: Neurolab // "No module named .."

2013-09-28 Thread Terry Reedy

On 9/28/2013 10:55 AM, FiveHydroxy Tryptamine wrote:

Hiya A word of warning, I am a complete beginner. My problem goes
like this:: I've been trying to "import neurolab as nl"(a neural
network library)and I keep getting the "No module named.." error in
my Python 2.7.3 shell. There is definitely something wrong with my
Python path, although everything looks fine (to me). I also appended
the sys.path with "C:/Python27/neurolab-0.2.3/neurolab" and I still
get that error. What am I missing? Thanks.


Perhaps that sys.path should contain directory paths but not module 
paths. I suspect that "C:/Python27/neurolab-0.2.3" is the directory you 
should append. Import will then find the neurolab module it contains.


--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list


Re: Neurolab // "No module named .."

2013-09-28 Thread Mark Lawrence

On 28/09/2013 15:55, FiveHydroxy Tryptamine wrote:

Hiya
A word of warning, I am a complete beginner.
My problem goes like this:: I've been trying to "import neurolab as nl"(a neural network 
library)and I keep getting the "No module named.." error in my Python 2.7.3 shell. There is 
definitely something wrong with my Python path, although everything looks fine (to me). I also appended the 
sys.path with "C:/Python27/neurolab-0.2.3/neurolab" and I still get that error. What am I missing?
Thanks.



Are you sure that path is correct?  I'd expect to see something like 
"C:/Python27/lib/site-packages/neurolab-0.2.3/neurolab"


--
Cheers.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Steven D'Aprano
On Sat, 28 Sep 2013 19:45:40 +0100, Mark Lawrence wrote:

> Not tortured, simply murdered

If your aim was to prove that you're a waste of space than Nikos, you've 
admirably succeeded.

*plonk*


-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Neurolab // "No module named .."

2013-09-28 Thread MRAB

On 28/09/2013 20:06, Mark Lawrence wrote:

On 28/09/2013 15:55, FiveHydroxy Tryptamine wrote:

Hiya
A word of warning, I am a complete beginner.
My problem goes like this:: I've been trying to "import neurolab as nl"(a neural network 
library)and I keep getting the "No module named.." error in my Python 2.7.3 shell. There is 
definitely something wrong with my Python path, although everything looks fine (to me). I also appended the 
sys.path with "C:/Python27/neurolab-0.2.3/neurolab" and I still get that error. What am I missing?
Thanks.



Are you sure that path is correct?  I'd expect to see something like
"C:/Python27/lib/site-packages/neurolab-0.2.3/neurolab"


+1

That's very true. If it's meant to be in the Python folder, then I'd
expected it to be in the "Lib\site-packages" subfolder.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Understanding how is a function evaluated using recursion

2013-09-28 Thread Peter Cacioppi
On Thursday, September 26, 2013 7:23:47 AM UTC-7, Neil Cerutti wrote:
> On 2013-09-26, Neil Cerutti  wrote:
> 
> > def flatten(seq):
> 
> >
> 
> > [1] http://en.wiktionary.org/wiki/bikeshed
> 
> 
> 
> In that spirit, it occurs to me that given current Python
> 
> nomenclature, 'flattened' would be a better name.
> 
> 
> 
> -- 
> 
> Neil Cerutti


The example presented here is simple enough for someone who is confident with 
recursion and somewhat new to Python. So perhaps a refresher on recursion would 
help.


The way to grok recursion for the first time is (a) to read some general info 
about it (Wikipedia has some decent stuff here, but there are many other 
sources) and (b) find a simple recursion example and play around with it in the 
debugger.

Python has some decent debugger solutions - I like using ipdb with iPython.

The factorial function is a good one to play around with if you're new to 
recursion. The Fibonacci sequence is also good. Find a .py example, or, better 
yet, write your own based on psuedo code.

If you're a recursion expert already, then I don't know what to tell you other 
than Python seems to have implemented recursion faithfully and there are no 
gotchas that I can see.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Weird bahaviour from shlex - line no

2013-09-28 Thread Piet van Oostrum
Peter Otten <__pete...@web.de> writes:

> Dave Angel wrote:
>
>> On 28/9/2013 02:26, Daniel Stojanov wrote:
>> 
>>> Can somebody explain this. The line number reported by shlex depends
>>> on the previous token. I want to be able to tell if I have just popped
>>> the last token on a line.
[...]
> The explanation seems obvious: a word may be continued by the next character 
> if that is in wordchars, so the parser has to look at that character. If it 
> happens to be '\n' the lineno is immediately incremented. Non-wordchars are 
> returned as single characters, so there is no need to peek ahead and the 
> lineno is not altered.
>
> In short: this looks like an implementation accident. 

I think shlex should be changed to give the line number of the start of
the token in self.lineno. It isn't hard.
-- 
Piet van Oostrum 
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Chris Angelico
On Sun, Sep 29, 2013 at 4:45 AM, Mark Lawrence  wrote:
> Not tortured, simply murdered so we don't have to put up with his completely
> unacceptable behaviour, which sadly is thriving owing to so many people
> ignoring the "do not feed this moron" signs.

You miss one important factor in these discussions: the silent
majority of readers. We have a few people here who are not "worth"
responding to, as they're highly unlikely to listen (the most
noteworthy other example being jmf on Unicode), but that doesn't mean
the threads can't be useful to someone else. And sometimes there can
be some extremely entertaining conversation, too.

That's also why I don't plonk anyone :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: card dealer

2013-09-28 Thread Tim Roberts
Antoon Pardon  wrote:
>
>Op 28-09-13 12:31, Ned Batchelder schreef:
>>
>> I've thought that way about it too: there are so many shuffles any way,
>> it won't be a problem.  But think about it like this:  if you shuffle a
>> deck of 52 cards with a default Python random object, then once you have
>> dealt out only 28 cards, the entire rest of the deck is completely
>> determined.  That is, given the sequence of the first 28 cards, there's
>> only one choice for how the remaining 24 will be dealt.  Depending on
>> what you need from your deck of cards, that could be a complete disaster.
>
>I don't see it. Unless given those 28 cards you can actually predict
>those 24 other cards or at least can devise some betting strategy that
>will allow you to beat the odds I don't see how this could lead to a
>disaster.

That's exactly the problem.  Because the number of permutations is limited,
once you know the first 28 cards, you can uniquely identify the permutation
you started with, and that's enough to get the entire sequence.

Now, it's going to take a hell of a lot of memory to store that
information, so I'm not sure it is a disaster in a practical sense.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Ben Finney
Mark Lawrence  writes:

> On 28/09/2013 19:38, Zero Piraeus wrote:
> > To be clear, Mark, you are calling for Νίκος to be tortured to death
> > with a red hot poker, yes?
>
> Not tortured, simply murdered so we don't have to put up with his
> completely unacceptable behaviour

Regardless of the behaviour of anyone else, threatening them (with calls
for their murder) is completely unacceptable in this forum. Please don't
do it, ever.

-- 
 \ “Religious faith is the one species of human ignorance that |
  `\will not admit of even the *possibility* of correction.”  —Sam |
_o__) Harris, _The End of Faith_, 2004 |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list