Re: Is Python really "Lisp without parentheses"? So would it be easy to *implement* a lot of Python in Scheme/Lisp?

2014-01-04 Thread Chris Seberino
Thanks.. I think your 10% Python idea is the way to go.  And you are right
that most of Python is not needed in an intro course.  
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: On a scrollbar for tkinter

2014-01-04 Thread eneskristo
On Friday, January 3, 2014 12:00:05 PM UTC+1, Vlastimil Brom wrote:
> 2014/1/3  :
> 
> > @Rick
> 
> > I found some solutions for python 2.x, but still, as I am with the future, 
> > I need a futuristic solution or 2, so if anyone else could help me, I'd be 
> > grateful!
> 
> > --
> 
> 
> 
> Hi,
> 
> I usually don't use tkinter myself, hence others may have more
> 
> idiomatic suggestions,
> 
> but you can of course use ScrolledWindow  tix with python3; cf.:
> 
> 
> 
> from tkinter import tix
> 
> 
> 
> root = tix.Tk()
> 
> root.title("scrolled window")
> 
> root.geometry("50x500+50+50")
> 
> sw= tix.ScrolledWindow(root)
> 
> sw.pack(fill=tix.BOTH, expand=1)
> 
> for i in range(1,101):
> 
> cb = tix.Checkbutton(sw.window, text=str(i))
> 
> cb.pack(fill=tix.BOTH, expand=0)
> 
> root.mainloop()
> 
> 
> 
> hth,
> 
>   vbr

Thank you sir! It really helped!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Strange behaviour with a for loop.

2014-01-04 Thread Sean Murphy
Chris,

Thanks for the tip on the function. I was not aware of that function, Grin. 
Creating the function as you mention makes a lot of sense.

I am doing a lot of little bits and pieces focusing on things I need to 
eventually build a script that is going to compile data from a router and 
config it. 

I have hundreds of other questions, if I don't find answers on the net before 
hand.

Sean 
On 04/01/2014, at 6:52 PM, Cameron Simpson  wrote:

> On 04Jan2014 16:54, Sean Murphy  wrote:
>> Thanks everyone.
>> 
>> Mark thanks for the correction on the ':'. Since I didn't cut and copy, 
>> rather typed it out. Errors crept in. :-)
>> 
>> another question in relation to slicing strings. If you want to get a single 
>> character, just using the index position will get it. If I use the 
>> following, shouldn't it also work? when I use Python 3.3, it didn't provide 
>> anything.
>> 
>> a = "test.txt"
>> print a[3]
>> result is:
>> 
>> 't
> 
> As expected, yes?
> 
>> print a[3:1]
>> Nothing is printed. 
>> 
>> print a[3:2]
>> Nothing is printed.
> 
> These are not requests for 1 and 2 character strings. They are
> requests for the character in the span from, respectively, 3 to 1
> and from 3 to 2. Important: counting FORWARDS. So: zero length
> strings.
> 
>> print a[3:-1]
>> t.tx is printed.
>> 
>> Why doesn't the positive number of characters to be splice return anything 
>> while the negative value does?
> 
> -1 is shorthand for len(a)-1
> It is often convenient to refer to a position from the end of the
> array instead of the start.
> 
> So this means: [3:7], so positions 3,4,5,6.
> 
>> sorry about these basic questions. I do like the splice feature within 
>> Python. Also what is the best method of testing for a blank string?
> 
> Well, and empty string: a == '' or len(a) == 0.
> And, because an "if" tests the nonzeroness of a single argument and
> an empty string has length zero, you can also go:
> 
>  if a:
>print "long string", a
>  else:
>print "empty string"
> 
> OTOH, if you mean a "blank string" to mean "containing only
> whitespace", you can use the string method "isspace", which tests
> that all characters are whitespace and that the string is not empty.
> The doco for isspace() actually says:
> 
>  Return true if there are only whitespace characters in the string
>  and there is at least one character, false otherwise.
> 
> So you might write:
> 
>  if not a or a.isspace():
>print "blank string:", repr(a)
> 
> Really you'd want to put that it a (trivial) function:
> 
>  def isblank(s):
>''' Test that the string `s` is entirely blank.
>'''
>return not s or s.isspace()
> 
> That way you can write isblank() all through your program and control the
> precise meaning by modifying the function.
> 
> Cheers,
> -- 
> 
> The perl5 internals are a complete mess. It's like Jenga - to get the perl5
> tower taller and do something new you select a block somewhere in the middle,
> with trepidation pull it out slowly, and then carefully balance it somewhere
> new, hoping the whole edifice won't collapse as a result.
> - Nicholas Clark, restating an insight of Simon Cozens

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


Re: Highest performance HTTP REST microframework?

2014-01-04 Thread Marc Aymerich
On Sat, Jan 4, 2014 at 5:26 AM, Alec Taylor  wrote:
> What is the highest performance REST microframework?
>
> Happy if it's mostly written in C or C++; as long as it provides a
> simple routes interface in Python.
>
> Currently using bottle and utilising its application, @route and
> app.merge(app2) extra features.

The biggest performance gains on HTTP architectures are usually made
by doing proper HTTP caching. Without knowing anything about your
architecture is hard to tell something more specific :)

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


Re: Strange behaviour with a for loop.

2014-01-04 Thread Chris Angelico
On Sat, Jan 4, 2014 at 8:52 PM, Sean Murphy  wrote:
> Thanks for the tip on the function. I was not aware of that function, Grin. 
> Creating the function as you mention makes a lot of sense.
>
> I am doing a lot of little bits and pieces focusing on things I need to 
> eventually build a script that is going to compile data from a router and 
> config it.
>
> I have hundreds of other questions, if I don't find answers on the net before 
> hand.

Glad it helped!

You may find it helpful to get familiar with the Python interactive
interpreter; if you're on Windows, I strongly recommend IDLE, which
probably came with your Python install anyway. It's easy and fast to
just try something out and see what it does. Plus, it makes for a
really powerful pocket calculator :)

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


On radio buttons in tkinter

2014-01-04 Thread eneskristo
So the issue is like this. I have to make a 2 x N grid like this:
o Radio - 1 o Radio - 2
o Radio - 3 o Radio - 4
...
o Radio - N - 1 o Radio - N

How to do so with a loop? 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: On radio buttons in tkinter

2014-01-04 Thread Chris Angelico
On Sat, Jan 4, 2014 at 9:17 PM,   wrote:
> So the issue is like this. I have to make a 2 x N grid like this:
> o Radio - 1 o Radio - 2
> o Radio - 3 o Radio - 4
> ...
> o Radio - N - 1 o Radio - N
>
> How to do so with a loop?

How far have you managed to get so far? Do you have a Tkinter program
that you're adding this to? Do you know how to iterate across integers
two by two, so that you see the numbers 1, 3, 5, ... N-1? Don't just
show us the question and expect us to do your homework for you.

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


Re: [newbie] Recursive algorithm - review

2014-01-04 Thread Wiktor
On Sat, 4 Jan 2014 13:02:37 +1100, Chris Angelico wrote:

>> def check(towers, x=None):
>> column = []   # value added on pos. x
>> for i in range(len(towers)):
>> column.append(towers[i][c])
>> column = [x for x in column if x != 0]
> 
> Any time you iterate over range(len(something)), you probably want to
> iterate over the thing instead:
> 
> for t in towers:
> column.append(t[c])

  Right, /facepalm/ I've done it so many times. Don't know why not this time.
 
> And any time you iterate over something and append to another list,
> you probably want a list comprehension:
> 
> column = [t[c] for t in towers]
> [...]
> column = [t[c] for t in towers if t[c] != 0]
> [...]
> column = [t[c] for t in towers if t[c]]

  Nice.
 
>> for c in range(len(towers)):  # 'x' not provided,
>> column = []   # so check all columns
> 
> I wouldn't normally wrap a comment onto an unrelated line; I'd put the
> comment above the loop, since it's too long to be a part of the loop
> header itself. It goes as much with the "else" as with the loop,
> anyhow.

  My mistake. I know, that sometimes comment doesn't relate to line that is
next to, but for one second I belived that it would be more readable ('talk'
about the code whitout providing more unnecessary whitespace). Now I see that
it isn't.   

> This is one case where you probably _do_ want to iterate up to
> range(len(towers)), though, which is why I said "probably" above. :)
> 
>> for i in range(len(towers)):
>> column.append(towers[i][c])
>> column = [x for x in column if x != 0]
> 
> This is the same code you had above, so it can benefit from the same
> translation. But maybe it'd be even cleaner to simply call yourself?
> 
> if not check(towers, i): return False

  You're right. It's cleaner this way.
 
>> # print(column)
>> if len(column) != len(set(column)):
>> return False
>> return True
> 
> And in fact, you might want to turn this whole branch into something
> that harks to a more functional programming style:
> 
> return all((check(towers, i) for i in range(len(towers)))

  Great. I didn't know all() before. :-)
  Now check() function looks very neat. 
  Although 'if' statement must now looks like: 'if x is not None:'. Earlier x
never was going to be 0. Now it can be.
 
>> random.shuffle(row)# at every recursion
> 
> Again, I wouldn't wrap comments onto unrelated lines. You see how
> confusing this looks, now that I take this line out of context? Same
> will happen if it throws an exception.

  Yeap. Now I see it. Never gonna do that again. :-)
 
> When you multiply a list of lists, you get references to the same
> list, yes. But you could use multiplication for one level:
> 
> towers = [[0]*size for _ in range(size)]
> 
> That'll give you independent lists. 

  Got it!

>> if not row:
>> row = [a for a in range(1, size+1)]
>> random.shuffle(row)
> 
> This is the same as you have at the top of 'if not towers'. Can you be
> confident that row is None any time towers is None? If so, just move
> this up above the other check and save the duplication.

  row is None at start, but later it is list - sometimes an empty list. For
that cases this if statement was written. If row == [] -> generate new random
row that I can pop out from.
 
>> num = row.pop(0)   # take num from right, and
>> towers[x // size][x % size] = num  # if doesn't match - put
>> repeat = not check(towers, x)  # back (append) on left -
>># - to rotate
>> if repeat:   # I'll repeat 'matching' next
>> row.append(num)  # number as long as last
>> x -= 1   # changed column is unique
> 
> Hmm, I'm slightly confused by your comments here. You pop(0) and
> append(), and describe that as taking from the right and putting on
> the left. Normally I'd write a list like this:

  Of course, of course. I was thinking one, writing another. I switched left
and right in my explanation. It looks stupid now. ;-)

  Thank you for all Your comments.

-- 
Best regards, Wiktor Matuszewski
'py{}@wu{}em.pl'.format('wkm', 'ka') # email spam trap
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [newbie] Recursive algorithm - review

2014-01-04 Thread Chris Angelico
On Sat, Jan 4, 2014 at 10:09 PM, Wiktor  wrote:
> On Sat, 4 Jan 2014 13:02:37 +1100, Chris Angelico wrote:
>> And in fact, you might want to turn this whole branch into something
>> that harks to a more functional programming style:
>>
>> return all((check(towers, i) for i in range(len(towers)))
>
>   Great. I didn't know all() before. :-)
>   Now check() function looks very neat.

Sometimes they aren't any help at all (puns intended), but sometimes
any() and all() are exactly what you want.

>   Although 'if' statement must now looks like: 'if x is not None:'. Earlier x
> never was going to be 0. Now it can be.

Nicely spotted, I hadn't thought of that implication.

>>> random.shuffle(row)# at every recursion
>>
>> Again, I wouldn't wrap comments onto unrelated lines. You see how
>> confusing this looks, now that I take this line out of context? Same
>> will happen if it throws an exception.
>
>   Yeap. Now I see it. Never gonna do that again. :-)

Please note that I didn't intend this as criticism, or a "this is the
rule so follow it" directive, just as advice :) I'm not bearing down
on you with a sergeant-major's string of orders, just offering some
tips that you're free to ignore if you like. And in fact, you probably
WILL ignore some of them, at some points, even if you believe them to
be good advice now - every stylistic rule must be secondary to the
overriding rule "Make it work and be readable", and should be broken
if it violates the prime directive.

>> This is the same as you have at the top of 'if not towers'. Can you be
>> confident that row is None any time towers is None? If so, just move
>> this up above the other check and save the duplication.
>
>   row is None at start, but later it is list - sometimes an empty list. For
> that cases this if statement was written. If row == [] -> generate new random
> row that I can pop out from.

Yes, but will you ever pass a non-None row and a None towers? If not,
you can deduplicate that bit of code by simply checking one before the
other.

>   Thank you for all Your comments.

My pleasure! Always happy to help out.

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


Re: [newbie] Recursive algorithm - review

2014-01-04 Thread Wiktor
On Fri, 03 Jan 2014 20:47:16 -0500, Terry Reedy wrote:

> [0]*size] is fine for one row
> 
> towers = [[0]*size] for i in range(size)]
> 
> should do what you want for a 2-d array instead of the above.

  Right. Thank you also.

-- 
Best regards, Wiktor Matuszewski
'py{}@wu{}em.pl'.format('wkm', 'ka') # email spam trap
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: On radio buttons in tkinter

2014-01-04 Thread Christian Gollwitzer

Am 04.01.14 11:17, schrieb [email protected]:

So the issue is like this. I have to make a 2 x N grid like this:
o Radio - 1 o Radio - 2
o Radio - 3 o Radio - 4
...
o Radio - N - 1 o Radio - N

How to do so with a loop?



Create the buttons and append them into a list, so you can later refer 
to them. Use grid() to create the layout you want (the text widget is an 
alternative) Make sure you set the same variable and different "values", 
so that the radiobuttons can distinguish which one is selected. The rule 
is:


1) If the associated variable has the value of "value", the button is 
selected


2) If the associated variable has a different value, the button is not 
selected (thus you can implement selecting nothing by setting the 
variable to some bogus value)


3) For Ttk widgets: If the variable is undefined, the button is in the 
third state


I'm not sure Tkinter handles case 3, because if you delete the variable 
object by letting it go out of scope, there is probably no way to 
reattach it to the buttons. And there is no unset method, let alone a 
translation from unset variables to None if you do it by bypassing Tkinter:


Apfelkiste:~ chris$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import Tkinter
>>> t=Tkinter.Tk()
>>> s=Tkinter.StringVar()
>>> s.set('Hello')
>>> s.get()
'Hello'
>>> t.eval('unset ' + str(s))
''
>>> s.get()
Traceback (most recent call last):
  File "", line 1, in 
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", 
line 255, in get

value = self._tk.globalgetvar(self._name)
_tkinter.TclError: can't read "PY_VAR0": no such variable
>>>


IMHO the last call should translate an unset variable to None to by 
useful for three-state widgets. You can still do it manually by invoking 
the widget's state() method


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


Re: [newbie] Recursive algorithm - review

2014-01-04 Thread Wiktor
On Sat, 4 Jan 2014 22:18:09 +1100, Chris Angelico wrote:

>>> This is the same as you have at the top of 'if not towers'. Can you be
>>> confident that row is None any time towers is None? If so, just move
>>> this up above the other check and save the duplication.
>>
>>   row is None at start, but later it is list - sometimes an empty list. For
>> that cases this if statement was written. If row == [] -> generate new random
>> row that I can pop out from.
> 
> Yes, but will you ever pass a non-None row and a None towers? If not,
> you can deduplicate that bit of code by simply checking one before the
> other.

  Oh, now I understand what You mean.
  I rewrote that part.

def generate(size=4, towers=None, row=None, x=0):

if not row:
row = [a for a in range(1, size+1)]
random.shuffle(row)

if not towers:
towers = [[0]*size for _ in range(size)]
towers[0] = row[:]
random.shuffle(row)
x = size - 1 

if x + 1 < size**2:
# [...]

  Much more cleaner.
  Thanks!

-- 
Best regards, Wiktor Matuszewski
'py{}@wu{}em.pl'.format('wkm', 'ka') # email spam trap
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [newbie] Recursive algorithm - review

2014-01-04 Thread Wiktor
On Sat, 4 Jan 2014 22:18:09 +1100, Chris Angelico wrote:

>>   Thank you for all Your comments.
> 
> My pleasure! Always happy to help out.

  I'm aware, that at my point of education there's no sense in optimizing code
to squeeze from it every millisecond, but Project Euler gave me habit to
compare time consumption of script every time I make serious change in it.

  Your tune-ups made this script (mostly check() I guess) about 20% faster. So
it's not only 'more readable' profit. :-)

-- 
Best regards, Wiktor Matuszewski
'py{}@wu{}em.pl'.format('wkm', 'ka') # email spam trap
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Blog "about python 3"

2014-01-04 Thread wxjmfauth
Le vendredi 3 janvier 2014 12:14:41 UTC+1, Robin Becker a écrit :
> On 02/01/2014 18:37, Terry Reedy wrote:
> 
> > On 1/2/2014 12:36 PM, Robin Becker wrote:
> 
> >
> 
> >> I just spent a large amount of effort porting reportlab to a version
> 
> >> which works with both python2.7 and python3.3. I have a large number of
> 
> >> functions etc which handle the conversions that differ between the two
> 
> >> pythons.
> 
> >
> 
> > I am imagine that this was not fun.
> 
> 
> 
> indeed :)
> 
> >
> 
> >> For fairly sensible reasons we changed the internal default to use
> 
> >> unicode rather than bytes.
> 
> >
> 
> > Do you mean 'from __future__ import unicode_literals'?
> 
> 
> 
> No, previously we had default of utf8 encoded strings in the lower levels of 
> the 
> 
> code and we accepted either unicode or utf8 string literals as inputs to text 
> 
> functions. As part of the port process we made the decision to change from 
> 
> default utf8 str (bytes) to default unicode.
> 
> 
> 
> > Am I correct in thinking that this change increases the capabilities of
> 
> > reportlab? For instance, easily producing an article with abstracts in 
> > English,
> 
> > Arabic, Russian, and Chinese?
> 
> >
> 
> It's made no real difference to what we are able to produce or accept since 
> utf8 
> 
> or unicode can encode anything in the input and what can be produced depends 
> on 
> 
> fonts mainly.
> 
> 
> 
> >  > After doing all that and making the tests
> 
> ...
> 
> >> I know some of these tests are fairly variable, but even for simple
> 
> >> things like paragraph parsing 3.3 seems to be slower. Since both use
> 
> >> unicode internally it can't be that can it, or is python 2.7's unicode
> 
> >> faster?
> 
> >
> 
> > The new unicode implementation in 3.3 is faster for some operations and 
> > slower
> 
> > for others. It is definitely more space efficient, especially compared to a 
> > wide
> 
> > build system. It is definitely less buggy, especially compared to a narrow 
> > build
> 
> > system.
> 
> >
> 
> > Do your tests use any astral (non-BMP) chars? If so, do they pass on narrow 
> > 2.7
> 
> > builds (like on Windows)?
> 
> 
> 
> I'm not sure if we have any non-bmp characters in the tests. Simple CJK etc 
> etc 
> 
> for the most part. I'm fairly certain we don't have any ability to handle 
> 
> composed glyphs (multi-codepoint) etc etc
> 
> 
> 
> 
> 
> 
> 
> 
> 
> > For one thing, indexing and slicing just works on all machines for all 
> > unicode
> 
> > strings. Code for 2.7 and 3.3 either a) does not index or slice, b) does not
> 
> > work for all text on 2.7 narrow builds, or c) has extra conditional code 
> > only
> 
> > for 2.7.



To Robin Becker

I know nothing about ReportLab except its existence.
Your story is very interesting. As I pointed, I know
nothing about the internal of ReportLab, the technical
aspects: the "Python part", "the used api for the PDF creation").
I have however some experience with the unicode TeX engine,
XeTeX, understand I'm understanding a little bit what's
happening behind the scene.

The very interesting aspect in the way you are holding
unicodes (strings). By comparing Python 2 with Python 3.3,
you are comparing utf-8 with the the internal "representation"
of Python 3.3 (the flexible string represenation).
In one sense, more than comparing Py2 with Py3.

It will be much more interesting to compare utf-8/Python
internals at the light of Python 3.2 and Python 3.3. Python
3.2 has a decent unicode handling, Python 3.3 has an absurd
(in mathematical sense) unicode handling. This is really
shining with utf-8, where this flexible string representation
is just doing the opposite of what a correct unicode
implementation does!

On the memory side, it is obvious to see it.

>>> sys.getsizeof('a'*1 + 'z')
10026
>>> sys.getsizeof('a'*1 + '€')
20040
>>> sys.getsizeof(('a'*1 + 'z').encode('utf-8'))
10018
>>> sys.getsizeof(('a'*1 + '€').encode('utf-8'))
10020

On the performance side, it is much more complexe,
but qualitatively, you may expect the same results.


The funny aspect is that by working with utf-8 in that
case, you are (or one has) forcing Python to work
properly, but one pays on the side of the performance.
And if one wishes to save memory, one has to pay on the
side of performance.

In othe words, attempting to do what Python is
not able to do natively is just impossible!


I'm skipping the very interesting composed glyphs subject
(unicode normalization, ...),  but I wish to point that
with the flexible string representation, one reaches
the top level of surrealism. For a tool which is supposed
to handle these very specific unicode tasks...

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


Re: Blog "about python 3"

2014-01-04 Thread Roy Smith
In article ,
 Mark Lawrence  wrote:

> Surely everybody prefers fast but incorrect code in 
> preference to something that is correct but slow?

I realize I'm taking this statement out of context, but yes, sometimes 
fast is more important than correct.  Sometimes the other way around.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Blog "about python 3"

2014-01-04 Thread Chris Angelico
On Sun, Jan 5, 2014 at 12:55 AM, Roy Smith  wrote:
> In article ,
>  Mark Lawrence  wrote:
>
>> Surely everybody prefers fast but incorrect code in
>> preference to something that is correct but slow?
>
> I realize I'm taking this statement out of context, but yes, sometimes
> fast is more important than correct.  Sometimes the other way around.

More usually, it's sometimes better to be really fast and mostly
correct than really really slow and entirely correct. That's why we
use IEEE floating point instead of Decimal most of the time. Though
I'm glad that Python 3 now deems the default int type to be capable of
representing arbitrary integers (instead of dropping out to a separate
long type as Py2 did), I think it's possibly worth optimizing small
integers to machine words - but mainly, the int type focuses on
correctness above performance, because the cost is low compared to the
benefit. With float, the cost of arbitrary precision is extremely
high, and the benefit much lower.

With Unicode, the cost of perfect support is normally seen to be a
doubling of internal memory usage (UTF-16 vs UCS-4). Pike and Python
decided that the cost could, instead, be a tiny measure of complexity
and actually *less* memory usage (compared to UTF-16, when lots of
identifiers are ASCII). It's a system that works only when strings are
immutable, but works beautifully there. Fortunately Pike doesn't have
any, and Python has only one, idiot like jmf who completely
misunderstands what's going on and uses microbenchmarks to prove
obscure points... and then uses nonsense to try to prove... uhh...
actually I'm not even sure what, sometimes. I wouldn't dare try to
read his posts except that my mind's already in a rather broken state,
as a combination of programming and Alice in Wonderland.

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


Re: How to make a tkinter GUI work on top of a CUI program?

2014-01-04 Thread Beinan Li
Thank you so much Jerry.
I should have read though the man page more carefully.
The available online cscope tutorials never mentioned the line-oriented
mode.



On Sat, Jan 4, 2014 at 1:35 AM, Jerry Hill  wrote:

> On Fri, Jan 3, 2014 at 9:44 PM, Beinan Li  wrote:
> > But some console programs have their own shell or ncurse-like CUI, such
> as
> > cscope.
> > So I figured that I need to first subprocess.popen a bidirectional pipe
> and
> > send command through stdin and get results from stdout and stderr.
> >
> > But in such a case I found that communicate('cmd') will freeze.
>
> Right.  communicate() waits for the subprocess to end, and the
> subprocess is still waiting for you to do something.  Instead, you'll
> need to read() and write() to the subprocess' stdin and stdout
> attributes, probably something like this (untested):
>
> def OnClickBtn(self, event):
> print('OnClickBtn')
> self.subProc.stdin.write('symbolName\n')
> print(self.subProc.stdout.read())
>
> It looks like cscope has both a screen-oriented mode and a line-based
> mode.  When you're working with a subprocess like this, you're going
> to want to be in the line-based mode, so you'll probably want to add
> -l or -L to your command line.
>
> --
> Jerry
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to make a tkinter GUI work on top of a CUI program?

2014-01-04 Thread Beinan Li
... and thanks to Chris too.
Now I got the better idea how the subprocess module works.


On Sat, Jan 4, 2014 at 11:29 AM, Beinan Li  wrote:

> Thank you so much Jerry.
> I should have read though the man page more carefully.
> The available online cscope tutorials never mentioned the line-oriented
> mode.
>
>
>
> On Sat, Jan 4, 2014 at 1:35 AM, Jerry Hill  wrote:
>
>> On Fri, Jan 3, 2014 at 9:44 PM, Beinan Li  wrote:
>> > But some console programs have their own shell or ncurse-like CUI, such
>> as
>> > cscope.
>> > So I figured that I need to first subprocess.popen a bidirectional pipe
>> and
>> > send command through stdin and get results from stdout and stderr.
>> >
>> > But in such a case I found that communicate('cmd') will freeze.
>>
>> Right.  communicate() waits for the subprocess to end, and the
>> subprocess is still waiting for you to do something.  Instead, you'll
>> need to read() and write() to the subprocess' stdin and stdout
>> attributes, probably something like this (untested):
>>
>> def OnClickBtn(self, event):
>> print('OnClickBtn')
>> self.subProc.stdin.write('symbolName\n')
>> print(self.subProc.stdout.read())
>>
>> It looks like cscope has both a screen-oriented mode and a line-based
>> mode.  When you're working with a subprocess like this, you're going
>> to want to be in the line-based mode, so you'll probably want to add
>> -l or -L to your command line.
>>
>> --
>> Jerry
>>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Blog "about python 3"

2014-01-04 Thread Ned Batchelder

On 1/4/14 9:17 AM, Chris Angelico wrote:

On Sun, Jan 5, 2014 at 12:55 AM, Roy Smith  wrote:

In article ,
  Mark Lawrence  wrote:


Surely everybody prefers fast but incorrect code in
preference to something that is correct but slow?


I realize I'm taking this statement out of context, but yes, sometimes
fast is more important than correct.  Sometimes the other way around.


More usually, it's sometimes better to be really fast and mostly
correct than really really slow and entirely correct. That's why we
use IEEE floating point instead of Decimal most of the time. Though
I'm glad that Python 3 now deems the default int type to be capable of
representing arbitrary integers (instead of dropping out to a separate
long type as Py2 did), I think it's possibly worth optimizing small
integers to machine words - but mainly, the int type focuses on
correctness above performance, because the cost is low compared to the
benefit. With float, the cost of arbitrary precision is extremely
high, and the benefit much lower.

With Unicode, the cost of perfect support is normally seen to be a
doubling of internal memory usage (UTF-16 vs UCS-4). Pike and Python
decided that the cost could, instead, be a tiny measure of complexity
and actually *less* memory usage (compared to UTF-16, when lots of
identifiers are ASCII). It's a system that works only when strings are
immutable, but works beautifully there. Fortunately Pike doesn't have
any, and Python has only one, idiot like jmf who completely
misunderstands what's going on and uses microbenchmarks to prove
obscure points... and then uses nonsense to try to prove... uhh...
actually I'm not even sure what, sometimes. I wouldn't dare try to
read his posts except that my mind's already in a rather broken state,
as a combination of programming and Alice in Wonderland.

ChrisA



I really wish we could discuss these things without baiting trolls.

--
Ned Batchelder, http://nedbatchelder.com

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


Re: [newbie] Recursive algorithm - review

2014-01-04 Thread Wiktor
On Sat, 4 Jan 2014 01:16:14 +0100, Wiktor wrote:

> Hi,

  OK, another question. This time, I think, closer to the original subject
(recursive algorithm).

  Thanks to Terry's and Chris' advises I refined script. Then I thought, that
with some changes and with minimal effort I can force this script to generate
Sudoku board (again: filled out, 'solved' one).
  Well, I was wrong. ;-) It actually took me 2 hours to make this script
working fine - even though changes weren't so big. And another one hour to make
it clear enough to share here.


  Idea is still the same. I start with 2d array
  
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]

  And then I fill it up one number by one (exception: first row). At every step
checking if current column is unique (0's not counted) and if also current
segment 3x3 is unique. If that condition is True I call another instance of
generate(), passing to it a) the board, b) the position in which I last putted
number, and c) a list of numbers that in next step this function can choose
from (if empty, function will generate new list). And so on.
  If that condition is False, I try another number from list of available
numbers, and check again. If all numbers fail, I go back one level and try
another number on previous position.


  I'll paste code now, and under that I'll write what's mine concern now.
(if you uncomment hashed lines it will print out entire process of generating
board, but watch out - it can be several thousands of lines) 


###  
import random


attempt_global = 0


def check(board, x=None, sudoku=False):
global attempt_global
attempt_global += 1

if sudoku and len(board) == 9 and x is not None:
c = x % len(board)
r = x // len(board)

# print('Attempt #{}; Checking ({}x{})'.format(attempt_global,
#  r, c))
# for row in board:
# print(row)
# print()

column = [t[c] for t in board if t[c]]

br_min, br_max = r//3 * 3, r//3 * 3 + 3
bc_min, bc_max = c//3 * 3, c//3 * 3 + 3
block = [t[bc_min:bc_max] for t in board[br_min:br_max]]
block_flat = [item for row in block for item in row if item]

return len(column) == len(set(column)) and \
len(block_flat) == len(set(block_flat))

elif x is not None:
c = x % len(board)
column = [t[c] for t in board if t[c]]
return len(column) == len(set(column))

elif sudoku and len(board) == 9:
return all((check(board, i, sudoku) for i in range(0,
   len(board)**2,
   4)))

else:
return all((check(board, i) for i in range(len(board


def generate(size=4, board=None, row=None, x=0, sudoku=False):
if not row:
row = [a for a in range(1, size+1)]
random.shuffle(row)

if not board:
board = [[0]*size for _ in range(size)]
board[0] = row[:]
random.shuffle(row)
x = size - 1

if x + 1 < size**2:
repeat = True
attempt = 0

while repeat:
x += 1
num = row.pop(0)
board[x // size][x % size] = num
repeat = not check(board, x, sudoku)

if repeat:
row.append(num)
board[x // size][x % size] = 0
x -= 1
attempt += 1

if attempt > len(row) - 1:
return False
else:
if not generate(size, board, row, x, sudoku):
repeat = True
row.append(num)
board[x // size][x % size] = 0
x -= 1
attempt += 1

if attempt > len(row) - 1:
return False

return board


def main():

global attempt_global
sudoku_board = generate(9, sudoku=True)

for row in sudoku_board:
print(row)

print('Attempts:', attempt_global)


if __name__ == "__main__": main()

###



  OK, it works fine. Most of the time it generates board in less than 400
attempts, so not so bad. But sometimes it takes over thousand tries to generate
board.

  For example, one time, at attempt #46 it validates last putted '1', and of
course it passes,

Attempt #46; Checking (4x1)
[1, 5, 3, 9, 4, 2, 8, 6, 7]
[2, 7, 6, 5, 8, 1, 3, 9, 4]
[9, 8, 4, 7, 3, 6, 1, 5, 2]
[8, 9, 5, 3, 7, 4, 6, 2, 1]
[7, 1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]

  then fills out entire row, and starting from attempt #61...

Attempt #61; Checking (5x0)
[1, 5, 3, 9, 4, 2, 8, 6, 7]
[2, 7, 

Re: Blog "about python 3"

2014-01-04 Thread wxjmfauth
Le samedi 4 janvier 2014 15:17:40 UTC+1, Chris Angelico a écrit :
> On Sun, Jan 5, 2014 at 12:55 AM, Roy Smith  wrote:
> 
> > In article ,
> 
> >  Mark Lawrence  wrote:
> 
> >
> 
> >> Surely everybody prefers fast but incorrect code in
> 
> >> preference to something that is correct but slow?
> 
> >
> 
> > I realize I'm taking this statement out of context, but yes, sometimes
> 
> > fast is more important than correct.  Sometimes the other way around.
> 
> 
> 
> More usually, it's sometimes better to be really fast and mostly
> 
> correct than really really slow and entirely correct. That's why we
> 
> use IEEE floating point instead of Decimal most of the time. Though
> 
> I'm glad that Python 3 now deems the default int type to be capable of
> 
> representing arbitrary integers (instead of dropping out to a separate
> 
> long type as Py2 did), I think it's possibly worth optimizing small
> 
> integers to machine words - but mainly, the int type focuses on
> 
> correctness above performance, because the cost is low compared to the
> 
> benefit. With float, the cost of arbitrary precision is extremely
> 
> high, and the benefit much lower.
> 
> 
> 
> With Unicode, the cost of perfect support is normally seen to be a
> 
> doubling of internal memory usage (UTF-16 vs UCS-4). Pike and Python
> 
> decided that the cost could, instead, be a tiny measure of complexity
> 
> and actually *less* memory usage (compared to UTF-16, when lots of
> 
> identifiers are ASCII). It's a system that works only when strings are
> 
> immutable, but works beautifully there. Fortunately Pike doesn't have
> 
> any, and Python has only one, idiot like jmf who completely
> 
> misunderstands what's going on and uses microbenchmarks to prove
> 
> obscure points... and then uses nonsense to try to prove... uhh...
> 
> actually I'm not even sure what, sometimes. I wouldn't dare try to
> 
> read his posts except that my mind's already in a rather broken state,
> 
> as a combination of programming and Alice in Wonderland.
> 


I do not mind to be considered as an idiot, but
I'm definitively not blind.

And I could add, I *never* saw once one soul, who is
explaining what I'm doing wrong in the gazillion
of examples I gave on this list.

---

Back to ReportLab. Technically I would be really
interested to see what could happen at the light
of my previous post.

jmf

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


3.4 on Windows ImportError: cannot import name 'IntEnum'

2014-01-04 Thread Mark Lawrence
I first saw this when tring to run the command "py -3.4 -m ensurepip" 
which gave me this lot.


Traceback (most recent call last):
  File "C:\Python34\lib\runpy.py", line 160, in _run_module_as_main
"__main__", fname, loader, pkg_name)
  File "C:\Python34\lib\runpy.py", line 73, in _run_code
exec(code, run_globals)
  File "C:\Python34\lib\ensurepip\__main__.py", line 66, in 
main()
  File "C:\Python34\lib\ensurepip\__main__.py", line 61, in main
default_pip=args.default_pip,
  File "C:\Python34\lib\ensurepip\__init__.py", line 92, in bootstrap
_run_pip(args + [p[0] for p in _PROJECTS], additional_paths)
  File "C:\Python34\lib\ensurepip\__init__.py", line 28, in _run_pip
import pip
  File 
"C:\Users\Mark\AppData\Local\Temp\tmpysmgllcx\pip-1.5.rc1-py2.py3-none-any.whl\pip\__init__.py", 
line 9, in   File 
"C:\Users\Mark\AppData\Local\Temp\tmpysmgllcx\pip-1.5.rc1-py2.py3-none-any.whl\pip\log.py", 
line 10, in 
  File 
"C:\Users\Mark\AppData\Local\Temp\tmpysmgllcx\pip-1.5.rc1-py2.py3-none-any.whl\pip\backwardcompat\__init__.py", 
lin

  File "C:\Python34\lib\urllib\request.py", line 88, in 
import http.client
  File "C:\Python34\lib\http\client.py", line 69, in 
import email.parser
  File "C:\Python34\lib\email\parser.py", line 13, in 
from email.feedparser import FeedParser, BytesFeedParser
  File "C:\Python34\lib\email\feedparser.py", line 27, in 
from email import message
  File "C:\Python34\lib\email\message.py", line 14, in 
from email import utils
  File "C:\Python34\lib\email\utils.py", line 30, in 
import socket
  File "C:\Python34\lib\socket.py", line 51, in 
from enum import IntEnum
ImportError: cannot import name 'IntEnum'

Before I raise an issue on the bug tracker can another Windows user or 
two please confirm that this is a genuine problem and not my 
installation being corrupt or whatever.


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

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


Re: [newbie] Recursive algorithm - review

2014-01-04 Thread Wiktor
On Sat, 4 Jan 2014 20:07:33 +0100, Wiktor wrote:

> I guess that some kind of you have done this before. ;-)


  Damn it. This 'kind' shouldn't be there. Now it sounds silly, 
even offensive. ;-) Normally I would supersede it, but probably attached
mailing-list doesn't recognize those Usenet articles (Chris previously answered
to my superseded article).

-- 
Best regards, Wiktor Matuszewski
'py{}@wu{}em.pl'.format('wkm', 'ka') # email spam trap
-- 
https://mail.python.org/mailman/listinfo/python-list


Flip a graph

2014-01-04 Thread Jason Friedman
I am teaching Python to a class of six-graders as part of an after-school
enrichment.  These are average students.  We wrote a non-GUI "rocket
lander" program:  you have a rocket some distance above the ground, a
limited amount of fuel and a limited burn rate, and the goal is to have the
rocket touch the ground below some threshold velocity.

I thought it would be neat, after a game completes, to print a graph
showing the descent.

Given these measurements:
measurement_dict = { # time, height
0: 10,
1: 9,
2: 9,
3: 8,
4: 8,
5: 7,
6: 6,
7: 4,
8: 5,
9: 3,
10: 2,
11: 1,
12: 0,
}

The easiest solution is to have the Y axis be time and the X axis distance
from the ground, and the code would be:

for t, y in measurement_dict.items():
print("X" * y)

That output is not especially intuitive, though.  A better visual would be
an X axis of time and Y axis of distance:

max_height = max(measurement_dict.values())
max_time = max(measurement_dict.keys())
for height in range(max_height, 0, -1):
row = list(" " * max_time)
for t, y in measurement_dict.items():
if y >= height:
row[t] = 'X'
print("".join(row))

My concern is whether the average 11-year-old will be able to follow such
logic.  Is there a better approach?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Strange behaviour with a for loop.

2014-01-04 Thread Larry Hudson

On 01/03/2014 08:03 PM, Sean Murphy wrote:

Hello all.

This is a newly question. But I wish to understand why the below code is 
providing different results.

import os, sys


if len(sys.argv) > 2:
   filenames = sys.argv[1:]
else
   print ("no parameters provided\n")
   sys.edit()

for filename in filenames:
   print ("filename is: %s\n" %filename)

The above code will return results like:

filename is test.txt

If I modify the above script slightly as shown below, I get a completely 
different result.

if len(sys.argv) > 2:
   filenames = sys.argv[1]
else
   print ("no parameters provided\n")
   sys.exit()

for filename in filenames:
   print ("filename is:  %s\n" % filename)

The result is the filename is spelled out a character at a time. The bit I am 
missing is something to do with splicing or referencing in Python.

Why am I getting different results? In other languages I would have got the 
whole content of the element when using the index of the array (list).


Sean
filename is: t
filename



How easy it is to overlook your own typos...  (No worry, everybody does it)   
;-)

In your first version you have:  filenames = sys.argv[1:]
which gives you a list of filenames (which is what you want).

In your second version you have:  filenames = sys.argv[1]
which is ONE item -- a string, not a list.  You left out the colon.

 -=- Larry -=-

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


Re: Flip a graph

2014-01-04 Thread Wiktor
On Sat, 4 Jan 2014 09:15:39 -0700, Jason Friedman wrote:

> My concern is whether the average 11-year-old will be able to follow such
> logic.  Is there a better approach?

  Basically mine approach is the same, but maybe is easier to explain it to
kids.

  
max_height = max(measurement_dict.values())

temporary_graph = []

for t, y in measurement_dict.items():
temporary_graph.append('X'*y + ' '*(max_height - y))

for i in range(max_height-1, -1, -1):
for item in temporary_graph:
print(item[i], end='')
print()

-- 
Best regards, Wiktor Matuszewski
'py{}@wu{}em.pl'.format('wkm', 'ka') # email spam trap
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Flip a graph

2014-01-04 Thread Terry Reedy

On 1/4/2014 11:15 AM, Jason Friedman wrote:

I am teaching Python to a class of six-graders as part of an
after-school enrichment.


Great. I love seeing basic Python used for that sort of thing.


 These are average students.  We wrote a
non-GUI "rocket lander" program:  you have a rocket some distance above
the ground, a limited amount of fuel and a limited burn rate, and the
goal is to have the rocket touch the ground below some threshold velocity.

I thought it would be neat, after a game completes, to print a graph
showing the descent.

Given these measurements:
measurement_dict = { # time, height
 0: 10,
 1: 9,
 2: 9,
 3: 8,
 4: 8,
 5: 7,
 6: 6,
 7: 4,
 8: 5,
 9: 3,
 10: 2,
 11: 1,
 12: 0,
}

The easiest solution is to have the Y axis be time and the X axis
distance from the ground, and the code would be:

for t, y in measurement_dict.items():
 print("X" * y)

That output is not especially intuitive, though.  A better visual would
be an X axis of time and Y axis of distance:

max_height = max(measurement_dict.values())
max_time = max(measurement_dict.keys())
for height in range(max_height, 0, -1):
 row = list(" " * max_time)
 for t, y in measurement_dict.items():
 if y >= height:
 row[t] = 'X'
 print("".join(row))

My concern is whether the average 11-year-old will be able to follow
such logic.  Is there a better approach?


I would take a black and white 'canvas' (rectangular array of printable 
blocks) approach. First, separate creating the plot (output) and 
printing it. (If nothing else, this allows easy automatic testing of the 
output without capturing print output.)


plot = []
for t, y in measurement_dict.items():
plot[t] = "X" * y

def printplot(plot):
  for row in plot:
print(row)

printplot(plot)

The plot loop could be a list comprehension, but I assume you are not 
doing those. Next, I would modify the plot loop to make a rectangular array.


max_height = max(measurement_dict.values())
...plot[t] = "X" * y + ' ' * max_height - y

Then transpose the array either with zip or an explicit double loop and 
print it with the rows reversed. Example:


plot = ['', 'xx  ', 'x']

def printplot(plot):
  for row in plot:
if not isinstance(row, str):
   row = ''.join(row)
print(row)

printplot(plot)
print()
printplot(reversed(list(zip(*plot
>>>

xx
x

x
x
xx
xxx

Or start with a list of lists of chars (blank canvas) and fill in 'x's 
column by column.


--
Terry Jan Reedy

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


Re: Flip a graph

2014-01-04 Thread Terry Reedy
PS to my previous response: please send plain text only, and not the 
html in addition.


--
Terry Jan Reedy

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


Re: Flip a graph

2014-01-04 Thread Vincent Davis
You might think about using an array to represent the canvas. Starting with
it filled with "" and then for each point change it to "X".
The print the rows of the array.

You can make the array/canvas arbitrarily large and then plot multiple
different paths onto the same array.


Vincent Davis
720-301-3003


On Sat, Jan 4, 2014 at 9:15 AM, Jason Friedman  wrote:

> I am teaching Python to a class of six-graders as part of an after-school
> enrichment.  These are average students.  We wrote a non-GUI "rocket
> lander" program:  you have a rocket some distance above the ground, a
> limited amount of fuel and a limited burn rate, and the goal is to have the
> rocket touch the ground below some threshold velocity.
>
> I thought it would be neat, after a game completes, to print a graph
> showing the descent.
>
> Given these measurements:
> measurement_dict = { # time, height
> 0: 10,
> 1: 9,
> 2: 9,
> 3: 8,
> 4: 8,
> 5: 7,
> 6: 6,
> 7: 4,
> 8: 5,
> 9: 3,
> 10: 2,
> 11: 1,
> 12: 0,
> }
>
> The easiest solution is to have the Y axis be time and the X axis distance
> from the ground, and the code would be:
>
> for t, y in measurement_dict.items():
> print("X" * y)
>
> That output is not especially intuitive, though.  A better visual would be
> an X axis of time and Y axis of distance:
>
> max_height = max(measurement_dict.values())
> max_time = max(measurement_dict.keys())
> for height in range(max_height, 0, -1):
> row = list(" " * max_time)
> for t, y in measurement_dict.items():
> if y >= height:
> row[t] = 'X'
> print("".join(row))
>
> My concern is whether the average 11-year-old will be able to follow such
> logic.  Is there a better approach?
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Flip a graph

2014-01-04 Thread Vincent Davis
When printing the rows of the array/canvas you might add \n to the end of
each row and print the canvas all at once rather than a print statement for
each row.

Vincent Davis
720-301-3003


On Sat, Jan 4, 2014 at 3:10 PM, Vincent Davis wrote:

> You might think about using an array to represent the canvas. Starting
> with it filled with "" and then for each point change it to "X".
> The print the rows of the array.
>
> You can make the array/canvas arbitrarily large and then plot multiple
> different paths onto the same array.
>
>
> Vincent Davis
> 720-301-3003
>
>
> On Sat, Jan 4, 2014 at 9:15 AM, Jason Friedman  wrote:
>
>> I am teaching Python to a class of six-graders as part of an after-school
>> enrichment.  These are average students.  We wrote a non-GUI "rocket
>> lander" program:  you have a rocket some distance above the ground, a
>> limited amount of fuel and a limited burn rate, and the goal is to have the
>> rocket touch the ground below some threshold velocity.
>>
>> I thought it would be neat, after a game completes, to print a graph
>> showing the descent.
>>
>> Given these measurements:
>> measurement_dict = { # time, height
>> 0: 10,
>> 1: 9,
>> 2: 9,
>> 3: 8,
>> 4: 8,
>> 5: 7,
>> 6: 6,
>> 7: 4,
>> 8: 5,
>> 9: 3,
>> 10: 2,
>> 11: 1,
>> 12: 0,
>> }
>>
>> The easiest solution is to have the Y axis be time and the X axis
>> distance from the ground, and the code would be:
>>
>> for t, y in measurement_dict.items():
>> print("X" * y)
>>
>> That output is not especially intuitive, though.  A better visual would
>> be an X axis of time and Y axis of distance:
>>
>> max_height = max(measurement_dict.values())
>> max_time = max(measurement_dict.keys())
>> for height in range(max_height, 0, -1):
>> row = list(" " * max_time)
>> for t, y in measurement_dict.items():
>> if y >= height:
>> row[t] = 'X'
>> print("".join(row))
>>
>> My concern is whether the average 11-year-old will be able to follow such
>> logic.  Is there a better approach?
>>
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Strange behaviour with a for loop.

2014-01-04 Thread Larry Hudson

On 01/03/2014 10:32 PM, Sean Murphy wrote:

Hi everyone.

[snip]

The 2nd part of my original question still stands. I will expand upon this a bit more to 
give more context. I want to print from the beginning of the paragraph to the end. Each 
paragraph ends with "\n\n\n".

If I use "\n\n\n" in lines this does return true for the string. But I don't 
have a starting position and ending position. The list method which I mention before can 
be sliced by going back one element.

Any suggestion on this would be welcomed. I want to achieve this using standard 
core python objects/methods.


Another useful string method is endswith().  With that you don't need to know 
the line length:

if line.endswith('\n\n\n'):
...

(Of course, there is a corresponding startswith() method also.)

If you are specifically looking for blank lines, someone already suggested isspace().  Another 
possibility is rstrip(), which will remove all trailing whitespace.  So you can check for blank 
lines with:


if line.rstrip() == '':
...

There are three of these:
lstrip() is left-strip, which removes leading whitespace,
rstrip() is right-strip, which removes trailing whitespace, and
strip() which removes whitespace from both ends.

All of these are very useful functions.

 -=- Larry -=-

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


Re: Blog "about python 3"

2014-01-04 Thread Terry Reedy

On 1/4/2014 2:10 PM, [email protected] wrote:

Le samedi 4 janvier 2014 15:17:40 UTC+1, Chris Angelico a écrit :



any, and Python has only one, idiot like jmf who completely


Chris, I appreciate the many contributions you make to this list, but 
that does not exempt you from out standard of conduct.



misunderstands what's going on and uses microbenchmarks to prove
obscure points... and then uses nonsense to try to prove... uhh...


Troll baiting is a form of trolling. I think you are intelligent enough 
to know this.  Please stop.



I do not mind to be considered as an idiot, but
I'm definitively not blind.

And I could add, I *never* saw once one soul, who is
explaining what I'm doing wrong in the gazillion
of examples I gave on this list.


If this is true, it is because you have ignored and not read my 
numerous, relatively polite posts. To repeat very briefly:


1. Cherry picking (presenting the most extreme case as representative).

2. Calling space saving a problem (repeatedly).

3. Ignoring bug fixes.

4. Repetition (of the 'gazillion example' without new content).

Have you ever acknowledged, let alone thank people for, the fix for the 
one bad regression you did find. The FSR is still a work in progress. 
Just today, Serhiy pushed a patch speeding up the UTF-32 encoder, after 
previously speeding up the UTF-32 decoder.


--
Terry Jan Reedy


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


[ANN] gg_scrapper -- scrapping of the Google Groups

2014-01-04 Thread Matej Cepl
Did you try to archive email list hosted on the Google Groups?  
Were you endlessly frustrated by the black hole which is Google 
Groups, conscpicious by its absence on the Data Liberation Front 
website? Yes, I was too_


So, I have created a script webscrapping a google group and 
created gg_scrapper_ . Thanks to `Sean Hogan`_ for the first 
inspiration for the script. Any comments would be welcome via 
email (I am sure you can find my addresses somewhere on the 
Web).


Best,

Matěj

.. _too:
   
http://matej.ceplovi.cz/blog/2013/09/we-should-stop-even-pretending-google-is-trying-to-do-the-right-thing/
.. _gg_scrapper:
   https://pypi.python.org/pypi/gg_scrapper
.. _`Sean Hogan`:
   
http://matej.ceplovi.cz/blog/2013/09/we-should-stop-even-pretending-google-is-trying-to-do-the-right-thing/#comment-482

--
http://www.ceplovi.cz/matej/, Jabber: mceplceplovi.cz
GPG Finger: 89EF 4BC6 288A BF43 1BAB  25C3 E09F EF25 D964 84AC

<"}}}><



pgpoyMd0BbZNw.pgp
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Flip a graph

2014-01-04 Thread David Hutto
I would definitely utilize y axis as an altitudinal derivative of time,x.
I'd go with more of a dart type of graphic, so you might be able to show a
peak in altitude from take off, and the rotate the graphic in relation to
the deceleration .

But, you could also depict the velocity, fuel rate, etc with different
colored plots, or as a side meter alongside the canvas the plot is being
displayed on.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [newbie] Recursive algorithm - review

2014-01-04 Thread Chris Angelico
On Sun, Jan 5, 2014 at 6:07 AM, Wiktor  wrote:
> On Sat, 4 Jan 2014 01:16:14 +0100, Wiktor wrote:
>   Idea is still the same. I start with 2d array
>   And then I fill it up one number by one (exception: first row). At every 
> step
> checking if current column is unique (0's not counted) and if also current
> segment 3x3 is unique. If that condition is True I call another instance of
> generate(), passing to it a) the board, b) the position in which I last putted
> number, and c) a list of numbers that in next step this function can choose
> from (if empty, function will generate new list). And so on.
>   If that condition is False, I try another number from list of available
> numbers, and check again. If all numbers fail, I go back one level and try
> another number on previous position.

That's a reasonable brute-force algorithm. I'll get onto some
alternatives down below.

> def check(board, x=None, sudoku=False):

You seem here to have two completely different programs that share
almost no code. This is going to cause confusion, more than anything
else. I recommend saving away the other program and making the Sudoku
one completely separate.programs.

> if sudoku and len(board) == 9 and x is not None:
> c = x % len(board)
> r = x // len(board)

Your algorithm involves a *lot* of division. This may be a premature
optimization (I haven't measured to see if that's actually a
bottleneck), but I would consider rejigging things to minimize this.
(Edit: It almost certainly *is* premature to try to cut out division.
Much better targets elsewhere.)

> br_min, br_max = r//3 * 3, r//3 * 3 + 3
> bc_min, bc_max = c//3 * 3, c//3 * 3 + 3
> block = [t[bc_min:bc_max] for t in board[br_min:br_max]]

You can define max in terms of min, here. I think it'd be clearer than
doing the division again (plus it might be faster, see above):

br = r//3 * 3
bc = c//3 * 3
block = [t[bc:bc+3] for t in board[br:br+3]]

> return len(column) == len(set(column)) and \
> len(block_flat) == len(set(block_flat))

Style point: In Python, it's more normal to bracket conditions like
that, rather than use a backslash.

return (len(column) == len(set(column)) and
len(block_flat) == len(set(block_flat)))

> elif sudoku and len(board) == 9:
> return all((check(board, i, sudoku) for i in range(0,
>len(board)**2,
>4)))

Ultimately, this is testing to see if the board state is valid. It
does this in 81 steps (len(board) squared), each one checking the
column and the block for validity, and not checking the row, because
you assume that to be valid elsewhere. (This last bit is worthy of a
code comment, I think.) Instead, you could simply check the nine
columns and the nine blocks, iteratively.

> def generate(size=4, board=None, row=None, x=0, sudoku=False):
> while repeat:
> x += 1
> num = row.pop(0)
> board[x // size][x % size] = num
> repeat = not check(board, x, sudoku)
>
> if repeat:
> row.append(num)
> board[x // size][x % size] = 0
> x -= 1
> attempt += 1
>
> if attempt > len(row) - 1:
> return False
> else:
> if not generate(size, board, row, x, sudoku):
> repeat = True
> row.append(num)
> board[x // size][x % size] = 0
> x -= 1
> attempt += 1
>
> if attempt > len(row) - 1:
> return False
>
> return board

Code's getting complicated, I'm getting bogged down in the indentation
levels. Is it possible to break out some of this into separate
functions? You're calling the same function in different modes;
stuff's getting a bit messy.

>   OK, it works fine. Most of the time it generates board in less than 400
> attempts, so not so bad. But sometimes it takes over thousand tries to 
> generate
> board.

That's the result of a brute-force algorithm. You're working top-down
and rolling back step by step. It's simple but not fast.

Here's the code for my Binary Sudoku engine. It's not in Python (it's
Pike - semantically similar, but uses a C-like syntax), but hopefully
you should be able to see what it's doing.

https://github.com/Rosuav/binary

There are three distinct parts to it:
1) Validate a state
2) Attempt to solve, by logic
3) Generate a puzzle

The key here is that step 2 uses the same techniques that a human
would use. In the case of Sudoku, that would basically mean
implementing the techniques you'd find on a Sudoku solving help web
site (eg figuring out that the only digit legal in this spot is a 3).
That's going to be far FAR more efficient than brute force, and it'll
take you a long way.

Then in step 3, 

Re: Blog "about python 3"

2014-01-04 Thread Chris Angelico
On Sun, Jan 5, 2014 at 9:46 AM, Terry Reedy  wrote:
> On 1/4/2014 2:10 PM, [email protected] wrote:
>>
>> Le samedi 4 janvier 2014 15:17:40 UTC+1, Chris Angelico a écrit :
>
>
>>> any, and Python has only one, idiot like jmf who completely
>
>
> Chris, I appreciate the many contributions you make to this list, but that
> does not exempt you from out standard of conduct.
>
>
>>> misunderstands what's going on and uses microbenchmarks to prove
>>> obscure points... and then uses nonsense to try to prove... uhh...
>
>
> Troll baiting is a form of trolling. I think you are intelligent enough to
> know this.  Please stop.

My apologies. I withdraw the aforequoted post. You and Ned are
correct, those comments were inappropriate. Sorry.

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


django question

2014-01-04 Thread Igor Korot
Hi, ALL,
Does anybody here use django?
I have a very basic question about it.

Is it possible to display a data grid table with django?
Basically I am looking for displaying a data from the db table on the
web interface thru django or some other web interface.
My main application is in Python, that's why I'd like to explore
Python possibilities first.

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


Re: django question

2014-01-04 Thread Joel Goldstick
On Sat, Jan 4, 2014 at 6:30 PM, Igor Korot  wrote:

> Hi, ALL,
> Does anybody here use django?
> I have a very basic question about it.
>
> Is it possible to display a data grid table with django?
>

Yes, using the django template language.  If you learn django (perhaps 2
days of exploring), you would have the skills to do this.  Check out the
django tutorial


> Basically I am looking for displaying a data from the db table on the
> web interface thru django or some other web interface.
> My main application is in Python, that's why I'd like to explore
> Python possibilities first.
>
> Thank you.
> --
> https://mail.python.org/mailman/listinfo/python-list
>



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


Re: django question

2014-01-04 Thread Tim Chase
On 2014-01-04 15:30, Igor Korot wrote:
> Does anybody here use django?

Yes.  However there's also a Django-users mailing list[1] for
Django-specific questions.  Folks there are friendly & helpful.
 
> Is it possible to display a data grid table with django?

The short answer is yes.

> Basically I am looking for displaying a data from the db table on
> the web interface thru django or some other web interface.

While I prefer Django for larger projects, for a lighter-weight
project such as what you describe, I'd be tempted to go with
something a little more light-weight unless you need additional
interactivity.  I've recently been impressed with Bottle[2] for a
small & clean web framework.  CherryPy comes somewhere in the middle,
but I can't say it met my needs/wants on the last project where it
was chosen (mostly in the documentation department, but it's hard to
beat Django's stellar docs).

-tkc

[1]
http://groups.google.com/group/django-users

[2]
http://bottlepy.org/




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


Update image in same window with, say, PIL

2014-01-04 Thread John O'Hagan
I'm using something like the following to display an image and refresh
it in the same window each time the image file is updated:

import cv

def display(filename):
"""Display scores as they are created"""
cv.NamedWindow(filename)
while 1:
... #wait for signal that filename has been updated, 
#or to break
image = cv.LoadImage(filename)
cv.ShowImage(filename, image)
cv.WaitKey(1000)


I would like to do the same thing using PIL, for two reasons. First,
the main project is written in Python 3, but cv is only available in
Python 2, so I have to launch the above as a separate process and do
IPC with it, which is annoying; whereas PIL has recently come into
Python 3. Second, PIL seems like a more appropriate tool. CV is a
sophisticated computer-vision project which I happen to be more
familiar with, but I'm using it just to display an image, so I feel as
if I'm using the Mars Explorer to vacuum my apartment. 

I have found a couple of StackOverflow and ActiveState recipes to do
this but they all seem to involve great globs of windowing code
involving Tkinter or Qt, which I know nothing about. CV does seem to
magically manage the windowing. Can I do this equally simply with PIL,
or perhaps something else in Python 3?

Thanks,

--

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


Re: Blog "about python 3"

2014-01-04 Thread Steven D'Aprano
Roy Smith wrote:

> In article ,
>  Mark Lawrence  wrote:
> 
>> Surely everybody prefers fast but incorrect code in
>> preference to something that is correct but slow?
> 
> I realize I'm taking this statement out of context, but yes, sometimes
> fast is more important than correct.

I know somebody who was once touring in the States, and ended up travelling
cross-country by road with the roadies rather than flying. She tells me of
the time someone pointed out that they were travelling in the wrong
direction, away from their destination. The roadie driving replied "Who
cares? We're making fantastic time!"

(Ah, the seventies. So many drugs...)

Fast is never more important than correct. It's just that sometimes you
might compromise a little (or a lot) on what counts as correct in order for
some speed.

To give an example, say you want to solve the Travelling Salesman Problem,
and find the shortest path through a whole lot of cities A, B, C, ..., Z.
That's a Hard Problem, expensive to solve correctly.

But if you loosen the requirements so that a correct solution no longer has
to be the absolutely shortest path, and instead accept solutions which are
nearly always close to the shortest (but without any guarantee of how
close), then you can make the problem considerably easier to solve.

But regardless of how fast your path-finder algorithm might become, you're
unlikely to be satisfied with a solution that travels around in a circle
from A to B a million times then shoots off straight to Z without passing
through any of the other cities.



-- 
Steven

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


Re: Blog "about python 3"

2014-01-04 Thread Chris Angelico
On Sun, Jan 5, 2014 at 1:27 PM, Steven D'Aprano
 wrote:
> But regardless of how fast your path-finder algorithm might become, you're
> unlikely to be satisfied with a solution that travels around in a circle
> from A to B a million times then shoots off straight to Z without passing
> through any of the other cities.

On the flip side, that might be the best salesman your company has
ever known, if those three cities have the most customers!

ChrisA
wondering why nobody cares about the customers in TSP discussions
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Blog "about python 3"

2014-01-04 Thread MRAB

On 2014-01-05 02:32, Chris Angelico wrote:

On Sun, Jan 5, 2014 at 1:27 PM, Steven D'Aprano
 wrote:

But regardless of how fast your path-finder algorithm might become, you're
unlikely to be satisfied with a solution that travels around in a circle
from A to B a million times then shoots off straight to Z without passing
through any of the other cities.


On the flip side, that might be the best salesman your company has
ever known, if those three cities have the most customers!

ChrisA
wondering why nobody cares about the customers in TSP discussions


Or, for that matter, ISP customers who don't live in an urban area. :-)

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


Re: Blog "about python 3"

2014-01-04 Thread Steven D'Aprano
[email protected] wrote:

> The very interesting aspect in the way you are holding
> unicodes (strings). By comparing Python 2 with Python 3.3,
> you are comparing utf-8 with the the internal "representation"
> of Python 3.3 (the flexible string represenation).

This is incorrect. Python 2 has never used UTF-8 internally for Unicode
strings. In narrow builds, it uses UTF-16, but makes no allowance for
surrogate pairs in strings. In wide builds, it uses UTF-32.

Other implementations, such as Jython or IronPython, may do something else.


-- 
Steven

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


Re: Blog "about python 3"

2014-01-04 Thread Chris Angelico
On Sun, Jan 5, 2014 at 1:41 PM, Steven D'Aprano
 wrote:
> [email protected] wrote:
>
>> The very interesting aspect in the way you are holding
>> unicodes (strings). By comparing Python 2 with Python 3.3,
>> you are comparing utf-8 with the the internal "representation"
>> of Python 3.3 (the flexible string represenation).
>
> This is incorrect. Python 2 has never used UTF-8 internally for Unicode
> strings. In narrow builds, it uses UTF-16, but makes no allowance for
> surrogate pairs in strings. In wide builds, it uses UTF-32.

That's for Python's unicode type. What Robin said was that they were
using either a byte string ("str") with UTF-8 data, or a Unicode
string ("unicode") with character data. So jmf was right, except that
it's not specifically to do with Py2 vs Py3.3.

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


Re: Blog "about python 3"

2014-01-04 Thread Roy Smith
I wrote: 
> > I realize I'm taking this statement out of context, but yes, sometimes
> > fast is more important than correct.

In article <[email protected]>,
 Steven D'Aprano  wrote:
> Fast is never more important than correct.

Sure it is.

Let's imagine you're building a system which sorts packages for 
delivery.  You sort 1 million packages every night and put them on 
trucks going out for final delivery.

Some assumptions:

Every second I can cut from the sort time saves me $0.01.

If I mis-sort a package, it goes out on the wrong truck, doesn't get 
discovered until the end of the day, and ends up costing me $5 
(including not just the direct cost of redelivering it, but also 
factoring in ill will and having to make the occasional refund for not 
meeting the promised delivery time).

I've got a new sorting algorithm which is guaranteed to cut 10 seconds 
off the sorting time (i.e. $0.10 per package).  The problem is, it makes 
a mistake 1% of the time.

Let's see:

1 million packages x $0.10 = $100,000 saved per day because I sort them 
faster.  10,000 of them will go to the wrong place, and that will cost 
me $50,000 per day.  By going fast and making mistakes once in a while, 
I increase my profit by $50,000 per day.

The numbers above are fabricated, but I'm sure UPS, FexEx, and all the 
other package delivery companies are doing these sorts of analyses every 
day.  I watch the UPS guy come to my house.  He gets out of his truck, 
walks to my front door, rings the bell, waits approximately 5 
microseconds, leaves the package on the porch, and goes back to his 
truck.  I'm sure UPS has figured out that the amortized cost of the 
occasional stolen or lost package is less than the cost for the delivery 
guy to wait for me to come to the front door and sign for the delivery.

Looking at another problem domain, let's say you're a contestant on 
Jeopardy.  If you listen to the entire clue and spend 3 seconds making 
sure you know the correct answer before hitting the buzzer, it doesn't 
matter if you're right or wrong.  Somebody else beat you to the buzzer, 
2.5 seconds ago.

Or, let's take an example from sports.  I'm standing at home plate 
holding a bat.  60 feet away from me, the pitcher is about to throw a 
baseball towards me at darn close to 100 MPH (insert words like "bowl" 
and "wicket" as geographically appropriate).  400 ms later, the ball is 
going to be in the catcher's glove if you don't hit it.  If you have an 
absolutely perfect algorithm to determining if it's a ball or a strike, 
which takes 500 ms to run, you're going back to the minor leagues.  If 
you have a 300 ms algorithm which is right 75% of the time, you're 
heading to the hall of fame.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Suggest an open-source log analyser?

2014-01-04 Thread Alec Taylor
Because I'm thinking that something with a much less expressive query
interface would serve me better in the long run... e.g.: Redis or
maybe Hadoop

On Sat, Jan 4, 2014 at 5:35 PM, Walter Hurry  wrote:
> On Thu, 02 Jan 2014 16:40:19 +1100, Alec Taylor wrote:
>
>> I use the Python logger class; with the example syntax of:
>> Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
>>
>> Can of course easily use e.g.: a JSON syntax here instead.
>>
>> Are there any open-source log viewers (e.g.: with a web-interface)
>> that you'd recommend; for drilling down into my logs?
>>
> If you want to do in-depth analysis, why not just stick it into an SQL
> database; e.g. SQLite or Postgres?
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Using multiple ORMs? - And SQLalchemy vs Pony vs Peewee vs stdnet vs …

2014-01-04 Thread Alec Taylor
Investigating possible using multiple ORMs in my project.

Toy project, want to make it as generic as humanly possible; whilst
still exposing abstract pythonic interfaces.

E.g.: support most number of backends, including SQL ones like:
Postgres, SQLite, MySQL, … and NoSQL ones such as Redis (using
python-stdnet).

One way of doing this is to write generic Python libraries; with
different models, insert and query lines for each of the backend ORMs.

What are your thoughts on this?

Additionally, there are a variety of new ORMs popping up, what are
your thoughts on them; and is there something other than the 4
mentioned in the subject which I should look into?

Thanks for all suggestions,

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


Re: Blog "about python 3"

2014-01-04 Thread Rustom Mody
On Sun, Jan 5, 2014 at 8:50 AM, Roy Smith  wrote:
> I wrote:
>> > I realize I'm taking this statement out of context, but yes, sometimes
>> > fast is more important than correct.
>
> In article <[email protected]>,
>  Steven D'Aprano  wrote:
>> Fast is never more important than correct.
>
> Sure it is.
>
> Let's imagine you're building a system which sorts packages for
> delivery.  You sort 1 million packages every night and put them on
> trucks going out for final delivery.
>
> Some assumptions:
>
> Every second I can cut from the sort time saves me $0.01.
>
> If I mis-sort a package, it goes out on the wrong truck, doesn't get
> discovered until the end of the day, and ends up costing me $5
> (including not just the direct cost of redelivering it, but also
> factoring in ill will and having to make the occasional refund for not
> meeting the promised delivery time).
>
> I've got a new sorting algorithm which is guaranteed to cut 10 seconds
> off the sorting time (i.e. $0.10 per package).  The problem is, it makes
> a mistake 1% of the time.
>
> Let's see:
>
> 1 million packages x $0.10 = $100,000 saved per day because I sort them
> faster.  10,000 of them will go to the wrong place, and that will cost
> me $50,000 per day.  By going fast and making mistakes once in a while,
> I increase my profit by $50,000 per day.
>
> The numbers above are fabricated, but I'm sure UPS, FexEx, and all the
> other package delivery companies are doing these sorts of analyses every
> day.  I watch the UPS guy come to my house.  He gets out of his truck,
> walks to my front door, rings the bell, waits approximately 5
> microseconds, leaves the package on the porch, and goes back to his
> truck.  I'm sure UPS has figured out that the amortized cost of the
> occasional stolen or lost package is less than the cost for the delivery
> guy to wait for me to come to the front door and sign for the delivery.
>
> Looking at another problem domain, let's say you're a contestant on
> Jeopardy.  If you listen to the entire clue and spend 3 seconds making
> sure you know the correct answer before hitting the buzzer, it doesn't
> matter if you're right or wrong.  Somebody else beat you to the buzzer,
> 2.5 seconds ago.
>
> Or, let's take an example from sports.  I'm standing at home plate
> holding a bat.  60 feet away from me, the pitcher is about to throw a
> baseball towards me at darn close to 100 MPH (insert words like "bowl"
> and "wicket" as geographically appropriate).  400 ms later, the ball is
> going to be in the catcher's glove if you don't hit it.  If you have an
> absolutely perfect algorithm to determining if it's a ball or a strike,
> which takes 500 ms to run, you're going back to the minor leagues.  If
> you have a 300 ms algorithm which is right 75% of the time, you're
> heading to the hall of fame.


Neat examples -- thanks
Only minor quibble isnt $5 cost of mis-sorting a gross underestimate?

I am reminded of a passage of Dijkstra in Discipline of Programming --
something to this effect

He laments the fact that hardware engineers were not including
overflow checks in machine ALUs.
He explained as follows:
If a test is moderately balanced (statistically speaking) a programmer
will not mind writing an if statement

If however the test is very skew -- say if 99% times, else 1% -- he
will tend to skimp on the test, producing 'buggy' code [EWD would
never use the bad b word or course]

The cost equation for hardware is very different -- once the
investment in the silicon is done with -- fixed cost albeit high --
there is no variable cost to executing that circuitry once or a
zillion times

Moral of Story: Intel should take up FSR
[Ducks and runs for cover]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Blog "about python 3"

2014-01-04 Thread Roy Smith
In article ,
 Rustom Mody  wrote:

> On Sun, Jan 5, 2014 at 8:50 AM, Roy Smith  wrote:
> > I wrote:
> >> > I realize I'm taking this statement out of context, but yes, sometimes
> >> > fast is more important than correct.
> >
> > In article <[email protected]>,
> >  Steven D'Aprano  wrote:
> >> Fast is never more important than correct.
> >
> > Sure it is.
> >
> > Let's imagine you're building a system which sorts packages for
> > delivery.  You sort 1 million packages every night and put them on
> > trucks going out for final delivery.
> >
> > Some assumptions:
> >
> > Every second I can cut from the sort time saves me $0.01.
> >
> > If I mis-sort a package, it goes out on the wrong truck, doesn't get
> > discovered until the end of the day, and ends up costing me $5
> > (including not just the direct cost of redelivering it, but also
> > factoring in ill will and having to make the occasional refund for not
> > meeting the promised delivery time).
> >
> > I've got a new sorting algorithm which is guaranteed to cut 10 seconds
> > off the sorting time (i.e. $0.10 per package).  The problem is, it makes
> > a mistake 1% of the time.
> >
> > Let's see:
> >
> > 1 million packages x $0.10 = $100,000 saved per day because I sort them
> > faster.  10,000 of them will go to the wrong place, and that will cost
> > me $50,000 per day.  By going fast and making mistakes once in a while,
> > I increase my profit by $50,000 per day.
> >
> > The numbers above are fabricated, but I'm sure UPS, FexEx, and all the
> > other package delivery companies are doing these sorts of analyses every
> > day.  I watch the UPS guy come to my house.  He gets out of his truck,
> > walks to my front door, rings the bell, waits approximately 5
> > microseconds, leaves the package on the porch, and goes back to his
> > truck.  I'm sure UPS has figured out that the amortized cost of the
> > occasional stolen or lost package is less than the cost for the delivery
> > guy to wait for me to come to the front door and sign for the delivery.
> >
> > Looking at another problem domain, let's say you're a contestant on
> > Jeopardy.  If you listen to the entire clue and spend 3 seconds making
> > sure you know the correct answer before hitting the buzzer, it doesn't
> > matter if you're right or wrong.  Somebody else beat you to the buzzer,
> > 2.5 seconds ago.
> >
> > Or, let's take an example from sports.  I'm standing at home plate
> > holding a bat.  60 feet away from me, the pitcher is about to throw a
> > baseball towards me at darn close to 100 MPH (insert words like "bowl"
> > and "wicket" as geographically appropriate).  400 ms later, the ball is
> > going to be in the catcher's glove if you don't hit it.  If you have an
> > absolutely perfect algorithm to determining if it's a ball or a strike,
> > which takes 500 ms to run, you're going back to the minor leagues.  If
> > you have a 300 ms algorithm which is right 75% of the time, you're
> > heading to the hall of fame.
> 
> 
> Neat examples -- thanks
> Only minor quibble isnt $5 cost of mis-sorting a gross underestimate?

I have no idea.  Like I said, the numbers are all fabricated.

I do have a friend who used to work for UPS.  He told me lots of UPS 
efficiency stories.  One of them had to do with mis-routed packages.  
IIRC, the process for dealing with a mis-routed package was to NOT waste 
any time trying to figure out why it was mis-routed.  It was just thrown 
back into the input hopper to go through the whole system again.  The 
sorting software kept track of how many times it had sorted a particular 
package.  Only after N attempts (where N was something like 3), was it 
kicked out of the automated process for human intervention.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Blog "about python 3"

2014-01-04 Thread Steven D'Aprano
Roy Smith wrote:

> I wrote:
>> > I realize I'm taking this statement out of context, but yes, sometimes
>> > fast is more important than correct.
> 
> In article <[email protected]>,
>  Steven D'Aprano  wrote:
>> Fast is never more important than correct.
> 
> Sure it is.

Sure it isn't. I think you stopped reading my post too early.

None of your examples contradict what I am saying. They all involve exactly
the same sort of compromise regarding "correctness" that I'm talking about,
where you loosen what counts as "correct" for the purpose of getting extra
speed. So, for example:

> Let's imagine you're building a system which sorts packages for
> delivery.  You sort 1 million packages every night and put them on
> trucks going out for final delivery.

What's your requirement, i.e. what counts as "correct" for the delivery
algorithm being used? Is it that every parcel is delivered to the specified
delivery address the first time? No it is not. What counts as "correct" for
the delivery algorithm is something on the lines of "No less than 95% of
parcels will be sorted correctly and delivered directly; no more than 5%
may be mis-sorted at most three times" (or some similar requirement).

It may even been that the requirements are even looser, e.g.:

"No more than 1% of parcels will be lost/damaged/stolen/destroyed"

in which case they don't care unless a particular driver loses or destroys
more than 1% of his deliveries. But if it turns out that Fred is dumping
every single one of his parcels straight into the river, the fact that he
can make thirty deliveries in the time it takes other drivers to make one
will not save his job. "But it's much faster to dump the parcels in the
river" does not matter. What matters is that the deliveries are made within
the bounds of allowable time and loss.

Things get interesting when the people setting the requirements and the
people responsible for meeting those requirements aren't able to agree.
Then you have customers who complain that the software is buggy, and
developers who complain that the customer requirements are impossible to
provide. Sometimes they're both right.


> Looking at another problem domain, let's say you're a contestant on
> Jeopardy.  If you listen to the entire clue and spend 3 seconds making
> sure you know the correct answer before hitting the buzzer, it doesn't
> matter if you're right or wrong.  Somebody else beat you to the buzzer,
> 2.5 seconds ago.

I've heard of Jeopardy, but never seen it. But I know about game shows, and
in this case, what you care about is *winning the game*, not answering the
questions correctly. Answering the questions correctly is only a means to
the end, which is "Win". If the rules allow it, your best strategy might
even be to give wrong answers, every time!

(It's not quite a game show, but the British quiz show QI is almost like
that. The rules, if there are any, encourage *interesting* answers over
correct answers. Occasionally that leads to panelists telling what can best
be described as utter porkies[1].)

If Jeopardy does not penalise wrong answers, the "best" strategy might be to
jump in with an answer as quickly as possible, without caring too much
about whether it is the right answer. But if Jeopardy penalises mistakes,
then the "best" strategy might be to take as much time as you can to answer
the question, and hope for others to make mistakes. That's often the
strategy in Test cricket: play defensively, and wait for the opposition to
make a mistake.


> Or, let's take an example from sports.  I'm standing at home plate
> holding a bat.  60 feet away from me, the pitcher is about to throw a
> baseball towards me at darn close to 100 MPH (insert words like "bowl"
> and "wicket" as geographically appropriate).  400 ms later, the ball is
> going to be in the catcher's glove if you don't hit it.  If you have an
> absolutely perfect algorithm to determining if it's a ball or a strike,
> which takes 500 ms to run, you're going back to the minor leagues.  If
> you have a 300 ms algorithm which is right 75% of the time, you're
> heading to the hall of fame.

And if you catch the ball, stick it in your pocket and race through all the
bases, what's that? It's almost certainly faster than trying to play by the
rules. If speed is all that matters, that's what people would do. But it
isn't -- the "correct" strategy depends on many different factors, one of
which is that you have a de facto time limit on deciding whether to swing
or let the ball through.

Your baseball example is no different from the example I gave before. "Find
the optimal path for the Travelling Salesman Problem in a week's time",
versus "Find a close to optimal path in three minutes" is conceptually the
same problem, with the same solution: an imperfect answer *now* can be
better than a perfect answer *later*.




[1] Porkies, or "pork pies", from Cockney rhyming slang.

-- 
Steven

-- 
https://mail.python.org/mailm

Re: Blog "about python 3"

2014-01-04 Thread Chris Angelico
On Sun, Jan 5, 2014 at 2:20 PM, Roy Smith  wrote:
> I've got a new sorting algorithm which is guaranteed to cut 10 seconds
> off the sorting time (i.e. $0.10 per package).  The problem is, it makes
> a mistake 1% of the time.

That's a valid line of argument in big business, these days, because
we've been conditioned to accept low quality. But there are places
where quality trumps all, and we're happy to pay for that. Allow me to
expound two examples.

1) Amazon

http://www.amazon.com/exec/obidos/ASIN/1782010165/evertype-20

I bought this book a while ago. It's about the size of a typical
paperback. It arrived in a box too large for it on every dimension,
with absolutely no packaging. I complained. Clearly their algorithm
was: "Most stuff will get there in good enough shape, so people can't
be bothered complaining. And when they do complain, it's cheaper to
ship them another for free than to debate with them on chat." Because
that's what they did. Fortunately I bought the book for myself, not
for a gift, because the *replacement* arrived in another box of the
same size, with ... one little sausage for protection. That saved it
in one dimension out of three, so it arrived only slightly
used-looking instead of very used-looking. And this a brand new book.
When I complained the second time, I was basically told "any
replacement we ship you will be exactly the same". Thanks.

2) Bad Monkey Productions

http://kck.st/1bgG8Pl

The cheapest the book itself will be is $60, and the limited edition
early ones are more (I'm getting the gold level book, $200 for one of
the first 25 books, with special sauce). The people producing this are
absolutely committed to quality, as are the nearly 800 backers. If
this project is delayed slightly in order to ensure that we get
something fully awesome, I don't think there will be complaints. This
promises to be a beautiful book that'll be treasured for generations,
so quality's far FAR more important than the exact delivery date.

I don't think we'll ever see type #2 become universal, for the same
reason that people buy cheap Chinese imports in the supermarket rather
than something that costs five times as much from a specialist. The
expensive one might be better, but why bother? When the cheap one
breaks, you just get another. The expensive one might fail too, so why
take that risk?

But it's always a tradeoff, and there'll always be a few companies
around who offer the more expensive product. (We have a really high
quality cheese slicer. It's still the best I've seen, after something
like 20 years of usage.) Fast or right? It'd have to be really
*really* fast to justify not being right, unless the lack of rightness
is less than measurable (like representing time in nanoseconds -
anything smaller than that is unlikely to be measurable on most
computers).

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


print range in python3.3

2014-01-04 Thread luofeiyu
>>> range(1,10)
range(1, 10)
>>> print(range(1,10))
range(1, 10)

how can i get 1,2,3,4,5,6,7,8,9 in python3.3 ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print range in python3.3

2014-01-04 Thread Chris Angelico
On Sun, Jan 5, 2014 at 6:38 PM, luofeiyu  wrote:
 range(1,10)
> range(1, 10)
 print(range(1,10))
> range(1, 10)
>
> how can i get 1,2,3,4,5,6,7,8,9 in python3.3 ?

Are you looking for a list? That's what Python 2 returned. In Python
3, you can get that like this:

>>> list(range(1,10))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

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