Re: class factory question

2013-06-26 Thread Joshua Landau
On 26 June 2013 15:46, Peter Otten __pete...@web.de wrote:
 The clean way to
 cope with the situation is to use a dict:

 classnames = [Vspace, ...]
 classes = {name: type(name, ...) for name in classnames}

 Then you can access the Vspace class with

 classes[Vspace]

 If that is inconvenient for your usecase you can alternatively update the
 global (module) namespace:

 globals().update((name, type(name, ...) for name in classnames)

 For example:

 class A(object): pass
 ...
 globals().update((n, type(n, (A,), {})) for n in [Beta, Gamma])
 Beta
 class '__main__.Beta'
 issubclass(Beta, A)
 True

I would say if a dict isn't good, there are still some cases where you
might not want to use globals.

I _might_ do:

import sys
from types import ModuleType

# As before
newclasses = ['Vspace', 'Boldpath', and so on, and yes, these all
become variables]
little_classes = {name: type(name, (int,), {}) for name in newclasses}

# Make a module
module_for_little_classes = ModuleType(module_for_little_classes,
All the things)
module_for_little_classes.__dict__.update(little_classes)

# Hack it in there!
sys.modules[module_for_little_classes] = module_for_little_classes

# Now we can undo all
import module_for_little_classes as mlc
mlc.Vspace
mlc.Boldpath
...

# And undo all our hard work avoiding globals():
from module_for_little_classes import *
Vspace
Boldpath


So, why avoid globals()?
1) Linters don't like globals()
2) Urm... it's ugly?
3) Ur...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Limit Lines of Output

2013-06-26 Thread Joshua Landau
On 25 June 2013 22:48, Gene Heskett ghesk...@wdtv.com wrote:
 On Tuesday 25 June 2013 17:47:22 Joshua Landau did opine:

I did not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Limit Lines of Output

2013-06-26 Thread Joshua Landau
On 26 June 2013 17:46, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Wed, 26 Jun 2013 16:24:56 +0100, Joshua Landau wrote:

 On 25 June 2013 22:48, Gene Heskett ghesk...@wdtv.com wrote:
 On Tuesday 25 June 2013 17:47:22 Joshua Landau did opine:

 I did not.

 Unless there are two people called Joshua Landau with email address
 joshua.landau...@gmail.com, I'm afraid that you did.

Ah, but as rusi has understood, I did not.

(Although I did not may itself be opining, that was not the quoted text.)

Hey, sometimes I just like being cryptic.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help removing trailing zeros

2013-06-26 Thread Joshua Landau
On 26 June 2013 23:02,  bandcam...@gmail.com wrote:
 Hello, i'm making a calculator and I want to be able to use decimals but I 
 don't like it when it comes out as ex.12.0 when it should be 12. I tried 
 using .rstrip(0.rstrip(.) but that never seemed to work. If anyone has a 
 solution please let me know, all help is greatly appreciated.

 Code:
LOTS 'O CODE

Was that really necessary?

All you needed to give use was print(1.0); why post so much?

Either:
{:g}.format(1.0)

or, if you hate scientific notation:
{:f}.format(1.0).rstrip(.0)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help removing trailing zeros

2013-06-26 Thread Joshua Landau
On 26 June 2013 23:21, PyNoob bandcam...@gmail.com wrote:
 Sorry about that... And thanks for your help, but I don't quite understand.
That's fine, but...

 Would that make it off your example print({:g}.format(1.0))?
I don't understand this sentence.

But, hey, I forgot to check what level you were working at -- there's
little point running ahead of what you know.

Did you try:
print({:g}.format(1.0))
? It works for me. So, yes, that's what you want.

So instead of:
print(The quotient of, A, and, B, is: , Answer)

you want
print(The quotient of, A, and, B, is: , {:g}.format(Answer))

See how I just used {:g}.format as some kind of magic-fixing-power?

Well, why does it work?

[See http://docs.python.org/3/library/stdtypes.html#str.format and the
sub-links for a more full explanation]

Run each of these in an interpreter:

{} {} {} {} {}.format(This, is, a, formatted, string!)

It is really useful: I have {} cows and {}
sheep.format(number_of_cows, number_of_sheep)

It gives me back a formatted {}, which I can
print.format(type(.format()).__name__)

I can also give things indexes: {3} {2} {1} {0}.format(Print,
in, reverse, order)

I can also give things names: {egg} {ham}
{flies}.format(egg=Are, ham=you, flies=there?)

It's not just {:!10}.format(that)

It lets me choose how I want things to be printed: {0:@^6},
{0:~10}, {0:£8}.format(Hi)

And for numbers: {0:e}, {0:.10%}, {0:#.1f}.format(123.456)

So you just want the best formatter; see
[http://docs.python.org/3/library/string.html#format-specification-mini-language]

Your best choice is {:g} which just means general format.

Note that you can also write your prints as so:

print(The quotient of {} and {} is: {:g}.format(A, B, Answer))

Whether you prefer it is your choice.


--


In regards to .rstrip: It will only work on strings; so you need to
convert like so:
str(1.0).rstrip(0).rstrip(.)

And note that:
1) My .rstrip(0.) was wrong and foolish (try str(10).rstrip(0.))
2) This needs the string to be reliably formatted in this style:
{:#f} *and* requires it to be a float.

So really, you'd need:

{:#f}.format(float(number)).rstrip(0).rstrip(.)

Which is ugly, but I guess it works.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class factory question

2013-06-26 Thread Joshua Landau
On 26 June 2013 16:40, Peter Otten __pete...@web.de wrote:
 Joshua Landau wrote:

 I would say if a dict isn't good, there are still some cases where you
 might not want to use globals.

 I _might_ do:

 # Make a module
 module_for_little_classes = ModuleType(module_for_little_classes,
 All the things)
 module_for_little_classes.__dict__.update(little_classes)

 Hm, from within module_for_little_classes that is globals(). To illustrate:

 import __main__ as main
 globals() is main.__dict__
 True

Yes, that's true - but the point wasn't not to use globals the
function, but not to use *this* global scope.

 Also, I'd spell module.__dict__ vars(module).

Again, good catch. Definitely that.

 That said I agree that it's a good idea to use a dedicated module (not
 necessarily created on the fly) for those dynamically generated classes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this PEP-able? fwhile

2013-06-25 Thread Joshua Landau
On 25 June 2013 00:13, Tim Chase python.l...@tim.thechases.com wrote:
 On 2013-06-24 23:39, Fábio Santos wrote:
 On 24 Jun 2013 23:35, Tim Chase wrote:
  On 2013-06-25 07:38, Chris Angelico wrote:
   Python has no issues with breaking out of loops, and even has
   syntax specifically to complement it (the 'else:' clause). Use
   break/continue when appropriate.
 
  from minor_gripes import breaking_out_of_nested_loops_to_top_level

 for x, y in itertools.product(range(width), range(height)):

 This works nicely for certain use cases, but if there's additional
 processing that needs to be done in the outer loops, it starts to get
 hairy.  As Ian Kelly mentions, I could really dig a labeled
 break/continue in Python (it's one of the few ideas I like that Java
 made pretty popular; though I can't say I particularly care for
 Java's implementation).  I'd love to see something like a decorator
 where you could do things like the following pseudocode:

   @toplevel
   for i in range(height):
 for j in range(width):
   for component in data[i,j]:
 if condition:
   continue toplevel
 elif other_condition:
   break toplevel
 else:
   other processing

 I'm not sure such a feature would ever arrive, but it would make it
 easier than the current recommendation which is usually to either (1)
 make inner loops into functions from which you can return; or (2)
 raise a custom exception and then catch it in the outer loop.

Guido says no; supposedly you can always just use a function. I don't
agree, but I'm not Guido.

Anyhoo, I prefer:

for i in range(height) as toplevel:
for j in range(width):
break from toplevel

Which reads like pure Python gold.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this PEP-able? fwhile

2013-06-25 Thread Joshua Landau
On 24 June 2013 23:50, Chris Angelico ros...@gmail.com wrote:

 In more free-form languages, I implement this by simply omitting a line-break:
...
 Python could afford to lose a little rigidity here rather than gain
 actual new syntax:

 for i in range(10): if i%3:
 print(i)

 And there you are, the for-if filtered iteration model, just by
 relaxing one rule.

Maybe rather:

for i in range(10); if i%3:
print(i)


One of the awesomer things about Coffeescript is:

decorator = (f) - (args...) - f(args[0])

Which lets you do stuff like:

recursive = do - r = (n) -
if n  0 then n*r(n-1) else 1

instead of:

def recursive_gen():
def recursive(n):
return n*recursive(n-1) if n  0 else 1
return recursive
recursive = recursive_gen()

Of course, Coffeescript has its own quirks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Limit Lines of Output

2013-06-25 Thread Joshua Landau
On 25 June 2013 21:22, Bryan Britten britten.br...@gmail.com wrote:
 Ah, I always forget to mention my OS on these forums. I'm running Windows.

Supposedly, Windows has more
[http://superuser.com/questions/426226/less-or-more-in-windows],

For Linux+less; this works:

from subprocess import Popen, PIPE
less = Popen(less, stdin=PIPE)
less.stdin.write(b\n.join(This is line number
{}.format(i).encode(UTF-8) for i in range(1000)))
less.wait()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)

2013-06-24 Thread Joshua Landau
Here's a little test to make sure you understand (this is one of the
most confusing parts of Python's closures in my opinion):

foo = I'm foo!

def working():
print(foo)

def broken():
print(foo)

if False: # There's no way this could cause a problem!
foo = This will *never* happen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)

2013-06-24 Thread Joshua Landau
On 24 June 2013 21:12, John Gordon gor...@panix.com wrote:
 Since you're new to programming, this might be a bit tricky to explain,
 but I'll do my best. :-)

 The problem is that change() isn't being executed here; instead it's being
 executed from within root.mainloop(), whenever the user presses button-1.

 And within root.mainloop(), there is no variable called isWhite.

Sorry, but I don't think you're right. Functions carry their
contexts around with them, so that shouldn't matter

(See Peter and Antoon's comments for explanation of what I think it is)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this PEP-able? fwhile

2013-06-24 Thread Joshua Landau
On 24 June 2013 20:52,  jim...@aol.com wrote:
 Syntax:

 fwhile X in ListY and conditionZ:

 The following would actually exactly as:  for X in ListY:

 fwhile X in ListY and True:

 fwhile would act much like 'for', but would stop if the condition after the
 'and' is no longer True.

 The motivation is to be able to make use of all the great aspects of the
 python 'for' (no indexing or explict
 end condition check, etc.) and at the same time avoiding a 'break' from the
 'for'.

There is one good reason not to use breaks: itertools.
I often prefer a for-over-a-properly-constrained-iterable to a
for-with-a-break, but there's no real reason to ever prefer a while.

That said, why add this to the syntax when there's already
functionality that gives you what you want? Just use
itertools.takewhile as Ian Kelly says.

 (NOTE:  Many people are being taught to avoid 'break' and 'continue' at all
 costs, so they instead convert
 the clean 'for' into a less-clean 'while'.  Or they just let the 'for' run
 out.  You can argue against this teaching
 (at least for Python) but that doesn't mean it's not prevalent and
 prevailing.)

We shouldn't make a language around people are taught the language
badly - let us accommodate for their bad practices!

 [People who avoid the 'break' by functionalizing an inner portion of the
 loop are just kidding themselves and making
 their own code worse, IMO.]

 I'm not super familiar with CPython, but I'm pretty sure I could get this up
 and working without too much effort.
 The mandatory 'and' makes sense because 'or' would hold the end value valid
 (weird) and not accomplish much.
 The condition itself could of course have multiple parts to it, including
 'or's.

 It's possible the name 'fwhile' is not optimal, but that shouldn't affect
 the overall merit/non-merit of the concept.

Possible? It's more than just possible, *wink*.

 Comments and Questions welcome.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)

2013-06-24 Thread Joshua Landau
On 24 June 2013 21:19,  pablobarhamal...@gmail.com wrote:
 Thank's to you all!

 Setting isWhite as global worked fine.
 I'll probably be back soon with another silly question, see you then :)

By the way, it's normally bad to use globals like this. When you're
learning it's something you just do, though; it's fine for now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: n00b question on spacing

2013-06-22 Thread Joshua Landau
On 21 June 2013 23:26, Gary Herron gher...@digipen.edu wrote:
 On 06/21/2013 02:17 PM, Yves S. Garret wrote:
 I have the following line of code:
 log.msg(Item wrote to MongoDB database %s/%s %(settings['MONGODB_DB'],
 settings['MONGODB_COLLECTION']), level=log.DEBUG, spider=spider)
...
 I was thinking of splitting it up like so:
 log.msg(Item wrote to MongoDB database %s/%s
   %(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']),
   level=log.DEBUG, spider=spider)

 This is how I'd do it:  (And it's *FAR* clearer -- You win no points for
 clarity by having it all in one statement.)

 fmt  = Item wrote to MongoDB database %s/%s
 msg = fmt % (settings['MONGODB_DB'],
  settings['MONGODB_COLLECTION'])
 log.msg(msg, level=log.DEBUG, spider=spider)

Hear, Hear.

But really, you should be using .format by now :P

My favourite way would be along the lines of:

message = Item wrote to MongoDB database 
message += {0[MONGODB_DB]}/{0[MONGODB_COLLECTION]}.format(settings)
log.msg(message, level=log.DEBUG, spider=spider)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: n00b question on spacing

2013-06-22 Thread Joshua Landau
On 22 June 2013 14:36, Joshua Landau joshua.landau...@gmail.com wrote:
 message = Item wrote to MongoDB database 

Pedant's note:
Item *written* to MongoDB database
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: n00b question on spacing

2013-06-22 Thread Joshua Landau
On 22 June 2013 16:24, Rick Johnson rantingrickjohn...@gmail.com wrote:
 On Saturday, June 22, 2013 8:36:43 AM UTC-5, Joshua Landau wrote:
 message = Item wrote to MongoDB database 
 message += {0[MONGODB_DB]}/{0[MONGODB_COLLECTION]}.format(settings)
 log.msg(message, level=log.DEBUG, spider=spider)

 If you're going to whore out parts of the string to
 variables i would suggest going for the gold and actually
 make it readable.

Erm, as you wish.

 Plus, your use of the format  syntax is
 incorrect.

Wut?

   _arg1 = settings['MONGODB_DB']
   _arg2 = settings['MONGODB_COLLECTION']
   _fmtstr = Item wrote to MongoDB database {0}, {1}
   msg = _fmtstr.format(_arg1, _arg2)
   log.msg(msg, level=log.DEBUG, spider=spider)

 If you want readability, now you got it.

If you say so.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: n00b question on spacing

2013-06-22 Thread Joshua Landau
On 22 June 2013 14:36, Joshua Landau joshua.landau...@gmail.com wrote:
 My favourite way would be along the lines of:

 message = Item wrote to MongoDB database 
 message += {0[MONGODB_DB]}/{0[MONGODB_COLLECTION]}.format(settings)
 log.msg(message, level=log.DEBUG, spider=spider)

To make a habit of replying to myself, I thought I'd point out I wrote
it this way mostly because I have no idea how big settings is.

If it's not large and only contains keys that are valid identifiers,
it'd be more readable to write:

message = Item wrote to MongoDB database 
message += {MONGODB_DB}/{MONGODB_COLLECTION}.format(**settings)
log.msg(message, level=log.DEBUG, spider=spider)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: n00b question on spacing

2013-06-22 Thread Joshua Landau
On 22 June 2013 16:55, Rick Johnson rantingrickjohn...@gmail.com wrote:
 On Saturday, June 22, 2013 10:40:24 AM UTC-5, Joshua Landau wrote:
  Plus, your use of the format syntax is incorrect.
 Wut?

 Well what i mean exactly is not that it's illegal, i just
 find the use of the getattr sugar, from WITHIN the format
 string, to be excessively noisy.

Sure...
So in other words you realised you were wrong but you're too scared to
admit it. Eh? That's it, isn't it! You just don't want to loosen your
proud persona :P.

 In short, i don't care to know WHAT is being injected into
 the format string, i simply need to know WHERE it is being
 injected.

No, I agree. It's never about what you're doing; it's where you
are when you do it.

 It's about abstractions. It's about not violating the
 fundamentals of templates.

Mmhmm, I too treasure these 'fundamentals'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: n00b question on spacing

2013-06-22 Thread Joshua Landau
On 22 June 2013 18:28, Alister alister.w...@ntlworld.com wrote:
 On Sat, 22 Jun 2013 17:11:00 +0100, Joshua Landau wrote:

 On 22 June 2013 16:55, Rick Johnson rantingrickjohn...@gmail.com
 wrote:
 On Saturday, June 22, 2013 10:40:24 AM UTC-5, Joshua Landau wrote:
  Plus, your use of the format syntax is incorrect.
 Wut?

 Well what i mean exactly is not that it's illegal, i just find the use
 of the getattr sugar, from WITHIN the format string, to be
 excessively noisy.

 Sure...
 So in other words you realised you were wrong but you're too scared to
 admit it. Eh? That's it, isn't it! You just don't want to loosen your
 proud persona :P.

 In this argument I tend to find myself siding with Rick.
 Considering his general reputation in this forum am I missing something
 or do I need help? ;-)

I wasn't mocking the preference against it, but rather that that was
completely not what he said originally. One cannot let slip when the
mighty Rick misses his mark.

That said, yes, it is quite a noisy construct. I still prefer it to:

message = Item wrote to MongoDB database {}/{}
message = message.format(
settings['MONGODB_DB'],
settings['MONGODB_COLLECTION']
)
log.msg(message, level=log.DEBUG, spider=spider)

Because this feels undescriptive - the first and second lines feel
detached. Instead of Rick's hilarious unpacking, you could always do:

message = Item wrote to MongoDB database {database}/{collection}
message = message.format(
database=settings['MONGODB_DB'],
collection=settings['MONGODB_COLLECTION']
)
log.msg(message, level=log.DEBUG, spider=spider)

Which is probably as good, if longer. You'll see the real problem is
that MONDODB_DB and MONGODB_COLLECTION are awful names; would you
really have so detested

message = Item wrote to MongoDB database 
message += 
{settings[database]}/{settings[collection]}.format(settings=settings)
log.msg(message, level=log.DEBUG, spider=spider)

or even, now,

message = Item wrote to MongoDB database
{settings[database]}/{settings[collection]}
message = message.format(settings=settings)
log.msg(message, level=log.DEBUG, spider=spider)

?

I think those options are quite nice, á mon avis. I could even write a
wrapper (oh noes!):

# Shortened for EMail
class SettingsWrapper:
def uglify_key(self, key): return key if key.startswith(MONGODB)
else MONGODB_ + key.upper()
def __init__(self, settingsdict): self.wrapped = settingsdict
def __len__(self): return self.wrapped.__len__()
def __iter__(self): return self.wrapped.__iter__()
def __getitem__(self, key): return self.wrapped[self.uglify_key(key)]
def __contains__(self, key): return self.uglify_key(key) in self.wrapped
def __setitem__(self, key, value):
self.wrapped[self.uglify_key(key)] = value
def __delitem__(self, key, value): del self.wrapped[self.uglify_key(key)]

settings = SettingsWrapper(settings)

message = Item wrote to MongoDB database {settings[db]}/{settings[collection]}
message = message.format(settings=settings)
log.msg(message, level=log.DEBUG, spider=spider)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with the for loop syntax

2013-06-20 Thread Joshua Landau
On 20 June 2013 04:11, Cameron Simpson c...@zip.com.au wrote:
 Also, opening-and-not-closing a set of brackets is almost the only
 way in Python to make this kind of error (syntax at one line, actual
 mistake far before).

 See if your editor has a show-the-matching-bracket mode.
snip
 If you suspect you failed to close a bracket, one approach is to
 go _below_ the syntax error (or right on it) and type a closing
 bracket. Then see where the editor thinks the opening one is.

Thanks for that, that's quite an ingenious technique.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About GIL Questions!

2013-06-20 Thread Joshua Landau
On 20 June 2013 05:13, Thanatos xiao yanxiaopei...@gmail.com wrote:
 Hey everyone!
 Recently I see the python source code, but i still not understand about gil.
 first, why single core quicker multi-core ?

Chris Angelico touched on your other points, but not this as clearly;

Python threads run on one thread because they have to. It is not
because they're faster. Python theoretically would be faster if its
threads could run multicore, but it's really hard to make that work.

See http://pypy.org/tmdonate.html for an example of the acrobatics it
would take to get a propper GIL-free Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Beginner's Doubt

2013-06-19 Thread Joshua Landau
Please be aware, Augusto, that Rick is known to be a bit... OTT. Don't
take him too seriously (but he's not an idiot either).

On 19 June 2013 14:58,  augusto...@gmail.com wrote:
 Hello!
 This is my first post in this group and the reason why I came across here is 
 that, despite my complete lack of knowledge in the programming area, I 
 received an order from my teacher to develop a visually interactive program, 
 until 20th July, so we can participate in a kind of contest.

 My goal is to learn and program it by myself, as good as the time allows me. 
 That said, what I seek here is advice from people who definitively have more 
 experience than me on topics like: is it possible to develop this kind of 
 program in such a short amount of time?

Possible? Yes.
It'll be well'ard to get much done with too limited a knowledge base,
but it should be possible even then.

 What kinds of aspects of Python should I focus on learning? What tutorials 
 and websites are out there that can help me? What kind of already done 
 packages are out there that I can freely use, so I do not need to create all 
 the aspects of the program froms scratch?

Neil Cerutti suggested Tkinter. Choosing a good simple GUI toolkit is
a good idea over Pygame for something like this.
I've used Pygame and I guarantee you it's not the hammer you want.

(I don't know much about GUI's to be honest, though.)

 It would be wise to give an abstract of the program. I made an information 
 flux kind of graphic, but I do not know how to post it in here, so I'll use 
 only words:
STUFF
 Thats basically the whole program. I've been studying Python for a week and 
 half now, through: How to think like a Computer Scientist and Invent with 
 Python and Pygame. I'm still at the very beggining, though, and I can't make 
 much more than make some images appear on a Pygame screen in a menu-like 
 style, with a patterned gap between them. No mouse interactions up to now.

In regards to this, I really would recommend just taking Rick's
suggestion: Tkinter; canvas; menu; etc.


Now, as I'm probably the most new programmer here I'll point out that
I don't agree with Chris when he says that:

 One way or
 another, you will probably spend the next week writing code you throw
 away; if you try to tackle the primary project immediately, you'll
 have to rewrite parts of it as you learn. It's easier to throw away a
 toy Hello world program than hunks of what you thought would be your
 final code.

As a new programmer, you will throw away code whether or not you
practice beforehand. Beware of that. If anything, it's the best thing
you can do*.

Other than that, he's spot on. Personally, I'd start on the big
project sooner rather than later, but not be afraid to dump all the
code every now and again.

*Anecdote time; a friend of mine who learned VB as his first language
wrote as one of his earlier scripts a 2075 line program with no
indentation - I still have a copy of that gem tucked away in a very
dark corner.


Last point; DRY. Look it up and breathe it. People might wonder why
I'm making that big a deal about it (it's not the be-all and end-all
of anything) but as a new programmer most of your random bits of
not-nice-looking code will probably just be a breach of DRY. If you've
written the same thing 5 times you've *probably* done it in a not-too
efficient manner and the real solution will be the next ladder up in
the hierarchy of programming.

As someone new, paying a fair bit of attention to this will probably
make what you learn some important higher-level concepts faster.


Best of luck, I hope I added something helpful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Beginner's Doubt

2013-06-19 Thread Joshua Landau
On 19 June 2013 17:39, Joel Goldstick joel.goldst...@gmail.com wrote:
 What is the subject that this teacher of yours teaches?
 Do you know anyone who has every done any programming?
 Why python?

One of those questions is too easy :P.

But, no, I'd actually point out that Python might *not* be the best
language for the job! *GASP!* *HERETIC* *I'M TELLING!*

If you just want a GUI interface program, I'd recommend JavaScript.
Heck, if you don't mind the compiler troubles I'd use CoffeeScript.

Why?! You scream! Well, it's definitely not the language. The GUI
toolkit, HTML, however, is ace for really small
compatibility-don't-really-matter scripts. A couple old examples from
before I went Python are attached, not to show off the somewhat lame
code but just to point out that even as a new programmer these things
were *concise*. That made them so many billions of times easier.

Beside the Point
Be careful not to mistake the libraries I used for the code I wrote,
too. The amount of code *I* wrote for each numbers very few lines
(just the main two html files).
About half in total was HTML/CSS, so doesn't even count as code. I
wrote these for me, so pretend they're licensed strictly. Anything I
can give away I do, but it's best to check the licences anyway.

Please note that if you don't run these in a modern Chrome/Chromium
browser you'll have a bad time - I never bothered with compatibility.
Also, apologies for snatching the coffeescript.org coffeescript - but
I didn't want to mail a 60KB attachment.

Instructions: Guessing the rules is part of the game. They're both
thinking games, by the way. For Z-Rox clone, the inspiration is from
http://www.kongregate.com/games/evildog/z-rox.
End Beside the Point

How is this relevant to you? Well, JQuery will make what you've
written probably just couple of hundred lines. Forget about 2000!
This isn't relevant if any of:
1) You have to use python
2) You don't want a silly web interface
3) Any other good reason

See http://jqueryui.com/draggable/ for little examples.


Examples.tar.gz
Description: GNU Zip compressed data
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python game

2013-06-19 Thread Joshua Landau
This is prob'ly the freakiest thing I've ever run...

Anyhoo, I recommend that when you post slabs of code to a mailing list
you at least make it runnable for us. We don't have the images. I
fixed it by doing:
| playerImage = pygame.Surface((40, 40))
| bearImage = pygame.Surface((64, 64))
|
| playerImage.fill(pygame.Color(red))
| bearImage.fill(pygame.Color(blue))

I'll not just give you answers, here, but try and make you understand
what you need to do to make your code shiny. I'll answer your
questions on the way, though.

On 19 June 2013 21:18,  jacksonkemp1...@gmail.com wrote:
 I made this game where you move a player over bears, but the bears keep 
 loading over the plaeyer making it hard to see it, also when i move down the 
 player goes down to the right

 here is my code:

 import pygame, sys, random
 from pygame.locals import *
 from threading import Timer

You probably want to split up these lines; all the cool kids do:
| import sys
| import random
| import pygame
|
| from pygame.locals import *
| from threading import Timer

This is just style; you might wonder why people do this but it's
something I've found makes sense in the long run for some reason, and
it's recommended as such.


 #set up pygame
 pygame.init()
 mainClock = pygame.time.Clock()

 #set up the window
 WINDOW_WIDTH = 400
 WINDOW_HEIGHT = 400
 windowSurface = pygame.display.set_mode((WINDOW_WIDTH,
 WINDOW_HEIGHT),0)
 pygame.display.set_caption('Get the Bears')

 #set up color constants
 BLACK = (0,0,0)
 BLUE = (0, 0, 255)

Ah! Pygame has a color module.

For example, instead of:
| windowsurface.fill(BLACK)

it's better to do:
| windowsurface.fill(pygame.Color(black))


 #set winning text
 textFont = pygame.font.SysFont(impact, 60)
 text = textFont.render(YOU WIN!, True, (193, 0, 0))

Just a niggle here; it'd be better to call this win_text or some
other more descriptive name.
It's also better to use under_score_names; they're more readable. It
took me about a year to realise this, but it's true. It's also
recommended.

 #set up the player and bear data structures
 bearCounter = 0
 NEW_BEAR = 40
 BEAR_SIZE = 64

I'll come back to this later.

 playerImage = pygame.image.load('hunter.png')
 bearImage = pygame.image.load('bear.png')

I replaced this with:
| player_image = pygame.Surface((40, 40))
| bear_image = pygame.Surface((64, 64))
|
| player_image.fill(pygame.Color(red))
| bear_image.fill(pygame.Color(blue))

Note that I'm changing things like the naming scheme as I go.

 player = pygame.Rect(300, 100, 40, 40)

Although it's OK to use  pygame.Rect as a player now, it's not a
player and you really shouldn't let this be a habit. It'd be better
to call this player_rect, or some more useful name.

 bears = []
 for i in range(20):
 bears.append(pygame.Rect(random.randint(0, WINDOW_WIDTH - BEAR_SIZE),
  random.randint(0, WINDOW_HEIGHT - BEAR_SIZE),
  BEAR_SIZE, BEAR_SIZE))

Split this up, damnit!
| for i in range(10):
| x = random.randint(0, WINDOW_WIDTH - BEAR_SIZE)
| y = random.randint(0, WINDOW_HEIGHT - BEAR_SIZE)
|
| bears.append((x, y), (BEAR_SIZE, BEAR_SIZE))

See how this way it's more obvious what it all means, there's no silly
line-wrapping *and* it's easier to read.

 #movement variables
 moveLeft = False
 moveRight = False
 moveDown = False
 moveUp = False

 MOVE_SPEED = 15

ER MER GERD

Think about what you're doing here. If I ask you what direction an
object on the screen is going in, do you say:
1) Left, about 15 pixels a frame
2) West at 5 klicks per hour
3) Left=True, Right=False, Up=False, Down=False, Speed=15
?

Well, it's not (3). So let us think about this.

A good classical newbie method, which works for non-newbie stuff too, is just

| directions = {left, right, up, down}
| movement_direction = left

However, it's not the best. In programming terms you'd want variable
speed in *both* directions. My preferred method is:

| velocity = [the_value_of_x, the_value_of_y]

so you'd write above:

| velocity = [0, 0]

See how nice that is? We'll come back to this later.

 #run the game loop
 startGame = True
 while startGame == True:

N! Not you too!

START PERSONAL OPINION, NOT SHARED BY EVERYONE
You have here a (really weird - I'll come to that later) infinite loop.
This is best described like so:

| while True:
| stuff()
| if finished():
| break

That's what break is for, after all.

Even better (I think) you can do:

| while game is running:
| stuff()
| if finished():
| break

which explains what you're doing concisely without changing the
meaning of the code.

A second advantage of this method
END

Plus, if you *insist* on while FLAG, choose a good name. startGame
is wrong, because it's not only running during the start of the game.

You mean:
| while game_running:

 #check for quit
This is a misplaced comment.

 for event in pygame.event.get():
 if event.type == QUIT:
 

Re: Problem with the for loop syntax

2013-06-19 Thread Joshua Landau
On 19 June 2013 23:53, Arturo B a7xrturo...@gmail.com wrote:
 Mmmm

 Ok guys, thank you

 I'm really sure that isn't a weird character, it is a space.

 My Python version is 3.3.2, I've runed this code in Python 2.7.5, but it 
 stills the same.

 I've done what you said but it doesn't work.

 Please Check it again here is better explained:

 http://snipplr.com/view/71581/hangman/

Listen;

1) Post the code in the EMail, not an external link.

2) Don't Top Post.

3) That link doesn't exist. There are so many good hosting sites; why
use one that doesn't work?

4) Give us a minimal example. This should be easy; just remove the
code above and the code below. This is also a valid debugging
technique.

5) Images? Really?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why 'files.py' does not print the filenames into a table format?

2013-06-15 Thread Joshua Landau
On 15 June 2013 20:51, Nick the Gr33k supp...@superhost.gr wrote:
 On 15/6/2013 10:46 μμ, Jarrod Henry wrote:

 Nick, at this point, you need to hire someone to do your work for you.


 The code is completely ready.
 Some detail is missing and its not printing the files as expected.

Look, Nick,

A lot of people are frustrated by you. You should understand that. If
you cannot, you need to step back and consider, or you really are a
troll.

Now, obviously it's not going to get you any help to have half of the
forum angry at you. People have stopped helping, at least in large.
This is fine; people here are volunteers. But you want help.

So, Nick, listen. You need to learn how to ask *smart* questions. If
you do, I *guarantee* that people will respect you a lot more. I'll be
willing to give a bit of time to explain what I mean.

1) What is your problem. Not I want to know why it doesn't print
anything. Here's an example, for some random idea:

 I've written some code to find the first file in a directory which
 is not UTF-8. Lines 40-42 are meant to print out the file found
 to a log (/home/joshua/.logs/log). Unfortunately, although
 there is no error, no file is printed to the log.

2) What have you tried? What debugging have you done? For someone of
your skill level, it's also important to tell us what you think your
code is doing. Example:

 I've tried checking for a failure - when there is no non-UTF-8 file
 in the directory the appropriate error is raised. I think this should
 mean that the else after the for loop would be run, and this
 should run the lines 40-42 above when there *is* a non-UTF-8
 file.

3) If possible, give us an example we can run.

 To make helping easier, I've removed the code that searches the
 directory as I know that works, and instead there's a list of BytesIO
 and StringIO objects that pretend to be them. The bug is still
 there.

Do you see the difference?

 Irrelevant to my question i just noticed weird behavior about my
 pelatologio.py script which can be seen here:

 http://superhost.gr/?show=stats

 The first 3 files are of my doing.
 All the rest are of someone else's that managed to append entries into my
 counters database utilizing this code:

 

 try:
 #find the needed counter for the page URL
 cur.execute('''SELECT ID FROM counters WHERE url = %s''',
 page )
 data = cur.fetchone()#URL is unique, so should only
 be one

 if not data:
 #first time for page; primary key is automatic, hit
 is defaulted
 cur.execute('''INSERT INTO counters (url) VALUES
 (%s)''', page )
 cID = cur.lastrowid#get the primary key
 value of the new record
 ==

 Does someone want to state something?

Sure. Here I go:

What's the question?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pattern Search Regular Expression

2013-06-15 Thread Joshua Landau
On 15 June 2013 11:18, Mark Lawrence breamore...@yahoo.co.uk wrote:
 I tend to reach for string methods rather than an RE so will something like
 this suit you?

 c:\Users\Mark\MyPythontype a.py
 for s in (In the ocean,
   On the ocean,
   By the ocean,
   In this group,
   In this group,
   By the new group):
 print(' '.join(s.split()[1:-1]))


 c:\Users\Mark\MyPythona
 the
 the
 the
 this
 this
 the new

Careful -  .join(s.split()) != s

Eg:
  .join(s\ns.split())
's s'

It's pedantry, but true.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Eval of expr with 'or' and 'and' within

2013-06-14 Thread Joshua Landau
On 14 June 2013 19:37, rusi rustompm...@gmail.com wrote:
 2. The recent responses from Robert Kern are in my view the ideal. In
 summary it runs thus:
 Stupid question no. 6457 from Nikos: ...
 Robert : Look this up link
 Nikos: I dont understand
 Robert: Link explains
 Nikos: I DONTU NDERSTND
 Robert: Link explains (repeated as often as needed)

 When (if) finally Nikos actually reads the link and asks a more
 specific/intelligent question, link can be replaced by more specific
 link'

+1

Please, everyone else, just do this. This will calm the beast, I
assure you, at least somewhat. If you're worried about not being
helpful, don't - this is as much help as ever. It's just it takes
less time, and a *lot* less space.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My son wants me to teach him Python

2013-06-13 Thread Joshua Landau
On 13 June 2013 17:50, Tomasz Rola rto...@ceti.pl wrote:
 Of course kids are more interesting in things painted on
 screen, especially if they are colorful, move and make
 sounds at that. The next step would be a simple,
 interactive game.

 Which is why I would synthesize something neat yet
 simple from http://processing.org/tutorials/

 Python is overkill for a kid. Ugh. Some people have just
 no common sense at all.

As someone who can only recently claim to be not a kid, I will again
do my duty and counter this point.

GUI is boring. I don't give a damn about that. If I had it my way, I'd
never write any interfaces again (although designing them is fine).
Console interaction is faster to do and it lets me do the stuff I
*want* to do quicker.

Also - Python is pretty much the only language that *isn't* overkill;
once you take more than the first few steps a language that's
*consistent* will help more with learning, á mon avis, than these
quicker languages ever will. Python is consistent and simple.

Then, when you're better and you do want to do cool stuff,
Cython/occasionally PyPy/Numpy/Numba etc. let you get C-like speeds
learning no other languages at all (although you do need to get C
types down). That's the easy way out, not
Python-then-C-because-Python-is-slow or some nonsense like that.

Basically, kid is a *very* generic term and there are people who
like GUIs and there are people who like internals and there are
hundreds of other classifiers from all over the globe. Please don't
conflate groups if you can help it, as it's often just wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My son wants me to teach him Python

2013-06-13 Thread Joshua Landau
On 13 June 2013 14:01, rusi rustompm...@gmail.com wrote:
 Some views of mine (controversial!).

 Python is at least two things, a language and a culture.
 As a language its exceptionally dogma-neutral.
 You can do OO or FP, throwaway one-off scripts or long-term system
 building etc

 However as a culture it seems to prefer the OO style to the FP style.
 This is unfortunate given that OO is on the down and FP is on a rise.
 Some thoughts re OOP: 
 http://blog.languager.org/2012/07/we-dont-need-no-o-orientation-4.html

 So my suggestion is use some rigorous FPL like Haskell to learn/teach
 programming.
 After that you can switch to python or some other realistic language.

Hey - Haskell is realistic [1].

 Note: I have some serious reservations regarding Haskell
 http://blog.languager.org/2012/08/functional-programming-philosophical.html
 Nevertheless it seems to be the best there is at the moment.

 tl;dr: Haskell is in 2013 what Pascal was in 1970 -- good for
 programming pedagogy.
 --
 http://mail.python.org/mailman/listinfo/python-list

[1] http://xmonad.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My son wants me to teach him Python

2013-06-13 Thread Joshua Landau
I don't normally respond to trolls, but I'll make an exception here.

On 14 June 2013 04:33, Rick Johnson rantingrickjohn...@gmail.com wrote:
 On Thursday, June 13, 2013 3:18:57 PM UTC-5, Joshua Landau wrote:

 [...]
 GUI is boring. I don't give a damn about that. If I had it
 my way, I'd never write any interfaces again (although
 designing them is fine). Console interaction is faster to
 do and it lets me do the stuff I *want* to do quicker.

 And are you willing to provide *proof* that the console is
 faster? Or is this merely just your opinion? I would be
 ready and willing to compete in a Pepsi challenge to
 disprove your claim if needed.  For instance, if i want to
 open a text file on my machine, i merely navigate to the
 file via my file browser interface, using clicks along the
 way, and then the final double click will open the text file
 using it's default program. Are you telling me you can type
 the address faster (much less remember the full path) than i
 can point and click? And if you think you're going to cheat
 by creating an environment variable, well i can still win
 by doing the same thing with a shortcut.

1) I said it's faster to implement, not faster to use.
2) Yes, I would win that test. Say I want to go to
Projects/Programming Tidbits/FeedLess, I'd write j Fee. Done. I'm
there. What was hard about that?
3) Gee, you think a graphical file manager is good? You should try
Ranger. Seriously, it's way better. (Seriously)

 Also - Python is pretty much the only language that
 *isn't* overkill; once you take more than the first few
 steps a language that's *consistent* will help more with
 learning, a mon avis, than these quicker languages ever
 will. Python is consistent and simple.

 Your statement is an oft cited misconception of the Python
 neophyte. I'm sorry to burst your bubble whilst also raining
 on your parade, but Python is NOT consistent. And the more i
 learn about Python the more i realize just how inconsistent
 the language is. Guido has the correct base idea, however
 he allowed the evolution to become a train wreck.

If you ignore stdlib, for a moment, lol.
If you include stdlib you're just wrong, but not humorously so.

 [...]
 Basically, kid is a *very* generic term and there are
 people who like GUIs and there are people who like
 internals

 Your statement is true however it ignores the elephant in
 the room. You can prefer console over GUI all day long but
 that does not negate the fact that GUI's outperform the
 console for many tasks. With the exception of text based
 games, the console is as useful for game programming as a
 cheese grater is for masturbation -- slightly amusing, but
 mostly just painful!

I'd like to see you write or do the equivalent of:
when-changed $FILE.coffee coffee -c $FILE.coffee; xclip -selection
clipboard  $FILE.js; echo Update
in a GUI. Really, I would.

Oh, and then make your result searchable with to all of your other
little one-liners, in a process that takes ½ a second to complete.

Nevermind that I was talking about console programs being quicker to
make this whole time, rather than quicker to use.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: The problem with print

2013-06-12 Thread Joshua Landau
On 4 June 2013 14:35, Mark Lawrence breamore...@yahoo.co.uk wrote:
 On 04/06/2013 14:29, rusi wrote:
 The Clash of the Titans

 Lé jmf chârgeth with mightƴ might
 And le Mond underneath trembleth
 Now RR mounts his sturdy steed
 And the windmill yonder turneth


 +1 funniest poem of the week :)

Week? Do we do this every Tuesday?

I vote all-time best post for python-list@python.org.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Split a list into two parts based on a filter?

2013-06-11 Thread Joshua Landau
On 11 June 2013 01:11, Peter Otten __pete...@web.de wrote:
 def partition(items, predicate=bool):
 a, b = itertools.tee((predicate(item), item) for item in items)
 return ((item for pred, item in a if not pred),
 (item for pred, item in b if pred))

I have to tell you this is the coolest thing I've read today. I'd
never have thought of that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Don't rebind built-in names* - it confuses readers

2013-06-11 Thread Joshua Landau
On 11 June 2013 01:14, Terry Jan Reedy tjre...@udel.edu wrote:
 Many long-time posters have advised Don't rebind built-in names*.

 For instance, open Lib/idlelib/GrepDialog.py in an editor that colorizes
 Python syntax, such as Idle's editor, jump down to the bottom and read up,
 and (until it is patched) find
 list.append(fn)
 with 'list' colored as a builtin. Stop. That looks wrong. List.append needs
 two arguments: a list instance and an object to append to the list. The
 'solution' is in a previous line
 list = []
 Reading further, one sees that the function works with two lists, a list of
 file names, unfortunately called 'list', and a list of subdirectories, more
 sensibly call 'subdirs'. I was initially confused and reading the code still
 takes a small bit of extra mental energy. Idle stays confused and will
 wrongly color the list instance name until it is changed. Calling the file
 list 'fnames' or 'filenames' would have been clearer to both me and Idle.

The problem here is the problem with all of this - names should be
descriptive. There is rarely a case where str or string, even, is
sufficiently detailed, and file often really refers to a path for
example.

You should really not worry about shadowing builtins because if you're
using sufficiently long names you almost ne'er accidentally will. In
one of my recent posts I was chastised by someone (I remember not who)
for overwriting the property builtin - obviously this would *never*
happen in real life. If you call your property property you are a
fool. It means nothing!

Secondly, shadowing will _almost never_ be a problem, as you
invariably, given that you don't use list or str as variable
names, will have shadowed a completely contextually useless variable.
And thus, in the one-in-a hundred-in-a-thousand chance that you
accidentally shadow a builtin that happens to be important, you can
assume that your editor has a half-decent variable replacement
mechanism - it's only shadowed in a single scope!



But enough of that, you asked about syntax highlighting.

Personally, the current method is good - it reminds you when you are
shadowing, but does it gently. If you're adamant that the most
sensible name for your variable is format, use it. The highlighting
shouldn't be taken to mean this is from __builtins__, but a little
reminder that __builtins__ uses the name. Chances are, you won't be
using format, so do. The little colour change, though, reminds you
to check that it really is the best name.

Or, well, do what I do and use a proper editor, and set syntax not to
highlight keywords if you care enough. My editor makes a good choice
only to highlight those keywords that you really don't want to shadow
- list, str, etc. - where they're just too vague to be good variable
names. Format's unusual and as such do what you want with it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re-using copyrighted code

2013-06-10 Thread Joshua Landau
On 10 June 2013 17:29, llanitedave llanited...@veawb.coop wrote:
 However, I have yet to see an example of source code that qualifies as either 
 parody or satire under any standard.

You should try reading Perl.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question

2013-06-04 Thread Joshua Landau
On 4 June 2013 04:39,  eschneide...@comcast.net wrote:
 Is there a more efficient way of doing this? Any help is gratly appreciated.


 import random
 def partdeux():
 print('''A man lunges at you with a knife!
 Do you DUCK or PARRY?''')
 option1=('duck')
 option2=('parry')
 optionsindex=[option1, option2]
 randomizer=random.choice(optionsindex)
 while randomizer==option1:
 if input() in option1:
 print('he tumbles over you')
 break
 else:
 print('he stabs you')
 break
 while randomizer==option2:
 if input() in option2:
 print('you trip him up')
 break
 else:
 print('he stabs you')
 break
 partdeux()

I'm going to look directly at the code for my comment, here, and
explain what's up. I imagine you were given this code to fix up,
I'll lead you through the steps.



 import random

You only use random.choice, never anything else, so in this case I'd
be tempted to do:
 from random import choice

This is *entirely optional*: I tend to do quite a lot of from
module import object but others prefer to be more explicit about
where things come from; your choice.



 def partdeux():

Other than the atrocious name this is as simple as it gets to define a
function - you should like that it's a function, though.



 print('''A man lunges at you with a knife!
 Do you DUCK or PARRY?''')

This is iffy! Triple-quotes? Personally this is a really bad time to
use them - they break indentation and whatnot. I'd write:

print('A man lunges at you with a knife!')
print('Do you DUCK or PARRY?')

This, in my opinion, is much nicer. But we haven't simplified much yet.



 option1=('duck')
 option2=('parry')
 optionsindex=[option1, option2]

There are two things off about this. Firstly, no-one should be so
addicted to brackets to use them here, and you should space variables.
 option1 = 'duck'
 option2 = 'parry'

BUT this is not needed anyway. The next line puts both of these in a
variable. You can add them straight in:
 optionsindex = ['duck', 'parry']

There are some things wrong though:
1) *Never* lie. This is not an index of any sort, unless you're
referring to one of these:
[http://shop.pageprotectors.com/images/Index-Ring-Binder-2-Rings-Recipe-3x5-Card.jpg]
This should be named options or, better, valid_responses.

2) You write Do you DUCK or PARRY?. None of this suggests uppercase.
We shall deal with this later.

Thus:
 valid_responses = ['duck', 'parry']


 randomizer=random.choice(optionsindex)
 while randomizer==option1:
...
 while randomizer==option2:

This is odd! What do you think this does? This says that you choose an
option, duck or parry. If it is duck, then do A. If it is
parry, then do B. But why would a computer choose options like that?
Surely it's better to do:

(I'm properly spacing it as I go along, by the way)
randomizer = random.choice([True, False])
while randomizer:
...
while not randomizer:

Oh, that's odd! As randomizer never changes after you set it, you can
be sure that the while randomizer is equivalent to while True or
while False. This means it will loop forever without a break.
Looking at the breaks it is clear that *all paths lead to a break*. A
while *LOOP* should only ever be used to *LOOP*. This makes the
looping redundant.

Thus remove the breaks and use:
randomizer = random.choice([True, False])
if randomizer:
...
if not randomizer:

which can be better written:
if random.choice([True, False]):
...
else:
(BUT you may have to write if choice([True, False]): if you've
followed all of my advice)


 if input() in option1:
option1 no longer exists, so this is now written:
 if input() in valid_responses[0]:
BUT why in? You want to check whether that *equals* the response,
not whether that is *in* the response:
 if input() == valid_responses[0]:


 else:
 print('he stabs you')
Why else? This means that if you wrote Seppuku *he'd* stab you.
You want to check that you actually wrote the right thing!
 elif input() == valid_responses[1]:
 print('he stabs you')
This does not work, but we'll fix it later.


 if input() in option2:
For the same reason, change this to:
if input() == valid_responses[1]:


 else:
 print('he stabs you')
and this to:
 elif input() == valid_responses[0]:
 print('he stabs you')


The rest is better. That leaves you with a much nicer looking function:

### START CODE ###
from random import choice

def partdeux():
print(A man lunges at you with a knife!)
print(Do you DUCK or PARRY?)

valid_responses = [duck, parry]

if choice([True, False]):
if input() == valid_responses[0]:
print('he tumbles over you')
elif input() == valid_responses[0]:
print('he stabs you')

else:
 

Re: How to get an integer from a sequence of bytes

2013-06-04 Thread Joshua Landau
On 4 June 2013 14:39, Grant Edwards invalid@invalid.invalid wrote:
 On 2013-06-03, Dan Stromberg drsali...@gmail.com wrote:
 Today though, it would be difficult to sell a conventional (Von Neumann)
 computer that didn't have 8 bit bytes.

 There are tons (as in millions of units per month) of CPUs still being
 sold in the DSP market with 16, 20, 24, and 32 bit bytes.  (When
 writing C on a TMS320Cxx CPU sizeof (char) == sizeof (int) == sizeof
 (long) == sizeof (float) == sizeof (double) == 1.  They all contain 32
 bits.
)

*) for the bracket not in the reply

Sorry.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [RELEASED] Python 2.7.5

2013-06-04 Thread Joshua Landau
On 4 June 2013 00:12, Mark Lawrence breamore...@yahoo.co.uk wrote:
 On 03/06/2013 23:37, Carlos Nepomuceno wrote:
 What still doesn't work in Python 3?

 http://python3wos.appspot.com/

Don't take this list too seriously - some of those do have fully
working and stable Python 3 packages that just aren't in pip, like
python-daemon.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to increment date by week?

2013-06-04 Thread Joshua Landau
On 4 June 2013 22:31, PieGuy r90...@gmail.com wrote:
Starting on any day/date, I would like to create a one year list, by week 
 (start date could be any day of week).  Having a numerical week index in 
 front of date, ie 1-52, would be a bonus.
ie, 1.  6/4/2013
2.  6/11/2013
3.  6/18/2013etc to # 52.

And to save that result to a file.
Moving from 2.7 to 3.3
 TIA

What have you tried? What are you stuck on? We're not here to do your
work for you.

See http://docs.python.org/3/library/datetime.html for where to get started.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Too many python installations. Should i remove them all and install the latest?

2013-06-03 Thread Joshua Landau
On 3 June 2013 04:18, Chris Angelico ros...@gmail.com wrote:
 On Mon, Jun 3, 2013 at 12:30 PM, alex23 wuwe...@gmail.com wrote:
 On Jun 1, 10:24 am, Chris Angelico ros...@gmail.com wrote:
 Hmm. What other MUD commands have obvious Unix equivalents?

 say -- echo
 emote -- python -c
 attack -- sudo rm -f

 who -- who
 tell -- write
 alias -- ln
 look -- cat
 go -- cd
 teleport -- pushd/popd ?

 I don't use an explicit 'go' though, I usually just type 'n' to go
 north, or 'booth1' to go booth1. Unfortunately that doesn't translate
 well into a simple alias :)

What shell do you use? Zsh supports this (implicit cd). I don't have
it active because it's not that useful - you get better completion
with explicit cd - but it exists.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cutting a deck of cards

2013-06-01 Thread Joshua Landau
On 31 May 2013 12:56, Lee Crocker leedanielcroc...@gmail.com wrote:
 Why on Earth would you want to? Cutting a deck makes no sense in software. 
 Randomize the deck properly (Google Fisher-Yates) and start dealing. 
 Cutting the deck will not make it any more random,

True

 and in fact will probably make it worse depending on how you choose the 
 cutpoint.

I'm pretty sure it won't. Otherwise you'd be lowering entropy by doing
a random thing to a random thing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can anyone please help me in understanding the following python code

2013-05-30 Thread Joshua Landau
On 30 May 2013 10:48,  bhk...@gmail.com wrote:
 Question:
 -
 Function mergeSort is called only once, but it is getting recursively 
 executed after the printing the last statement print(Merging ,alist). But 
 don't recursion taking place except at these places mergeSort(lefthalf), 
 mergeSort(righthalf)

 Sometimes the function execution directly starts from i=0,j=0,k=0 . Not sure 
 how.

Here's some different code; it does the same thing but in a less weird way:

##
def mergeSort(alist, depth=1):
# If the piece we have to sort is [i] or [], then we have no sorting to do
if len(alist) = 1:
# Returning what we were given
# Make a new list from it, though, because we are nice
print({padding}return {list}\n.format(padding= *depth*8,
list=alist))
return alist[:]

# Split along the middle
mid = len(alist)//2

# We have two halves
lefthalf = alist[:mid]
righthalf = alist[mid:]

# Which we sort, so we have two sorted halves
print({padding}lefthalf  = mergesort({list})\n.format(padding=
*depth*8, list=lefthalf))
lefthalf  = mergeSort(lefthalf,  depth+1)

print({padding}righthalf = mergesort({list})\n.format(padding=
*depth*8, list=righthalf))
righthalf = mergeSort(righthalf, depth+1)


# We want to return a sorted alist from our two lists
# We'll add the items to here
new_list = []

# We'll go through adding the smallest to new_list
while lefthalf and righthalf:

# Lefthalf has the smaller item, so we pop it off into new_list
if lefthalf[0]  righthalf[0]:
new_list.append(lefthalf.pop(0))

# Righthalf has the smaller item, so we pop it off into new_list
else:
new_list.append(righthalf.pop(0))

# One of our lists isn't empty, so just add them on
new_list += lefthalf + righthalf

print({padding}return {list}\n.format(padding= *depth*8, list=new_list))
return new_list

print(Start mergesort({list}):\n.format(list=[2, 4, 0, 1]))

sorted_list = mergeSort([2, 4, 0, 1])

print(Our final result: {list}.format(list=sorted_list))
##

And it gives

##
Start mergesort([2, 4, 0, 1]):

lefthalf  = mergesort([2, 4])

lefthalf  = mergesort([2])

return [2]

righthalf = mergesort([4])

return [4]

return [2, 4]

righthalf = mergesort([0, 1])

lefthalf  = mergesort([0])

return [0]

righthalf = mergesort([1])

return [1]

return [0, 1]

return [0, 1, 2, 4]

Our final result: [0, 1, 2, 4]
##

Hopefully this code is a little easier to understand - the original
changes the list while it is running the algorithm and mine makes new
lists. The algorithm is very similar, and what you learn applies to
both.

You can see in the output (thanks Chris Angelico) that the main
function is always running. It runs *two* other instances: lefthalf
and righthalf.

So the mergesort([2, 4, 0, 1]) runs lefthalf  = mergesort([2, 4])

mergesort([2, 4]) runs lefthalf  = mergesort([2])

mergesort([2]) gives back [2] to mergesort([2, 4])

mergesort([2, 4]) goes OH! I can continue now and runs righthalf
= mergesort([4])

mergesort([4]) gives back [4] to mergesort([2, 4])

mergesort([2, 4]) goes OH! I can continue now and gives back [2,
4] to mergesort([2, 4, 0, 1])

mergesort([2, 4, 0, 1]) goes OH! I can continue now and runs
righthalf = mergesort([0, 1])

mergesort([0, 1]) runs lefthalf  = mergesort([0])

mergesort([0]) gives back [0] to mergesort([0, 1])

mergesort([0, 1]) goes OH! I can continue now and runs righthalf
= mergesort([1])

mergesort([1]) gives back [1] to mergesort([0, 1])

mergesort([0, 1]) goes OH! I can continue now and gives back [0,
1] to mergesort([2, 4, 0, 1])

mergesort([2, 4, 0, 1]) goes OH! I can continue now and gives back
[0, 1, 2, 4]

DONE.

Does that help you see the flow?



Exactly the same flow happens for your code. The difference is that
instead of returning a list, mergesort *sorts* a list, and then that
is used to replace items in the original list. Personally, their way
is a little silly (and mine is inefficient, so use neither).


Question: Why did you rewrite the code?
Answer: Revising is boring.


Question: Sometimes the function execution directly starts from
i=0,j=0,k=0 . Not sure how.
Answer: That's not a question. Anyhow:

i, j and k are LOCAL to a function. mergesort([2, 4, 0, 1]) has a
different i, j and k than mergesort([0, 1]), They never use each
other's i, j and k. Hence for each recursion they run i=0, j=0, k=0
and they are set to 0 within the function.


Does this help?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can anyone please help me in understanding the following python code

2013-05-30 Thread Joshua Landau
On 30 May 2013 11:19,  bhk...@gmail.com wrote:
 Also, Can you please let me know how did you found out that I am using Python 
 2 Interpreter.

Do you have access to a Python3 interpreter? If so, try running it and
your output will look like:

Splitting  [54, 26, 93, 17, 77, 31, 44, 55, 20]
Splitting  [54, 26, 93, 17]
Splitting  [54, 26]
Splitting  [54]
Merging  [54]
Splitting  [26]
Merging  [26]
... BLAH BLAH BLAH

Which is obviously much nicer. This is how Chris knew the code was
written for Python3. Therefore I would suggest you use Python3 - not
all code runs on both!

The proper way to write the prints for Python2 is without the brackets:

print Merging ,alist

But the methods Chris and I have used work the same on both so are
probably better in this case. They're more complicated, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: User Input

2013-05-30 Thread Joshua Landau
On 30 May 2013 15:47, Eternaltheft eternalth...@gmail.com wrote:
 And perhaps you meant for your function to CALL drawBoard(), rather than
 returning the function object drawBoard.

 DaveA

 do you think it would be better if i call drawBoard?

Please read http://www.catb.org/esr/faqs/smart-questions.html, or
anything similar you can find.

Start from the beginning.

1) What are you doing? Not what are you doing now but, from the top,
what is the goal you are trying to achieve?

2) How have you tried to do it? Code  would be nice here too, but
don't just send really large blocks of irrelevant code. For example, your
drawBoard function would be better surmised as:

def drawBoard(b):
Turtle.speed(0)
Turtle.up()
Turtle.goto(-4 * b, 4 * b)
Turtle.down()

for i in range (8):
Turtle.forward(b)
Turtle.right(90)
... # etc, drawing a board

3) What are you stuck on? In this case, you are stuck on what to do
after you call input(stuff), if I understand. What do you want to do
- not how do you want to do it but what is it that you are doing?

4) Finally, we should understand what calling drawBoard is for. Ask us
again and we'll be much more likely to give good answers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Fatal Python error

2013-05-29 Thread Joshua Landau
Hello all, again. Instead of revising like I'm meant to be, I've been
delving into a bit of Python and I've come up with this code:

class ClassWithProperty:
 @property
def property(self):
pass

thingwithproperty = ClassWithProperty()

def loop():
try:
thingwithproperty.property
 except:
pass

loop()

try:
loop()
except RuntimeError:
pass

As you will expect, this does nothing... on Python2.7 and PyPy. Python3.3
prefers to spit out a Fatal Python error: Cannot recover from stack
overflow., which seems a bit unexpected.

Wuzzup with that?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fatal Python error

2013-05-29 Thread Joshua Landau
On 29 May 2013 13:25, Dave Angel da...@davea.name wrote:

 On 05/29/2013 07:48 AM, Joshua Landau wrote:

 Hello all, again. Instead of revising like I'm meant to be, I've been
 delving into a bit of Python and I've come up with this code:


 To start with, please post in text mode.  By using html, you've completely
 messed up any indentation you presumably had.


Appologies, I use GMail and I don't know how to force text-only


  class ClassWithProperty:
   @property
 def property(self):
 pass


 Did you really mean to hide the built-in property?  I don't know if this
 does that, but it's certainly confusing.  And perhaps that's a difference
 between 2.x and 3.x


I'm not. That goes to self.property, whilst the normal function isn't. I
guess it does locally hide it, but who really cares? :P

You can rename it if you want. Anything will do. Obviously this is a
minimal example code, and not the real thing.

 As you will expect, this does nothing... on Python2.7 and PyPy. Python3.3
 prefers to spit out a Fatal Python error: Cannot recover from stack
 overflow., which seems a bit unexpected.


 A stack overflow means you have infinite recursion.


I realise, but I was hoping to catch that with the except RuntimeError.


 Try fixing the property name above, and see if that makes a difference.


It does not make a difference.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fatal Python error

2013-05-29 Thread Joshua Landau
On 29 May 2013 13:30, Marcel Rodrigues marcel...@gmail.com wrote:

 I just tried your code with similar results: it does nothing on PyPy
2.0.0-beta2 and Python 2.7.4. But on Python 3.3.1 it caused core dump.
 It's a little weird but so is the code. You have defined a function that
calls itself unconditionally. This will cause a stack overflow, which is a
RuntimeError.


The weirdness of the code is simply as I've taken all the logic and
conditionality away, since it was irrelevant. Why, though, does removing
any one element make it fail properly? That's what's confusing, largely.


  Since you are handling this very exception with a pass statement, we
would expect that no error occurs. But the fatal error message seems pretty
informative at this point: Cannot recover from stack overflow..

 One thing to note is that while it's reasonable to handle exceptions that
happens at the level of your Python code, like a ValueError, it's not so
reasonable to try to handle something that may disturb the interpreter
itself in a lower level, like a stack overflow (I think that the stack used
by your code is the same stack used by the interpreter code, but I'm not
sure).


What is the expected response here then? Should I ever feel justified in
catching a Stack Overflow error? This code was extracted from a file
manager after much difficulty, but it should have been caught by a global
try...except and not crashed the whole program immediately. I'd imagine
that's a good enough reason to bring this up.



Also;
This works for the code:

def loop():
thingwithproperty.prop
loop()

This does not:

def loop():
try:
thingwithproperty.prop
except:
pass
loop()

thingwithproperty.prop NEVER creates an error.
(.prop is the new .property)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fatal Python error

2013-05-29 Thread Joshua Landau
On 29 May 2013 14:02, Dave Angel da...@davea.name wrote:

 On 05/29/2013 08:45 AM, Oscar Benjamin wrote:
 Joshua:  Avoid doing anything complex inside an exception handler.


Unfortunately, Ranger (the file manager in question) wraps a lot of stuff
in one big exception handler. Hence there isn't much choice. The original
wasn't actually in an infinite recursion, too, but just a recursion over a
large directory.

Is there a reason that Python 3 can't be made to work like Python 2 and
PyPy, and -if not- should it? The catchable fail would be much nicer than
just bombing the program.

In the meantime the algorithm should just be reworked, but it seems like a
larger step than should be needed.

If nothing else, the exception frame is huge.  I probably would have
 spotted it except for the indentation problem triggered by html.  The top
 level code following your function didn't have any loops, so it wasn't a
 problem.

 Can anyone help Joshua put his gmail into text mode?


I've found a new option. As a test, here's a simplified version without the
property:

def loop():
try:
(lambda: None)()
except:
pass

loop()

try:
loop()
except RuntimeError:
pass

which is pretty much Oscar Benjamin's, but less stupid.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do Perl programmers make more money than Python programmers

2013-05-06 Thread Joshua Landau
On 6 May 2013 13:03, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.infowrote:

 On Mon, 06 May 2013 17:30:33 +1000, Chris Angelico wrote:

  On Mon, May 6, 2013 at 4:28 PM, Fábio Santos fabiosantos...@gmail.com
  wrote:
  And of course, the Python Programmer's moral code is only 80
  characters wide.
 
  No! Was it not seventy characters wide? Was I fooled my entire life?
 
  Well you see, it was 70 bytes back in the Python 2 days (I'll defer to
  Steven for data points earlier than that),


 You had bytes? You were lucky. When I were a lad, we used to have to
 program by punching holes in stone tablets with our head.


 You-tell-young-people-this-today-and-they-don't-believe-you-ly y'rs,


I do have my doubts, yes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with loading file into an array

2013-05-06 Thread Joshua Landau
On 5 May 2013 07:06, peter berrett pwberr...@gmail.com wrote:

 I am trying to build a program that can find comets in a series of
 astronomical images. I have already written functions to find the comet in
 a series of images, the data of which is stored in embedded lists.

 The area I am having difficulty with is take a standard gif file (1024 x
 1024) and reading it into an array or embedded lists.


This is not what you should really be doing. There are specialised things
for this.

Take a look at PIL (http://www.pythonware.com/products/pil/).
It will install as Image and from there you can do:

import Image
image = Image.open(FILE)
pixels = image.load()

and access the pixels like:

pixels[x, y] # You get (r, g, b) tuple of integers from 0 to 255


 In a nutshell here is an example of what I want to do

 Let's say I have a gif file called 20130428__c2_1024.gif in a folder
 called c:\comets

 I want to read the data from that gif file taking the red data (excluding
 the green and blue data) and store that in an array called Image[][] which
 is a nested array length 1024 with a list in each item of 1024 length (ie
 1024 x 1024)


*Ahem*:
1) Python standard is to only uppercase class (and sometimes module) names,
so it should just be image.
2) Technically, you mean list.
3) Chose the above method instead, so instead of indexing it with
image[x][y] you use image[x, y].

Now, you only want the red channel. What this means is that you want to
split the image into channels before using image.load():

import Image

image = Image.open(FILE)
image.load() # .open is lazy, so you have to load now

red, green, blue = image.split()
red_pixels = red.load()

And you access as before:

red_pixels[x, y] # You get integer from 0 to 255

Could someone please provide a piece of code to do the above so I can then
 go on to modify it to pick up different files from different folders? In
 particular I am keen to seen how you read in the data and also how you
 change the directory from which you are reading the image.


Changing directories is done with os.chdir (
http://docs.python.org/3/library/os.html#os.chdir).


 For the record this is not for homework but is a pet project of mine. I
 have already written a version of the program in Justbasic but python is
 faster. I am also interested in readers views as to which is the simplest
 and best way to achieve what I am trying to do.


Thanks for the clarification, btw. Good luck, as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Collision of Two Rect

2013-05-06 Thread Joshua Landau
On 4 May 2013 00:42, Ian Kelly ian.g.ke...@gmail.com wrote:

 The other thing that is suspicious about the code you posted is that
 it has two different notions of the ball's position that are not
 necessarily in agreement.  There is the ball_rect, and there are also
 the x and y variables.

snip

 You should be careful to make sure these
 variables agree at all times -- or better yet, get rid of x and y
 entirely, so that you only have one notion of the ball's position to
 worry about.


Pygame uses integers for its Rects and thus I advise much the opposite:
*never* store position in Rects.

Sorry, but it's true. You'll need to keep x and y around and try to use
Rects only when representing pixels on the screen. Pygame has a lot of
deficiencies with its default set of objects and functions, so it's
something to get used to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested iteration?

2013-04-23 Thread Joshua Landau
On 23 April 2013 21:49, Terry Jan Reedy tjre...@udel.edu wrote:

 ri= iter(range(3))
 for i in ri:
 for j in ri:
 print(i,j)
 # this is somewhat deceptive as the outer loop executes just once
 0 1
 0 2

 I personally would add a 'break' after 'outer_line = next(f)', since the
 first loop is effectively done anyway at that point, and dedent the second
 for statement. I find to following clearer

 ri= iter(range(3))
 for i in ri:
 break
 for j in ri:
 print(i,j)
 # this makes it clear that the first loop executes just once
 0 1
 0 2

 I would only nest if the inner loop could terminate without exhausting the
 iterator and I wanted the outer loop to then resume.


Surely a normal programmer would think next(ri, None) rather than a loop
that just breaks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested iteration?

2013-04-23 Thread Joshua Landau
On 23 April 2013 22:29, Oscar Benjamin oscar.j.benja...@gmail.com wrote:

 I just thought I'd add that Python 3 has a convenient way to avoid
 this problem with next() which is to use the starred unpacking syntax:

  numbers = [1, 2, 3, 4]
  first, *numbers = numbers


That creates a new list every time. You'll not want that over
try-next-except if you're doing this in a loop, and on addition (if you
were talking in context) your method will exhaust the iterator in the outer
loop.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools.groupby

2013-04-21 Thread Joshua Landau
On 21 April 2013 01:13, Steven D'Aprano 
steve+comp.lang.pyt...@pearwood.info wrote:

 I wouldn't use groupby. It's a hammer, not every grouping job is a nail.

 Instead, use a simple accumulator:


 def group(lines):
 accum = []
 for line in lines:
 line = line.strip()
 if line == 'Starting a new group':
 if accum:  # Don't bother if there are no accumulated lines.
 yield accum
 accum = []
 else:
 accum.append(line)
 # Don't forget the last group of lines.
 if accum: yield accum


Whilst yours is the simplest bar Dennis Lee Bieber's and nicer in that it
yields, neither of yours work for empty groups properly.

I recommend the simple change:

def group(lines):
accum = None
for line in lines:
line = line.strip()
if line == 'Starting a new group':
if accum is not None:  # Don't bother if there are no
accumulated lines.
yield accum
accum = []
else:
accum.append(line)
# Don't forget the last group of lines.
yield accum

But will recommend my own small twist (because I think it is clever):

def group(lines):
lines = (line.strip() for line in lines)

if next(lines) != Starting a new group:
 raise ValueError(First line must be 'Starting a new group')

while True:
 acum = []

for line in lines:
if line == Starting a new group:
 break

acum.append(line)

else:
 yield acum
break

yield acum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I hate you all

2013-04-06 Thread Joshua Landau
On 6 April 2013 07:56, Timothy Madden terminato...@gmail.com wrote:

 On 06.04.2013 08:53, Ian Kelly wrote:

 On Fri, Apr 5, 2013 at 11:07 PM, Timothy Madden terminato...@gmail.com
 wrote:

 [...]

 So in other words, everybody must be forced to use 8-character tabs
 because you want to be able to mix tabs and spaces.

  People say I can use tabs all the way, just set them to the indent I
 want.

 Well, I always had my indent independent of the tab size. Which is the
 way
 it should be, after all, since one can indent with or without tabs, so
 indent should not be tied to them.

 But now I can not; python no longer lets me do that.


 Honestly, I really don't understand why you *want* to do that.  If
 your indentation is 4 characters, then that would be the natural tab
 width to use.  If you're not going to tie your indent to your tabs,
 then why even use tabs in the first place?

  The new rules may look flexible at first sight, but the net effect they
 have
 is they push me to use non-default tab size (which is not good),


 What makes that not good?  There is no law anywhere that says tabs are
 8 characters.  That's just an arbitrary amount that looked appropriate
 to the people designing the first teletypes.


 I am aware that 7 bytes per tab character (or 14/28, in UTF-16, UTF-32!)
 will not justify the time spent debating.

 The reason I want to use tabs is that I think there is nothing wrong with
 them.


So use them


 The reason why everybody should use 8-character tabs is so that I and the
 rest of the world can use `grep` / `findstr` on their code, and still see
 lines of code properly aligned in the terminal. Or to be able to print
 fragments of code as plain text only, and get the proper alignment.


Oh thanks. I liked using my four character tabs, but I guess you *are* so
important that I'm going to have to change everything I do just for you.
It's obviously not good enough for you just to not mix tabs and spaces so
that we can both enjoy ourselves because that would make *you*, the holiest
of all, have to put some effort in. No, I totally understand and will now
go and change everything after Python is changed to break hundreds of files
of codes for you.


 But most importantly, the reason that tab size should be 8 is so that all
 of us people in this world can freely exchange formatted text like source
 code without having to first consider if will it look the same in their
 editor ? What tab size do they use ?


Hrm. Hrm. Hmmm.

H.

No, you're right: spaces are totally not for this in any way and that
no-one has ever made this point before and who the hell cares if you're
reading code with a different indent size anyway it's not like it affects
the actual code.

Yours frustratedly,

Joshua Landau



But seriously, please at least look like you've read other people's posts.
It doesn't matter what tabstop you use as long as you don't mix. If your
code depends on tab size then it's categorically wrong. Other people's tab
sizes are as valid. I use tabs because of the variation it lets me have - I
can switch tab sizes on the fly - and it's faster on dumb editors. So let
me do that.

But let us assume we were going to standardise on TAB == 8 SPACES. It would
*still* be bad to mix tabs and spaces. Hence you'd change Python in exactly
0 ways. So *what do you want from us*?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: JIT compilers for Python, what is the latest news?

2013-04-06 Thread Joshua Landau
On 5 April 2013 19:37, Devin Jeanpierre jeanpierr...@gmail.com wrote:

 On Fri, Apr 5, 2013 at 4:34 AM, John Ladasky john_lada...@sbcglobal.net
 wrote:
  On Thursday, April 4, 2013 7:39:16 PM UTC-7, MRAB wrote:
  Have you looked at Cython? Not quite the same, but still...
 
  I'm already using Numpy, compiled with what is supposed to be a fast
 LAPACK.  I don't think I want to attempt to improve on all the work that
 has gone into Numpy.

 There's no reason you can't use both cython and numpy. See:
 http://docs.cython.org/src/tutorial/numpy.html


Don't use this. Use memoryviews:
http://docs.cython.org/src/userguide/memoryviews.html. I have no idea why
that doc page isn't headed DEPRICATED by now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: JIT compilers for Python, what is the latest news?

2013-04-06 Thread Joshua Landau
On 5 April 2013 03:29, John Ladasky john_lada...@sbcglobal.net wrote:

 I'm revisiting a project that I haven't touched in over a year.  It was
 written in Python 2.6, and executed on 32-bit Ubuntu 10.10.  I experienced
 a 20% performance increase when I used Psyco, because I had a
 computationally-intensive routine which occupied most of my CPU cycles, and
 always received the same data type.  (Multiprocessing also helped, and I
 was using that too.)

 I have now migrated to a 64-bit Ubuntu 12.10.1, and Python 3.3.  I would
 rather not revert to my older configuration.  That being said, it would
 appear from my initial reading that 1) Psyco is considered obsolete and is
 no longer maintained, 2) Psyco is being superseded by PyPy, 3) PyPy doesn't
 support Python 3.x, or 64-bit optimizations.

 Do I understand all that correctly?

 I guess I can live with the 20% slower execution, but sometimes my code
 would run for three solid days...


If you're not willing to go far, I've heard really, really good things
about Numba. I've not used it, but seriously:
http://jakevdp.github.io/blog/2012/08/24/numba-vs-cython/.

Also, PyPy is fine for 64 bit, even if it doesn't gain much from it. So
going back to 2.7 might give you that 20% back for almost free. It depends
how complex the code is, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: In defence of 80-char lines

2013-04-04 Thread Joshua Landau
On 4 April 2013 12:09, Tim Chase python.l...@tim.thechases.com wrote:

 On 2013-04-04 08:43, Peter Otten wrote:
  llanitedave wrote:
  self.mainLabel.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD,
 faceName = FreeSans))
 
  I think I would prefer
 
  labelfont = wx.Font(
  pointSize=12,
  style=wx.DEFAULT,
  family=wx.NORMAL,
  weight=wx.BOLD,
  faceName=FreeSans)
  self.mainLabel.SetFont(labelfont)

 +1
 The only change I'd make to this suggestion would be to add a
 semi-superfluous comma+newline after the last keyword argument too:

  labelfont = wx.Font(
  pointSize=12,
  style=wx.DEFAULT,
  family=wx.NORMAL,
  weight=wx.BOLD,
  faceName=FreeSans,
  )


Since we're all showing opinions, I've always prefered the typical block
indentation:

labelfont = wx.Font(
pointSize=12,
style=wx.DEFAULT,
family=wx.NORMAL,
weight=wx.BOLD,
faceName=FreeSans,
) # Not indented here

as

A(
B(
C,
D,
E,
)
)

reads a lot cleaner than

A(
B(
C,
D,
E
)
)

which makes diffs cleaner when you need to insert something after
 faceName:

DIFS SNIP

That is a very good point :).

Additionally, if there are lots of keyword parameters like this, I'd
 be tempted to keep them in sorted order for ease of tracking them
 down (though CSS has long-standing arguments on how properties should
 be ordered, so to each their own on this).


Personally I'd rarely be tempted to put more than 9 or so arguments
directly into a function or class. Most of the time I can imagine unpacking
(or equiv.) would look much more readable in the circumstances that apply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance of int/long in Python 3

2013-04-02 Thread Joshua Landau
The initial post posited:
The Python 3 merge of int and long has effectively penalized
small-number arithmetic by removing an optimization. As we've seen
from PEP 393 strings (jmf aside), there can be huge benefits from
having a single type with multiple representations internally. Is
there value in making the int type have a machine-word optimization in
the same way?

Thanks to the fervent response jmf has gotten, the point above has been
mostly abandoned  May I request that next time such an obvious diversion
(aka. jmf) occurs, responses happen in a different thread?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Small program ideas

2013-02-26 Thread Joshua Landau
On 26 February 2013 22:47, eli m techgeek...@gmail.com wrote:

 How hard would it be to change one file to another and would it be a
 small-medium sized program?


How do you want to change it? Like rename a file (os.rename)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 24 February 2013 19:29, piterrr.dolin...@gmail.com wrote:

 Hi. Steve, I don't know where you have been over the past couple of days
 but it is widely known (if the thread title is any indication) that I am
 indeed very new to Python, but not new to programming in general.

 To give a bit of background where I found __str__, I am using a Python IDE
 called PyScripter. Its Intellisense is full of methods starting and ending
 with __, hence the question.

 Regarding Hungarian notation, I don't use it in any other language but
 Python and JS. Call it poor, but it helps me to remember what type a
 variable is.


If you can't remember what type a variable is, you're doing something
incorrectly.


 The redundant comments serve the same purpose.


To help you remember the type of the variable?

 intX = 32  # decl + init int var
How is it not obvious that intX is an integer *without* the comment?

 X = 32
How is it not obvious that X is an integer?

 intX_asString = None   # decl + init with NULL string var
How is it not obvious that intX_asString is an integer (it starts with
int, duh... oh wait)

The comment says it's the NULL string, so it's . F*ck.

It's None. Why? No idea.

 intX_asString = intX.__str__ ()# convert int to string
Wait. So why'd you write the previous line?

Just write:
 X_as_string = str(X)
'Cause str *always* returns a string. So it's a string. How is that not
obvious?


But then, what's the context?

X is a *useless* name. Why are you converting X to a string? I have no
idea. The problem with the code isn't that you could be overwriting X.
The problem is that your code is contradictory, pretends it's C, has
useless names and doesn't try to be readable.


 As for pointless predeclaration, it helps me know where in the code I
 first started using the variable, so I know there are no references to it
 before then.


Why? Why can't you overwrite old variables? Why can't a variable change
type? If your functions are so large that you're likely to lose track of
what's defined, you have a different problem indeed.


For example:
def floatA_floatB_floatC_to_tupleR(floatA, floatB, floatC): # decl with
floatA, floatB, floatC parameters
floatD = None # decl + init with NULL float var
floatD = ((floatB ** 2) - (4 * floatA * floatC)) # set to B² - 4AC
floatD = floatD ** 0.5 # set to √floatD

floatR1 = None # decl + init with NULL float var
floatR1 = (((- floatB) + floatD) / (2 * floatA)) # set to (-B+D)/(2A)

floatR2 = None # decl + init with NULL float var
floatR2 = (((- floatB) - floatD) / (2 * floatA)) # set to (-B-D)/(2A)

return (floatR1, floatR2)

Versus

def solve_quadratic(a, b, c):
Solve a quadratic equation of the form ax² + bx + c = 0

The result will be a tuple of the two results; the results can be equal if
the determinant is 0.
This supports imaginary results for if the determinant is negative.

# The method used is the quadratic equation:
# http://en.wikipedia.org/wiki/Quadratic_equation

# b² - 4ac
determinant = b**2 - 4*a*c

# ±√(b² - 4ac)
 sqrt_determinant = determinant ** 0.5
squareroots = sqrt_determinant, -sqrt_determinant

 # -b ± √(b² - 4ac)
fraction_tops = [(-b + d) for d in squareroots]

results = [top/(2*a) for top in fraction_tops]

return results

Which is easier to read? Reading through it you don't just suddenly forget
what the type of determinant is (which must be a number because it's a
determinant) or results (which is a container since it's plural). The
names tell you.

The useful comments such as The method used is... and ±√(b² - 4ac) give
you context, too, which is a lot more than can be said of
floatA_floatB_floatC_to_tupleR. For that, I tried to emulate what I saw
in your code.

I'm not a good programmer. But because of that the code I write makes
sense, so I can understand it. Tell the reader what they want to know, not
what they see.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 24 February 2013 20:48, Roy Smith r...@panix.com wrote:

 In article mailman.2434.1361738581.2939.python-l...@python.org,
  Chris Angelico ros...@gmail.com wrote:

  On Mon, Feb 25, 2013 at 7:34 AM, MRAB pyt...@mrabarnett.plus.com
 wrote:
   Some languages require parentheses, others don't.
  
   C does. C++, Java and C# are descended from, or influenced by, C.
  
   Algol didn't (doesn't?). Pascal, Modula-2, Oberon, Ada, and others
   don't.
  
   Parentheses are used where required, but not used where they're not
   required, in order to reduce visual clutter.
 
  And just to muddy the waters, parens are used in Python when the
  condition goes over a line break:
 
  if (condition1
  and condition2
  and condition3):
 
  ChrisA

 That could also be written:

 if condition1 \
and condition2 \
and condition3:

 but as a practical matter, I would write it in the parens style, if for
 no other reason than because emacs does a better job of auto-indenting
 it that way :-)


Pah,

condition1 = long_condition_expression_1
condition2 = long_condition_expression_2
condition3 = long_condition_expression_3

if condition1 and condition2 and condition3:
STUFF

No multiline needed. If you have *many* conditions, then:

supercondition = all(
condition1,
condition2,
condition3,
condition4,
condition5,
condition6,
condition7,
condition8,
condition9
) # or equiv.

if supercondition:
STUFF


Reason:
Indentation should be *really simple*.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 24 February 2013 22:43, piterrr.dolin...@gmail.com wrote:

 Josh,

 Not thank you for your malicious post.


Be careful, us programmers do *eventually* catch on to who is a troll, and
if you say things like that we may eventually mark you off as just to
hostile.
I *honestly* meant no malice or insult. If you can't take my word, you can
point out what I said that was otherwise.

(Then again, you'll have about a week before we really start to notice :P)


 I think you are missing the point here.

 My source code was just a dummy to offer context for the question I wanted
 to ask. Further down the line, if I ever feel I don't need to
 pseudo-declare variables I will stop doing it. But for the moment I am
 trying to imitate familiar ground.

 My code as written has no syntax errors, so what's the problem? It is
 highly unlikely you will ever read any of my Python code - no need to get
 excited over a few of my lines.


You said Any comments on this before I quit my job?.

I commented on how I think you should approach Python in order to
appreciate its virtues rather than get stuck in its differences. Again, I
am no good programmer, but I think these methods will help you.


 And you don't need to answer questions which were not posed, thank you.


Nor do I need to answer questions which were posed.


 I wanted Python to register what type of variable I'm after. So I init my
 vars accordingly, int might be 0, float 0.0 and string with null, err...
 None.


You seem to think that a null version of a type is the falsy version.
Then:
int - 0
float - 0.
tuple - ()
list - []

And then (*dun dun duuun!*):

str -  (NOT None, which is a different type)

Other people have commented on whether this is a good idea (it's not), so
I'll suggest you read those, too.

In practice, I wouldn't define an intX_asString var, I would do str (num)
 every time a string representation is needed, provided it isn't a loop, as
 in that context the expression would probably negatively impact performance
 in an interpreted language.


PS: Guess what str(None) is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 24 February 2013 22:08, Chris Angelico ros...@gmail.com wrote:

 On Mon, Feb 25, 2013 at 8:35 AM, Joshua Landau
 joshua.landau...@gmail.com wrote:
  def solve_quadratic(a, b, c):
  Solve a quadratic equation of the form ax² + bx + c = 0
 
  The result will be a tuple of the two results; the results can be equal
 if
  the determinant is 0.
  This supports imaginary results for if the determinant is negative.
  ...
  results = [top/(2*a) for top in fraction_tops]

 Yeah, I think we know which one is the more readable... Just to
 nit-pick a little though, that returns a list when its docstring says
 it'll return a tuple :)


Good catch.


 Other than that (which is probably better solved by changing the docs
 than the code), the only change I'd make would be to ditch the
 fraction_tops temporary (and to throw out some of the comments that
 serve only to reexpress the code that immediately follows them, though
 for a demo they're entirely appropriate).


I knew someone would critique it. It's an exaggerated demo for foo's sake.
Heck, who even uses a function like that (or uses unicode in comments :P)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 24 February 2013 23:18, Oscar Benjamin oscar.j.benja...@gmail.comwrote:

 On 24 February 2013 21:35, Joshua Landau joshua.landau...@gmail.com
 wrote:
 
  determinant = b**2 - 4*a*c

 It's called the discriminant. A determinant is something altogether
 different.


*cries at own idiocy*

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


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 25 February 2013 00:08, piterrr.dolin...@gmail.com wrote:

  For example (I believe it's already been mentioned) declaring intX
 with some integer value does *nothing* to maintain
 
  X as an integer:
 
  -- intX = 32
 
  -- intX = intX / 3.0
 
  -- intX
 
  10.66
 

 Yes I did see that it is possible to redefine the type of a variable. But
 I don't think I would ever do this intentionally; need to be really careful
 with Python.


Not necessarily.

Python duck types. If you don't know what that means, Google's got a ton on
it.

Take a look at my really bad quadratic equation solver. It supports integer
input, float input and complex input. It will output a list of two floats
or complex numbers.

That's a use for having one variable have different types. You'll find
thousands of parallels in real, working code.

Hence, you don't really need to be careful. You'd probably benefit if you
stopped thinking of supporting type-changing as dangerous and started
thinking of it as useful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 25 February 2013 02:08, Dennis Lee Bieber wlfr...@ix.netcom.com wrote:

 On Sun, 24 Feb 2013 21:58:36 +, Joshua Landau
 joshua.landau...@gmail.com declaimed the following in
 gmane.comp.python.general:


 
  condition1 = long_condition_expression_1
  condition2 = long_condition_expression_2
  condition3 = long_condition_expression_3
 
  if condition1 and condition2 and condition3:
  STUFF
 
  No multiline needed. If you have *many* conditions, then:
 
 Except that Python does short-circuit evaluation; your scheme will
 fail in some situations:

  x = 0
  if x != 0 and 32 / x  4:
 ... print we passed
 ...
  c1 = x != 0
  c2 = 32 / x  4
 Traceback (most recent call last):
   File interactive input, line 1, in module
 ZeroDivisionError: integer division or modulo by zero
 


Yeah, well... context*.

There are perfectly legitimate ways of doing that too.

A simple one would be:

 supercondition = (
 long_condition_expression_1 and
 long_condition_expression_2 and
 long_condition_expression_3
 )

 if supercondition: ...

Please note the problem of the original is that the indentation dedents and
indents in too quick a sequence:

 if (
 something_here): # Where do I indent this to?
 something_else

There are standards, but I don't like the style. I thought it worth
mentioning as we were all being subjective anyway ;P. It's much worse than:

 if something_here: something_else #on the same line

which is already explicitly advised against.

* By which I mean: fair point
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with exam task for college

2013-01-04 Thread Joshua Landau
On 4 January 2013 19:00, Chris Angelico ros...@gmail.com wrote:

 On Sat, Jan 5, 2013 at 5:59 AM, Chris Angelico ros...@gmail.com wrote:
  Google tells me that brandstofmeter might mean Babylon 9

 And by the way, in case it didn't come across, I'm jesting there. What
 I mean is that Google didn't have any useful and obvious results
 indicating what this actually means. But I'm guessing it's a fuel or
 altitude gauge.


It might measure a brand in femtometers ;).

But, seriously, it's Dutch for Fuel Gauge. Google told me, in case you
think I know Dutch, but it's in the Python Spirit either way.

ruimteschip - Spaceship
hoek - angle
sterren - stars
poot - leg
vlam - flame
graden - degrees
maan - moon

I'd say they'd be good names if you're in the Netherlands.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please help if you can!

2012-12-26 Thread Joshua Landau
THIS IS A LONG POST, BUT IF YOU WANT TO LEARN YOU SHOULD READ IT. SERIOUSLY.

UNLIKE Mitya Sirenef's THIS DOES NOT ASSUME MORE KNOWLEDGE THAN IS IN YOUR
POST ALREADY, ALTHOUGH HIS IS DEFINITELY BETTER OVERALL. AS SUCH, THERE ARE
NO FUNCTIONS.

OK. There are several small errors in here, but there's nothing too large
or worth much worry.

On 26 December 2012 21:40, bobflipperdoo...@gmail.com wrote:

 I really hope you can help!

 I need to create a program where the user can order any combination and
 quantity of 3 products. I then offer a 10% discount if the customer
 correctly answers a trivia question.  After that, there are 3 choices for
 shipping.

 I have most of the program completed but I'm struggling with the most
 important parts :/  I get the total of multiple orders of the same item,
 but we can't figure out how to total the entire order - before discounts
 and shipping - and then where to put any code referring back to the trivia
 question. Can somebody please help me with this? I would really appreciate
 it!


You write that you need to do this, which may hint that this is some sort
of homework. If so, it's generally a nice thing to say as much. That said,
as long as you've given a good shot at it it's normally fine.


 This is the code:


My *very first* thought about this code is that it's really badly spaced.
Don't put lines together so much! [https://gist.github.com/4383950] shows
how much nicer things look when they're partitioned more. You may not
agree, but it took about 10 seconds and I prefer it.


 shop_again = 'y'


Hold on! Hold on!
shop_again should have a True/False value. It is screaming to be a boolean.
y is a letter, not a boolean. Thus:

shop_again = True

This is important because you don't really want to get confused with all
your types. What if shop_again was later changed to be True when a button
was clicked. Why on earth would you set it to y? You'd set it to True.
Thus, the sensible option is to have your types right from the very start.

print(Welcome to the Star Wars Shop!)
 customer = eval(input(Is there a customer in line? (1 = yes, 2 = no) ))


eval(input(TEXT)) is a *bad* idea.

First of all, eval is really dangerous. Answer yes instead and it'll just
crash. Answer True and it'll run... BUT do *neither* the if or the elif!
That's *bad*.
Secondly, you don't need it. Your:

if(customer == 1) could be if(customer == '1'), which would work
without the eval.

And then you've got the standard of Y/N. So a better question would be:

customer = input(Is there a customer in line? [Y/N] )

Finally, you want to accept Y *and* y, so you'd really want:

customer = input(Is there a customer in line? [Y/N] ).lower()

-
customer = input(Is there a customer in line? [Y/N] ).lower()
Because customer really deserves to be boolean [True/False], you'd want to
change it immediately.

customer = (customer == y)

This second line assumes that all non-ys are False, but that's a folly
you'll have to live with for now.

while shop_again == 'y':


If you've changed shop_again to be boolean:

while shop_again:

Some people don't get how this line would make sense. But it does. The
while statement only cares if it's value it gets is truthy. Here are
lots of truthy things:

y == y
True
False == False
not False
egg loaf
[1, 2, 1, False, False]

and here are some falsy things:

n == y
False
True == False
not True

[]

If this makes no sense, please just say.

if (customer == 2):


Again, if you've done my changes from above:

if not customer:


 print(Welcome to the Star Wars Memorabilia Shop!)
 customer = eval(input(Is there a customer in line? (1 = yes, 2 =
 no) ))


Again:

customer = input(Is there a customer in line? [Y/N] ).lower()
customer = (customer == y)

BUT HOLD ON!

Run your program and then answer 2 twice. What happens? It's not good.

The problem is that answering 2 to this second one doesn't skip the loop!

x = ASK
LOOP:
if not x:
ASK
if x:
STUFF
MORE STUFF

Where you want:

x = ASK
LOOP:
if not x:
ASK
if x:
STUFF
MORE STUFF

or (even better):

while not x:
x = ASK
LOOP:
STUFF
MORE STUFF

The second is what I've just decided to call the ask-until-yes model.
Basically, you ask until you get a yes, so you don't have to put the loop
anywhere else. By the time the first loop is over, you *know* that x is
True!

elif (customer == 1):


Again, if you've done my changes from above:

elif customer:


 print(Please select an item to update your order and any other
 number to check out.)
 print(Yoda Figure: $10 each.)
 print(Star Wars Movie DVD: $20 each.)
 print(Death Star Lego Set: $200 each.)
 print( 1 for Yoda Figure)
 print( 2 for Star Wars Movie DVD)
 print( 3 for Death Star Lego Set)
 order = eval(input(Order: ))


Again:

order = input(Order number: )


 if (order == 1):


If you've followed my advice:

if order == 

Re: Please help if you can!

2012-12-26 Thread Joshua Landau
On 27 December 2012 00:04, bobflipperdoo...@gmail.com wrote:

 First, sorry for starting a new post - I didn't want anyone to have to
 read through the whole first one when the questions were completely
 different :/

 Second, I honestly have no idea how to answer your questions.  I am a
 sophomore in high school and I am trying to learn this on my own because my
 teacher is not very good at explaining things.

 i just cant figure out how to get the total when an order is placed
 without the customer ordering at least one of each item.  I also can't
 figure out how to get the shipping to calculate correctly. It is an intro
 class and we are using just the basics. Most of what Mitya said is stuff
 I've never seen before, although I am very grateful for her response, I am
 supposed to use only what the teacher taught.

 Sorry if I frustrated you.  I'm just a kid trying to learn. Any help is
 appreciated


There's no anger here, by the way. If we were unhappy with you, you'd know
;). But seriously, if we weren't just trying to help, we wouldn't reply. We
were just telling you some stuff you needed to know.

 I'm in school too, and I'm self taught. I also run a little club where I
teach people how to code, from scratch. I get where you're coming from, and
you should realise you're doing fine. We get a lot of newbies posting on
here, and I'm used to seeing code like this. The important part is that
your mistakes are small and self-contained. Those are the easy mistakes,
and they're the parts that you don't have to worry about.

FINALLY:
When you use Google Groups, your quotations look to us like this:

 This is something I said

 with lots of extra

 lines in the middle

 for no reason. Google

 Groups sucks, basically.

So please just delete the part where you quote other people. I think there
are other ways of quoting properly, but you might as well just not quote.
(When you quoted my post, the result was *literally* twice as long!)

Thanks, and good luck.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Custom alphabetical sort

2012-12-26 Thread Joshua Landau
On 25 December 2012 06:18, Dave Angel d...@davea.name wrote:

 On 12/24/2012 06:19 PM, Pander Musubi wrote:

 snip

   Thanks very much for this efficient code.

 Perhaps you missed Ian Kelly's correction of Thomas Bach's approach:

 d = { k: v for v, k in enumerate(cs) }


 def collate(x):
 return list(map(d.get, x))

 sorted(data, key=collate)

 I'd use Ian Kelly's approach.


Well, he was first to it :P


 It's not only more compact,


I take offence* here! The only difference was list(map(d.get, x)) vs
[hashindex[s] for s in string] (11 chars) and my longer naming scheme. If
you really care enough about those to sway your judgement, shame on you! ;)

* Not really

it shouldn't
 give an exception for a character not in the table.


That was a choice, not a bug. I didn't want undefined behaviour, so I
thought I'd leave it to crash on bad input than sort in a way that may be
unwanted. Even Ian Kelly gave this as way of coding it.


 At least, not for
 Python 2.x.  I'm not sure about Python 3, since it can give an exception
 comparing None to int.



Please not that this post was done in humour (but with truth) to delay
sleep. No offence to Ian or you intended ;).

Happy After-Christmas!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Custom alphabetical sort

2012-12-24 Thread Joshua Landau
On 24 December 2012 16:18, Roy Smith r...@panix.com wrote:

 In article 40d108ec-b019-4829-a969-c8ef51386...@googlegroups.com,
  Pander Musubi pander.mus...@gmail.com wrote:

  Hi all,
 
  I would like to sort according to this order:
 
  (' ', '.', '\'', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 'a',
  'A', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', 'b', 'B', 'c',
 'C',
  '?', '?', 'd', 'D', 'e', 'E', '?', '?', '?', '?', '?', '?', '?', '?',
 'f',
  'F', 'g', 'G', 'h', 'H', 'i', 'I', '?', '?', '?', '?', '?', '?', '?',
 '?',
  'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', '?', 'N', '?', 'o', 'O',
 '?',
  '?', '?', '?', '?', '?', '?', '?', '?', '?', 'p', 'P', 'q', 'Q', 'r',
 'R',
  's', 'S', 't', 'T', 'u', 'U', '?', '?', '?', '?', '?', '?', '?', '?',
 'v',
  'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z')
 
  How can I do this? The default sorted() does not give the desired result.


snip

Given all that, I would start by writing some code which turned your
 alphabet into a pair of dicts.  One maps from the code point to a
 collating sequence number (i.e. ordinals), the other maps back.
 Something like (for python 2.7):

 alphabet = (' ', '.', '\'', '-', '0', '1', '2', '3', '4', '5',
 '6', '7', '8', '9', 'a', 'A', '?', '?', '?', '?',
 [...]
 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z')

 map1 = {c: n for n, c in enumerate(alphabet)}
 map2 = {n: c for n, c in enumerate(alphabet)}

 Next, I would write some functions which encode your strings as lists of
 ordinals (and back again)

 def encode(s):
encode('foo') == [34, 19, 19]  # made-up ordinals
return [map1[c] for c in s]

 def decode(l):
decode([34, 19, 19]) == 'foo'
 return ''.join(map2[i] for i in l)

 Use these to convert your strings to lists of ints which will sort as
 per your specified collating order, and then back again:

 encoded_strings = [encode(s) for s in original_list]
 encoded_strings.sort()
 sorted_strings = [decode(l) for l in encoded_strings]


This isn't needed and the not-so-new way to do this is through .sort's key
attribute.

encoded_strings = [encode(s) for s in original_list]
encoded_strings.sort()
sorted_strings = [decode(l) for l in encoded_strings]

changes to

encoded_strings.sort(key=encode)

[Which happens to be faster /reasonable_guess]

Hence you neither need map2 or decode:

## CODE ##

alphabet = (
' ', '.', '\'', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
'A', 'ä', 'Ä', 'á', 'Á', 'â', 'Â',
 'à', 'À', 'å', 'Å', 'b', 'B', 'c', 'C', 'ç', 'Ç', 'd', 'D', 'e', 'E', 'ë',
'Ë', 'é', 'É', 'ê', 'Ê', 'è', 'È',
 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'ï', 'Ï', 'í', 'Í', 'î', 'Î', 'ì',
'Ì', 'j', 'J', 'k', 'K', 'l', 'L',
 'm', 'M', 'n', 'ñ', 'N', 'Ñ', 'o', 'O', 'ö', 'Ö', 'ó', 'Ó', 'ô', 'Ô', 'ò',
'Ò', 'ø', 'Ø', 'p', 'P', 'q', 'Q',
 'r', 'R', 's', 'S', 't', 'T', 'u', 'U', 'ü', 'Ü', 'ú', 'Ú', 'û', 'Û', 'ù',
'Ù', 'v', 'V', 'w', 'W', 'x', 'X',
 'y', 'Y', 'z', 'Z'
)

hashindex = {character:index for index, character in enumerate(alphabet)}
def string2sortlist(string):
return [hashindex[s] for s in string]

# Quickly make some stuff to sort. Let's try 200k, as that's what's
suggested.
import random
things_to_sort = [.join(random.sample(alphabet, random.randint(4, 6)))
for _ in range(20)]

print(things_to_sort[:15])

things_to_sort.sort(key=string2sortlist)

print(things_to_sort[:15])

## END CODE ##

Not-so-coincidentally, this is exactly the same as Ian Kelly's extension to
Tomas Bach's method.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: argparse -- mutually exclusive sets of arguments?

2012-11-23 Thread Joshua Landau
On 23 November 2012 18:46, Roy Smith r...@panix.com wrote:

 My command either takes two positional arguments (in which case, both
 are required):

 $ command foo bar

 or the name of a config file (in which case, the positional arguments
 are forbidden):

 $ command --config file

 How can I represent this with argparse; add_mutually_exclusive_group()
 isn't quite the right thing.  It could specify that foo and --config are
 mutually exclusive, but not (as far as I can see) the more complicated
 logic described above.


Do you need to use argparse?

If not, I've been recommending docopt due to its power and simplicity:

-START -

Command.

Usage:
command foo bar
command --config=file

Options:
foo  The egg that spams
bar  The spam that eggs
--config=file  The config that configures


from docopt import docopt

if __name__ == '__main__':
arguments = docopt(__doc__)
print(arguments)
- END 

- USAGE -
%~ python simple_docopt.py foobar barfoo
{'--config': None,
 'bar': 'barfoo',
 'foo': 'foobar'}
%~ python simple_docopt.py foobar
Usage:
simple_docopt.py foo bar
simple_docopt.py --config=file
%~ python simple_docopt.py --config=turtle.conf
{'--config': 'turtle.conf',
 'bar': None,
 'foo': None}
%~ python simple_docopt.py --config=turtle.conf not allowed
Usage:
simple_docopt.py foo bar
simple_docopt.py --config=file
--- END USAGE ---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistent behaviour os str.find/str.index when providing optional parameters

2012-11-22 Thread Joshua Landau
If you reply through Google Groups, please be careful not to do it the
traditional way as us poor saps get hundreds of lines of  added in.

I believe (but this is mere recollection) that a good way to use the site
is by selecting the text you want to quote before replying (even if it is
the whole post). I'm not too sure, though.

On 22 November 2012 18:22, Giacomo Alzetta giacomo.alze...@gmail.comwrote:

 SNIP

 My point was not to change the behaviour but only to point out this
 possible inconsistency between what str.find/str.index do and what they
 claim to do in the documentation.

 Anyway I'm not so sure that changing the behaviour would break many
 programs... I mean, the change would only impact code that was looking for
 an empty string over the string's bounds. I don't see often using the lo
 and hi parameters for find/index, and I think I never saw someone using
 them when they get out of bounds. If you add looking for the empty string I
 think that the number of programs breaking will be minimum. And even if
 they break, it would be really easy to fix them.

 Anyway, I understand what you mean and maybe it's better to keep this (at
 least to me) odd behaviour for backwards compatibility.

 SNIP

 Yeah, I understand what you say, but the logic you pointed out is never
 cited anywhere, while slices are cited in the docstring.

 SNIP



Definitely. The sentence Optional
 arguments start and end are interpreted as in slice notation. should be
 changed to something like:
 Optional arguments start and end are interpreted as in slice notation,
 unless start is (strictly?) greater than the length of S or end is smaller
 than start, in which cases the search always fails.

 In this way the 'spam'.find('', 4) *is* documented because start=len(S) -
 start and end are treated like in slice notation and 4 makes sense, while
 'spam'.find('', 5) - -1 because 5  len('spam') and thus the search fails
 and also 'spam'.find('', 3, 2) - -1 makes sense because 2  3(this edge
 case makes more sense, even though 'spam'[3:2] is still the empty
 string...).


+1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet another Python textbook

2012-11-22 Thread Joshua Landau
On 22 November 2012 22:41, Colin J. Williams c...@ncf.ca wrote:

 On 22/11/2012 1:27 PM, Ian Kelly wrote:

 On Thu, Nov 22, 2012 at 5:24 AM, Colin J. Williams c...@ncf.ca wrote:

  From my reading of the docs, it seems to me that the three following
 should
 be equivalent:

(a) formattingStr.format(values)
 with
(b) format(values, formattingStr)
 or
(c) tupleOfValues.__format__(**formattingStr

 Example:
 print('{:-^14f}{:^14d}'.**format(-25.61, 95 ))
 print(format((-25.61, 95), '{:-^14f}{:^14d}'))
 (-25.61, 95 ).__format__('{:-^14f}{:^14d}'**)

 The second fails, perhaps because values can only be a single value.
 The third fails, the reason is unclear.


 The latter two (which are more or less equivalent) fail because they are
 intended for invoking the formatting rules of a single value.  The
 string argument to each of them is not a format string, but a format
 specification, which in a format string is only the part that goes
 inside the curly braces and after the optional colon.  For example, in
 this format string:


 Thanks, this is clear.  I wish the docs made this clearer.

 You and I used __format__.  I understand that the use of double underscore
 functions is deprecated.  Is there some regular function which can achieve
 the same result?


 help(format)
format(...)
format(value[, format_spec]) - string

Returns value.__format__(format_spec)
format_spec defaults to 


 *In other words, format(a, b) is the correct way to write
a.__format__(b).*

This is in the same way that a.__add__(b) should be written a + b, or
a.__round__(b) written round(a, b).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistent behaviour os str.find/str.index when providing optional parameters

2012-11-21 Thread Joshua Landau
snipping occurs

On 21 November 2012 20:58, MRAB pyt...@mrabarnett.plus.com wrote:

 On 2012-11-21 19:25, Hans Mulder wrote:

 On 21/11/12 17:59:05, Alister wrote:

 On Wed, 21 Nov 2012 04:43:57 -0800, Giacomo Alzetta wrote:

  'spam'.find('', 5)

 -1

 Now, reading find's documentation:

  print(str.find.__doc__)

 S.find(sub [,start [,end]]) - int

 Return the lowest index in S where substring sub is found,
 such that sub is contained within S[start:end].  Optional arguments
 start and end are interpreted as in slice notation.

 Return -1 on failure.



  why would you be searching for an empty string?
 what result would you expect to get from such a search?


 In general, if

  needle in haystack[ start: ]

 return True, then you' expect

  haystack.find(needle, start)

 to return the smallest i = start such that

  haystack[i:i+len(needle)] == needle

 also returns True.

 The only other consistent position would be that spam[5:]
 should raise an IndexError, because 5 is an invalid index.



  You'd expect that given:

 found = string.find(something, start, end)

 if 'something' present then the following are true:

 0 = found = len(string)

 start = found = end


I don't think I agree.

I think *only* the second holds, but start defaults to 0 and end to
len(string), which is consistent with Han's method and thus conclusion.

Of course this is merely opinion and practicality beats purity, but it
seems logical, considering the slicing synonym.

Even if functionally this remains unchanged, the docstring should be edited
to reflect this oddity.

(I'm assuming here that 'start' and 'end' have already been adjusted
 for counting from the end, ie originally they might have been negative
 values.)

 The only time that you can have found == len(string) and found == end
 is when something ==  and start == len(string).

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


Re: Yet another Python textbook

2012-11-21 Thread Joshua Landau
On 21 November 2012 22:17, Chris Angelico ros...@gmail.com wrote:

 On Thu, Nov 22, 2012 at 4:03 AM, Colin J. Williams c...@ncf.ca wrote:
  On 20/11/2012 4:00 PM, Chris Angelico wrote:
  To the OP: jmf has an unnatural hatred of Python 3.3 and PEP 393
  strings. Take no notice; the rest of the world sees this as a huge
  advantage. Python is now in a VERY small group of languages (I'm aware
  of just one other) that have absolutely proper Unicode handling *and*
  efficient string handling.
 
  ChrisA
 
  It's interesting to see that someone else finds the format function to
 be a
  pain.  Perhaps the problem lies with the documentation.

 Hang on, what? I'm not sure where the format function comes in. I was
 referring to the underlying representation.

 That said, though, I'm just glad that %-formatting is staying. It's an
 extremely expressive string formatting method, and exists in many
 languages (thanks to C's heritage). Pike's version is insanely
 powerful, Python's is more like C's, but all three are compact and
 convenient.

 str.format(), on the other hand, is flexible. It strikes me as rather
 more complicated than a string formatting function needs to be, but
 that may be a cost of its flexibility.


Since we've decided to derail the conversation...

{}.format() is a blessing an  % () should go. % has no relevance to
strings, is hard to get and has an appalling* syntax. Having two syntaxes
just makes things less obvious, and the right choice rarer.

str.format is also really easy. I don't understand what makes you disagree.

Easy vs easier:

 %s %s %s % (1, 2, 3)
'1 2 3'

 {} {} {}.format(1, 2, 3)
'1 2 3'

Easy vs easier:

 You have %(spam)s spam and %(eggs)s eggs! % {spam: 43, eggs: 120}
'You have 43 spam and 120 eggs!'

 You have {spam} spam and {eggs} eggs!.format(spam=43, eggs=120)
OR
 You have {spam} spam and {eggs} eggs!.format(**{spam: 43, eggs:
120})
'You have 43 spam and 120 eggs!'

Eh...? vs easy:

 Thing %s has state %+o! % (#432, 14)
'Thing #432 has state +16!

 Thing {} has state {:+o}!.format(#432, 14)
'Thing #432 has state +16!'

*Additionally*, a = str.format is much *better* than a = str.__mod__.

I have a piece of code like this:
{fuscia}{{category__name}}/{reset}{{name}} {green}{{version}}{reset}:\n
 {{description}}

Which *would* have looked like this:
%(fuscia)s%%(category__name)s/%(reset)s%%(name)s
%(green)s%%(version)s%(reset)s:\n%%(description)s

Which would have parsed to something like:
'FUSCIA{category__name}/RESET{name} GREEN{version}RESET:\n{description}'
and
'FUSCIA%(category__name)s/RESET%(name)s GREEN%(version)sRESET:\n
 %(description)s'

Can you seriously say you don't mind the %(name)ss in this?

* A {} is in the {} vs A %s is in the %s?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 10 sec poll - please reply!

2012-11-20 Thread Joshua Landau
On 20 November 2012 16:19, Dave Angel d...@davea.name wrote:

 On 11/20/2012 11:09 AM, John Gordon wrote:
  In 3d71f175-164e-494c-a521-2eaa5679b...@googlegroups.com Michael
 Herrmann michael.herrm...@getautoma.com writes:
 
  What, in your view, would be the most intuitive alternative name?
  keyboard_input().
 

 Well, since Python already has input() and raw_input(), it would then be
 clear that keyboard_input() would take some kind of data from the
 keyboard, not send it.


keyboard_output()
output_keys()
?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proxy??

2012-11-20 Thread Joshua Landau
On 20 November 2012 14:48, Jorge Alberto Diaz Orozco 
jaoro...@estudiantes.uci.cu wrote:

 Hi there.
 Does anyone knows how to manage headers using a simple proxy???
 I'm doing this but It gives me problems In some pages.


I don't know the answer, but I do know you'd get more favour if you
explained whatproblems and In some pages refer to.


 import SocketServer
 import SimpleHTTPServer
 import urllib2

 PORT = 

 class Proxy(SimpleHTTPServer.**SimpleHTTPRequestHandler):
 def do_GET(self):
 try:
 print self.path
 self.copyfile(urllib2.urlopen(**self.path), self.wfile)
 except:
 print 'error',self.path

 httpd = SocketServer.ForkingTCPServer(**('127.0.0.1', PORT), Proxy)
 print serving at port, PORT
 httpd.serve_forever()

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


Re: Greedy parsing of argparse/positional arguments

2012-11-20 Thread Joshua Landau
On 20 November 2012 10:02, Johannes Bauer dfnsonfsdu...@gmx.de wrote:

 Hi list,

 I have a problem with Python3.2's argparse module. The following sample:

 parser = argparse.ArgumentParser(prog = sys.argv[0])
 parser.add_argument(-enc, metavar = enc, nargs = +, type = str,
 default = [ utf-8 ])
 parser.add_argument(pattern, metavar = pattern, type = str, nargs = 1)
 parser.add_argument(filename, metavar = filename, type = str, nargs =
 1)
 args = parser.parse_args(sys.argv[1:])

 illustrates the problem: I want to be able to specify an encoding one or
 more times (multiple encodings possible), have a pattern and a filename
 as the last two arguments.

 This works as long as I don't specify '-enc' on the command line. If I
 do, for example

 ./foo -enc myencoding mypattern myfile

 The -enc greedy parser seems to capture [myencoding, mypattern,
 myfile], leaving nothing for pattern and filename, yielding an error:

 ./foo: error: too few arguments

 How can I force positional arguments to take precedence over optional
 arguments? I could exclude them from the parsing altogether, but that
 would make them not appear in the help page (which I'd like to avoid).


My first suggestion would be to change -enc to --enc,

my second to make the input --enc FIRST --enc SECOND --enc THIRD...
pattern filename (action=append, remove nargs=+),

and my third to use docopt (docopt.org) where the example you have posted
is just:
-

My Program.

Usage:
my_prog.py [--enc=encoding...] pattern filename

Options:
--enc encoding  [default: UTF-8]



from docopt import docopt
arguments = docopt(__doc__)

--*
Note that this will not work if you don't take my first two suggestions.


An alternative is like mplayer's, where it accepts comma-delimited lists:

my_prog.py --enc UTF-8,ASCII,FOO,BAR pattern% filename.txt

Where you will parse the comma-delimited list afterwards. This is only
worth it if you expect a lot of encodings.


Q: How about actually answering the question?
A: I don't know how, short of parsing it manually.


* Small differences exist
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary of Functions

2012-11-15 Thread Joshua Landau
On 15 November 2012 17:13, Chris Kaynor ckay...@zindagigames.com wrote:

 On Thu, Nov 15, 2012 at 8:04 AM, Kevin Gullikson
 kevin.gullik...@gmail.com wrote:
  Hi all,
 
  I am trying to make a dictionary of functions, where each entry in the
  dictionary is the same function with a few of the parameters set to
 specific
  parameters. My actual use is pretty complicated, but I managed to boil
 down
  the issue I am having to the following example:
 
  In [1]: def test_fcn(a, x):
 ...: return a*x
 ...:
 
  In [2]: fcn_dict = {}
 
  In [3]: for i in [1,2,3]:
 ...: fcn_dict[i] = lambda x: test_fcn(i, x)
 ...:

 In this case, I would recommend using functools.partial instead of a
 lambda.
 It will solve this problem (although MRAB's solution will as well), is
 trivially faster (likely insignificant in any real application), and,
 IMO, clearer:

 for i in [1,2,3]:
 fcn_dict[i] = functools.partial(test_fcn, i)

 Note that this only works if you are either only specifying the first
 arguments by position, or specifying arguments by keyword. There is no
 way to specify the second argument by position; you'd have to pass it
 as a keyword argument.


Another way to do this is by making a factory function:

 def factor_multiplier(factor):
... def factor_multiply(target):
... return factor * target
... return factor_multiply
...

Testing it:

 trippler = factor_multiplier(3)
 trippler
function factor_multiplier.locals.factor_multiply at 0x7ffeb5d6db90
 trippler(10)
30
 doubler = factor_multiplier(2)
 doubler(15)
30
 doubler(trippler(1))
6


Solving your problem:

 function_dict = {}
 for i in range(100):
... function_dict[i] = factor_multiplier(i)
...

 function_dict[42](2)
84
 function_dict[20](3)
60


This is definitely longer that Chris' approach, but it's more powerful
overall. It's worth learning and using both.

In a sense, you were close, but you were just not catching the variable:

 function_dict.clear()
 for i in range(100):
... function_dict[i] = (lambda i: lambda x: x*i)(i)
...
 function_dict[19](2)
38

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


Re: Python questions help

2012-11-15 Thread Joshua Landau
On 15 November 2012 01:47, su29090 129k...@gmail.com wrote:

 I brought a python book and i'm a beginner and I read and tried to do the
 questions and I still get it wrong.

 How to create a program that reads an uspecified number of integers, that
 determines how many positive and negative values have been read, and
 computes the total and average of the input values(not counting zeroes). My
 program have to end with the input 0 and have to display the average as a
 floating-point number.


Think about the requirements.
For example, you need here:
* Some sort of loop to take in an unlimited number of integers
* Some way to take in integers
 * Some way of stopping when a 0 is entered
* Some way of finding the total and averages
* Some way of putting it all together

If you can solve some of these sub-tasks and just need help with others,
tell us what you've done and we'll help you work out the rest.

Use nested loops that display the following patterns in separate programs:

 1
 12
 123
 1234
 12345
 123456


What are the patterns here?
1st: 1 - 2 - 3 - 4 - ...
2nd: 1 - 12 - 123 - 1234 - ...

How would you do these? How would you combine them?


 123456
 12345
 1234
 123
 12
 1


How would you change the above to do this instead?


  1
 21
321
   4321
  54321
 654321


How would you change it to do this?


 Write a program that computes the following summation:

 1/ 1+square root of 2 + 1/ 1+square root of 2 + square root of 3 + 1/
 1+square root of 3 + square root of 4...+ 1/ 1+square root of 624 + square
 root of 625


You've probably written this wrong. You've got:
(1/ 1) + (square root of 2) +  (1/ 1) + (square root of 2) + (square root
of 3) + (1/ 1) + (square root of 3) + (square root of 4)... +  (1/ 1) +
(square root of 624) + (square root of 625)

Which you can write as: 1 + root(2) + 1 + root(2) + root(3) + 1 + root(3) +
root(4) + ... + 1 + root(624) + root(625)
As (1/1) is 1. You probably need brackets somewhere. I've never seen any
equation like this, so I can't guess at what you really wanted.

Do you know how to find the square root? Just search square root python
if you do not.
Then put it in a loop.


 How to  a program to draw a chessboard using range?


 I imagine you want to use loops, where a range is what you loop over.

O X O X O X O X
X O X O X O X O
O X O X O X O X
X O X O X O X O
O X O X O X O X
X O X O X O X O
O X O X O X O X
X O X O X O X O

It's 8 by 8, so you want to loop 8 times for one dimension and 8 times for
the other. How would you use range to do this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Question regarding running .py program

2012-11-14 Thread Joshua Landau
Steven, whilst I hold you in high regard, this post seems spurned by bias.

I would urge you to reconsider your *argument*, although your *position*
has merit.

On 14 November 2012 23:07, Steven D'Aprano 
steve+comp.lang.pyt...@pearwood.info wrote:

 On Wed, 14 Nov 2012 10:20:13 -0800, rurpy wrote:

  On 11/14/2012 06:35 AM, Chris Angelico wrote:
  I stand by what I said. Members, plural, of this list. I didn't say
  all members of, ergo the word some is superfluous, yet not needful,
  as Princess Ida put it.
 
  Then you would have no problem I suppose with Australians are racists
  because some Australians are racist and I didn't say all?

 Speaking as an Australian, I wouldn't have a problem with that, because
 Australians *are* racist. To the degree that we can talk about a
 national character, the national character of Australia is racist, even
 if many Aussies aren't, and many more try not to be.

 In any case, your example is provocative. Here's a less provocative
 version:

 [paraphrase]
 Then you would have no problem I suppose with People have two legs
 because some people have two legs and I didn't say all?
 [end paraphrase]


Ahem? Seriously?

With rounding, all people *do* have two legs. That's not fair. In fact, the
idea that most users of this list ban Google Groups is probably false.

Additionally, being provocative isn't actually  weakness of his argument,
although it is a distraction. He asked if you had a problem with it on
the basis that if it was a fair claim you would not, in order to show that
it was not a fair claim. That would *imply* his correctness.

How about this(?):
People have brown hair.

  As a user of GG, Usenet and email lists I claim you are wrong.  GG does
  NOT require quite a bit of extra work.  If it did, I wouldn't use it.
  For occasional posters, GG is EASIER.  (It would be even easier if
  Google would fix their execrable quoting behaviour but as I showed, it
  is easy to work around that.) I think you are ignoring setup time and a
  number of other secondary factors, things that are very significant to
  occasional posters, in your evaluation of easy.

 I don't understand why you suggest counting setup time for the
 alternatives to Google Groups, but *don't* consider setup time for Google
 Groups. You had to create a Google Account didn't you? You've either put
 in your mobile phone number -- and screw those who don't have one -- or
 you get badgered every time you sign in. You do sign in don't you?


That's not fair, either, on the basis that almost everyone has a Google
account. Additionally, who signs in manually any more [*wink*]?


 For *really* occasional posters, they might not even remember their
 Google account details from one post to the next. So they have to either
 create a new account, or go through the process of recreating it. Why do
 you ignore these factors in *your* evaluation of easy?


They might not remember their Email account either. This seems to be a
really contrived point.


 We all do it -- when we talk about easy or difficult, we have an
 idealised generalised user in mind. Your idealised user is different from
 Chris' idealised user. You are both generalising. And that's *my*
 generalisation.


All of this is really beside the point, anyway. He claimed the he used it
because *he* found it easier. And there was claim that there were good
reasons to use Google Groups. If you claim that his point is invalid
because it only talks about *his* idealised user, you've only invalidated
your own point.


 Even if you are right that Google Groups is easier for some users, in my
 opinion it is easy in the same way as the Dark Side of the Force.
 Quicker, faster, more seductive, but ultimately destructive.


How so?


   As for best, that is clearly a matter of opinion. The very fact that
  someone would killfile an entire class of poster based on a some others'
  posts reeks of intolerance and group-think.

 Intolerance? Yes. But group-think? You believe that people are merely
 copying the group's prejudice against Google Groups. I don't think they
 are. I think that the dislike against GG is group consensus based on the
 evidence of our own eyes, not a mere prejudice.


Consensus? Hrm...A synonym of consensus is unanimity. This argument's
existence basically disproves that.


 The use of Google Groups
 is, as far as I can tell, the single most effective predictor of badly
 written, badly thought out, badly formatted posts, and a common source of
 spam.

 As for intolerance, you say that like it is that a bad thing. Why should
 people have to tolerate bad behaviour? Google Groups *encourages* bad
 behaviour.


I think this is a valid thing to say. I agree largely because it's the
user's choice to read and reply to this list. Calling someone helpful in a
community intolerant because you think they could be nicer would be a bit
intolerant yourself.


 Should we tolerate spam because any spam filter might
 occasionally throw away a legitimate 

Re: List comprehension for testing **params

2012-11-12 Thread Joshua Landau
Just a few tricks you may have missed:

On 12 November 2012 10:48, Ulrich Eckhardt
ulrich.eckha...@dominolaser.comwrote:

 Am 11.11.2012 23:24, schrieb Cantabile:

if required.intersection(params.**keys()) != required:


if required.issubset(params):


missing = required - set(params.keys())


missing = required.difference(params)


raise Exception(missing arguments {}.format(
', '.join(missing)))



(untested)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List comprehension for testing **params

2012-11-12 Thread Joshua Landau
On 12 November 2012 13:23, Joshua Landau joshua.landau...@gmail.com wrote:

 Just a few tricks you may have missed:

  On 12 November 2012 10:48, Ulrich Eckhardt 
 ulrich.eckha...@dominolaser.com wrote:

 Am 11.11.2012 23:24, schrieb Cantabile:

 if required.intersection(params.**keys()) != required:


 if required.issubset(params):


*Ahem*: if *not* required.issubset(params):




missing = required - set(params.keys())


 missing = required.difference(params)


raise Exception(missing arguments {}.format(
', '.join(missing)))



 (untested)

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


Re: Help building a dictionary of lists

2012-11-12 Thread Joshua Landau
On 12 November 2012 22:26, NJ1706 nickj1...@googlemail.com wrote:

 Chaps,

 I am new to Python  have inherited a test harness written in the language
 that I am trying to extend.

 The following code shows how dictionaries holding lists of commands are
 handled in the script...

  Start of Code_1 

SNIP

  End of Output_1 

 Note that dict1 contains only the details of the particlare test, see YYY.

 This is a very cut down script compared to the real thing  in reality
 there are many more entries in the TestList and also there are many
 dictionaries. To make the script simpler to extend I would like to remove
 the need to manually create each of the dictionaries.

 After some reading around I found the dict.fromkeys() method  came up
 with the following...

  Start of Code_2 

 SNIP

  End of Ouput_2 

 This almost does what I want but dict2[Test_2] displayed at XXX contains
 the value for Test_1 as well as Test_2. I would be very grateful if someone
 can help me to get the line marked with XXX to be the same as YYY in code_1
 at the start.

 I am using Python 2.6.8 on Cygwin 1.7.17 but get the same results on
 CentOS 6.3


First of all, thank you for being thorough. It's always a help. *However*,
a minimalistic will be read faster usually, so you may want to crop down
what you have. Additionally, it can result in you solving it yourself!

The problem is as follows

{1:[], 2:[], 3:[]} does not equal dict.fromkeys([1, 2, 3], [])

You could have worked out this much very quickly, as it is the only thing
you change in the code.

Let's look:
 {1:[], 2:[], 3:[]}
{1: [], 2: [], 3: []}
 dict.fromkeys([1,2,3], [])
{1: [], 2: [], 3: []}


Oh no! They are the same! What has happened?
Well, they're *not*. In the first example each of the lists are *unique*:

 dct = {1:[], 2:[], 3:[]}
 dct[1] is dct[2]
False
 dct[1] is dct[3]
False
 dct[2] is dct[3]
False


In the second, they are all *the same list*:

 dct = dict.fromkeys([1,2,3], [])
 dct[1] is dct[2]
True
 dct[1] is dct[3]
True
 dct[2] is dct[3]
True


What does this mean?

 a = []
 b = []
 c = b

 a is b
False
 b is c
True

 a.append(1)
 b.append(2)
 c.append(3)

 a
[1]
 b
[2, 3]
 c
[2, 3]


Because b and c in this are *the same*, changing one *is* changing the
other. Hence, you've appended *two* things to b and c, but only one to a.

In your code you use .append on the items in your dict. This will have the
same problem as with a, b and c above.

If you want to make a dict, you can use a dictionary comprehension. I
assume you understand what a list comprehension is. If not, look here:
http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

Dict comprehension:
{i:[] for i in [Test 1, Test 2, Test 3]}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help building a dictionary of lists

2012-11-12 Thread Joshua Landau
On 12 November 2012 22:26, NJ1706 nickj1...@googlemail.com wrote:

 # List of tests
 TestList = (
 'Test_1',
 'Test_2'
 )


Note that TestList is a *tuple*, not a list.

You normally would want to write test_names instead of TestList for
several reasons:

* Unless it's a class, Python prefers lowercase_names_with_underscores (or
sometimes camelCaseNamesThatLookLikeThis)
* Python tries not to care what type you have - that your names are in a
list is less important than that you can loop over it
* It's definitely not a list. A list would look like this:
TestList = [
'Test_1',
'Test_2'
]



Additionally, your comment here is somewhat pointless.  The code says
*exactly* what your comment does, so why write it twice?

# List of tests
Don't need

# Initialise the dictionary of lists
Don't need

# Loop through the list of tests
Don't need

# Append to the list for each instance
Not very helpful. If you comment here, you should explain *why* you are
looping, not *that* you are looping. You write append, but *what* and,
more importantly,*why*?

# Initialise our string list
Don't need

# Build string list
Again, whilst it is nice to know more, you are not saying *what*
you are building. What is the *purpose* of the list?

# Convert to string
Don't need

# Assign to target list
Don't need


A good comment might just be one at the start that explains the goal, or
one inside that explains the *point* of a piece of code. Consider these two
commented pieces of code:


# Define a function that takes a, b and c
def f(a, b, c):

# Set s to ((the square of b) minus four times a times c) all to the
power of 0.5
s = (B**2 - 4 * a * c) ** 0.5

# Return the calculated values
return (- b + s) / (2 * a), (- b - s) / (2 * a)


Vs.


# Finds x where the equation ax**2 + bx + c makes 0
def f(a, b, c):
# Use the quadratic equation (
http://en.wikipedia.org/wiki/Quadratic_equation)

# s is the square root part of the equation (where x**0.5 is the square
root of x)
s = (B**2 - 4 * a * c) ** 0.5

# Return two values because there are two possible solutions
return (- b + s) / (2 * a), (- b - s) / (2 * a)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Division matrix

2012-11-12 Thread Joshua Landau
On 13 November 2012 01:00, Cleuson Alves cleuso...@gmail.com wrote:

 Hello, I need to solve an exercise follows, first calculate the inverse
 matrix and then multiply the first matrix.


This list isn't to give answers for homeworks, and this sounds like one. We
*do* give help to those who have a specific problem and who preferably show
that they are trying to help up help them.


 I await help.


For what?! You haven't asked a question.
1) What do you need. Answer precisely, preferably giving an example output
for the input you want
2) What techniques have you tried? You have given code below in an
extremely un-obvious manner. What does it do, crash? Is it the wrong
output? What is wrong about the output?
3) What do you *think* has gone wrong? What about the output seems to be
wrong?


 Thank you.
 follows the code below incomplete.


On the basis that we can get some foreign people who maybe don't have
English as a commonly used language, muddled grammar isn't that big deal.
However, when asking for help it is worth checking that you've asked in a
clear way.


 m = [[1,2,3],[4,5,6],[7,8,9]]
 x = []
 for i in [0,1,2]:
 y = []
 for linha in m:
 y.append(linha[i])
 x.append(y)

 print x
 [[1, 4, 7], [2, 5, 8], [3, 6, 9]]


Is this the right output? Is this what you *meant* by inverse? As Ian Kelly
(who is undoubtedly more learned in this area) said, this is a transpose,
so you have just swapped the one axis with another.


 def ProdMatrix(x,b):
 tamL = len(x)
 tamC = len(x[0])
 c = nullMatrix(tamL,tamC)
 for i in range(tamL):
 for j in range(tamC):
 val = 0
 for k in range(len(b)):
 val = val + x[i][l]*b[k][j]
 c[i][j]
 return c


You haven't given the full code. This crashes because we don't have
nullMatrix defined. It would be nice if we had something we could try to
run.

Then, the error is: NameError: global name 'l' is not defined. On the
line val = val + x[i][l]*b[k][j] you use a variable l which doesn't
exist. What should you be using, or should you have created it?

*Then* you get an output of pure 0s. This is because you forgot to put your
result into c, your new matrix.
You probably just forgot to finish the line c[i][j], which does nothing
now.

You're actually really close on the second part. I have no idea if you're
doing what you want for the first part, but it's not what's traditionally
called an inverse.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-dimensional list initialization

2012-11-07 Thread Joshua Landau
On 7 November 2012 11:11, Oscar Benjamin oscar.j.benja...@gmail.com wrote:

  On Nov 7, 2012 5:41 AM, Gregory Ewing greg.ew...@canterbury.ac.nz
 wrote:
 
  If anything is to be done in this area, it would be better
  as an extension of list comprehensions, e.g.
 
[[None times 5] times 10]
 
  which would be equivalent to
 
[[None for _i in xrange(5)] for _j in xrange(10)]

 I think you're right that the meaning of list-int multiplication
 can't/shouldn't be changed if this way.

 A multidimensional list comprehension would be useful even for people who
 are using numpy as it's common to use a list comprehension to initialise a
 numpy array.

 A more modest addition for the limited case described in this thread could
 be to use exponentiation:

  [0] ** (2, 3)
 [[0, 0, 0], [0, 0, 0]]

Hold on: why not just use multiplication?

 [0] * (2, 3)

is an error now, and it makes total sense. Additionally, it's not breaking
the no copy -- _ever_ rule because none of the lists existed before. The
values inside the list would be by reference, as before, so lst * (x,)
would be the same as lst * x if x is an integer.

*I* would use this a lot. This is the first thing on this thread that makes
a lot of sense to me.

We do have to think of the potential problems, though. There are definitely
some. For one, code that relies on lst * x throwing an error would break.
It may confuse others - although I don't see how.

But I don't see any big problems, so I really do like this idea.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-dimensional list initialization

2012-11-07 Thread Joshua Landau
*Spoiler:* You've convinced me.

On 7 November 2012 14:00, Oscar Benjamin oscar.j.benja...@gmail.com wrote:

 On 7 November 2012 13:39, Joshua Landau joshua.landau...@gmail.com
 wrote:
  On 7 November 2012 11:11, Oscar Benjamin oscar.j.benja...@gmail.com
 wrote:
  A more modest addition for the limited case described in this thread
 could
  be to use exponentiation:
 
   [0] ** (2, 3)
  [[0, 0, 0], [0, 0, 0]]
 
  Hold on: why not just use multiplication?
 
  [0] * (2, 3)
 
  is an error now, and it makes total sense. Additionally, it's not
 breaking
  the no copy -- _ever_ rule because none of the lists existed before.
 The
  values inside the list would be by reference, as before, so lst * (x,)
 would
  be the same as lst * x if x is an integer.

 The problem is that this operation is asymmetric. Currently int/list
 multiplication is commutative so that:

 ['a', 'b'] * 2 == 2 * ['a', 'b']


I see. I agree that that is a valid point. Remember, though, that we could
just keep this behaviour:

[0] * (2, 3) == (2, 3) * [0]


 If you use this kind of multiplication what happens to the other
 cases? e.g. what do you give for:

  [0] * [2, 3]


Nothing. If you allowed lists to multiply this time, why not with your
suggestion? We should require a tuple and a list.


  [2, 3] * [0]


Same.


  (2, 3) * [0]


== [0] * (2, 3)


  (2, 3) * (4, 5)


Nothing.


 and so on. Although Python does not guarantee commutativity of
 multiplication in general I think that since for lists it has always
 been commutative it would be bad to change that.


Agreed


 Exponentiation is expected to be asymmetric and is currently unused so
 there is no ambiguity. The problem is if someone has already
 subclassed list and added an exponentiation method.


How is that a problem? They just wont get the functionality.


That said, losing:
[0] * (2, 3) == [0] * [2, 3]
would mean losing duck-typing in general. *Thus*, I fully agree with your
choice of exponentiation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-dimensional list initialization

2012-11-07 Thread Joshua Landau
On 7 November 2012 23:55, Andrew Robinson andr...@r3dsolutions.com wrote:

  On 11/07/2012 05:39 AM, Joshua Landau wrote:

  A more modest addition for the limited case described in this thread
 could be to use exponentiation:

  [0] ** (2, 3)
 [[0, 0, 0], [0, 0, 0]]

  I'm against over using the math operators, for the reason that matrix
 and vector algebra have meanings mathematicians desire (rightly) to
 maintain.  Numpy users might find matricies overloaded to do these things
 in the future -- and then it becomes unclear whether an initialization is
 happening or a mathematical operation. I think it best just not to set up
 an accident waiting to happen in the first place.


I'm going to say right now that I'm very much fond of
the exponentiation proposal.

Multiplication on Numpy arrays is already completely disjoint to
multiplication on lists, and that is probably completely disjoint to all
sorts of mathematical meanings. I don't personally feel that anyone who
knows what [0] * 3 is would *assume* (although they may suppose)
that exponentiation will be a maths operator.

When I saw [0] ** (2, 3), I knew what it did before I read anything else. I
know I had the context of the posts above, so it isn't a fair comparison,
but it seems really obvious an extension. It's so closely linked to * (if
not for the ambiguities, I would have preferred multiplication) that it
makes total sense. Even if you think of 4 ** 5 as 4 * 4, 5 times, there
is a direct mental link to what is happening.

  Hold on: why not just use multiplication?

  [0] * (2, 3)

 Would you consider that better than [0].nest(2).nest(3) ? or [0].nest(2,3)
 ?
 (I'm against multiplication, but I'm still interested in what you find
 attractive about it.)


Yes.

Having [0] * 2 with a distinct but fundamentally the same (it's just gotten
extra dimensions) partner that is called in a very similar way is a good
thing.

I'd feel equally unhappy with 4 * 3 partnering with (4).pow(3)* as I
would with your .nest(2, 3) and I like the iterated ones even less because
I don't see it as obviously possible for them to even work.

[0].nest(2) - [[0], [0]] ?
[[0], [0]].nest(3) - [[0,0,0], [0,0,0]] ???
(what about 3d?)

* Even if you could write that as 4.pow(3) because floats didn't exist or
something.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-dimensional list initialization

2012-11-05 Thread Joshua Landau
On 5 November 2012 06:27, Demian Brecht demianbre...@gmail.com wrote:

  a = [None] * 4
  a[0] = 'a'
  a
 ['a', None, None, None]

  m = [[None] * 4] * 4
  m[0][0] = 'm'
  m
 [['m', None, None, None], ['m', None, None, None], ['m', None, None,
 None], ['m', None, None, None]]

 Is this expected behaviour and if so, why? In my mind either result makes
 sense, but the inconsistency is what throws me off.


z = [[None] * 4]

goes to

z = [x, x, x, x]
where x = [y]
where y = None

AND THEN

z[0] = 2

means

z = [p, x, x, x]
where p = 2

AND

z[1][0] = 3

means

x = [q]
where q = 3
hence z = [2, [3], [3], [3]]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __unicode__() works, unicode() blows up.

2012-11-04 Thread Joshua Landau
On 4 November 2012 13:32, Roy Smith r...@panix.com wrote:

 Environment:
   Python-2.7.3
   Ubuntu Precise
   mongoengine 0.6.20

 I have a class which includes a __unicode__() method:

 class User(mongoengine.Document):
 def __unicode__(self):
 return self.username

 If I create an instance of this class by calling the constructor
 directly, self.username is None.  When I pass that to unicode(), it
 blows up.  However, calling __unicode__() directly, works as expected:

  u = User()
  print u.username
 None

  print u.__unicode__()
 None

  print unicode(u)
 Traceback (most recent call last):
   File stdin, line 1, in module
 TypeError: coercing to Unicode: need string or buffer, NoneType found

 What's going on here?  I thought
 (http://docs.python.org/2/library/functions.html#unicode) the latter two
 calls should be identical, but obviously they're not.


 class Foo:
... def __unicode__(self): return Bar # NOT Unicode
...
 Foo().__unicode__()
'Bar'
 unicode(Foo())
u'Bar'

unicode(x) calls x.__unicode__() *and then* coerces the result to Unicode.

None cannot be coerced to Unicode.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT Questions

2012-10-28 Thread Joshua Landau
On 16 October 2012 18:23, Ian Kelly ian.g.ke...@gmail.com wrote:

 On Tue, Oct 16, 2012 at 9:21 AM, Demian Brecht demianbre...@gmail.com
 wrote:
  There's a small light somewhere deep down that says maybe this is just
  someone quite misdirected. A brief search shows that he has multiple
  domains, all with the same type of design. I would be hard pressed to
 think
  that someone would go to that extent just to troll a list.
 
  Meh, maybe it's my good nature :P

 My theory for a while now has been that Mr. Hutto is probably an
 enterprising teenager.  His desire to build a web development company
 is sincere and should be encouraged, but his lack of experience is
 readily apparent, as is his rather crude behavior on list.


I feel necessity  to argue against this point.

It is a common thing to stereotype teens in this way - but, being teen
myself, I feel one should try to avoid it. It's painful to watch every time
someone claims he can't be a teenager - his spelling/grammar is too good
or any derivation of it, as with the inverse concept that the uneducated
are always teenagers.

i have techers who type lke this, and I have teachers who type
very professionally.
I have peers of my age group who meticulously craft
their online conversations, n i no BFFs who dun b like that.

How someone speaks on the internet seems to me proportional almost entirely
to their intelligence*, not to their wisdom. Sure, there is an age where
one, no matter how bright, will speak like trash, but this normally
coincides with an inability to speak well, too. Most older teenagers have
as good a grasp on language as they will ever learn, so it hardly applies
to them.

* Note that I speak not of IQ or problem-solving ability, but more of a
general social intelligence that can be seen in almost any poster on this
list.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A desperate lunge for on-topic-ness

2012-10-23 Thread Joshua Landau
On 23/10/2012, Dennis Lee Bieber wlfr...@ix.netcom.com wrote:
 On Mon, 22 Oct 2012 16:02:34 -0600, Ian Kelly ian.g.ke...@gmail.com
 declaimed the following in gmane.comp.python.general:

 On my wishlist for Python is a big, fat SyntaxError for any variable
 that could be interpreted as either local or nonlocal and is not
 explicitly declared as either.  It would eliminate this sort of
 confusion entirely and make code that shadows nonlocal variables much
 more readable.

   Which now makes code dependent upon changes to some imported modules
 if someone is foolish enough to use the

   from xyz import *

 notation...

   I'd be very displeased if working code with local names suddenly
 fails because some third-party package was updated.

   Yes, I prefer not to use the from...* notation, but how many
 tutorials (especially of GUI toolkits, with their dozens of constants)
 illustrate using the wildcard?

I'm not particularly fond (or disliking) of the proposal, but we
already make changes to the structure of locals/globals and so forth
when someone does from something import *. Disabling checks when
it is used is totally reasonable.

Additionally, SyntaxError: import * only allowed at module level.
This means, as far as I grasp, one should never *manage* to create an
ambiguity here. Ian already stated this idea should (due to
neccessity) be disabled for possible globals.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can we append a list with another list in Python ?

2012-10-23 Thread Joshua Landau
On 23/10/2012, inshu chauhan insidesh...@gmail.com wrote:
 can we append a list with another list in Python ? using the normal routine
 syntax but with a for loop ??

I assume you want to join two lists.

You are corrrect that we can do:

 start = [1, 2, 3, 4]
 end = [5, 6, 7, 8]

 for end_item in end:
 start.append(end_item)

 print(start)
[1, 2, 3, 4, 5, 6, 7, 8]


However, it is markedly repetitive, no?
This is a common enough operation that there is a shortcut to find out about it.

If you want to find out what methods there are, try help(...). I
can't stress this enough.

 help(start)
Help on list object:

class list(object)
 |  list() - new empty list
 |  list(iterable) - new list initialized from iterable's items
 |
 |  Methods defined here:
 |
 |  __add__(...)
 |  x.__add__(y) == x+y
...
 |  append(...)
 |  L.append(object) -- append object to end
...
 |  extend(...)
 |  L.extend(iterable) -- extend list by appending elements from
the iterable
...

So list.extend seems to do exactly this!

You can always check the documentation
http://docs.python.org/tutorial/datastructures.html.
An lo! The documentation says start.extend(end) is _equivilant_ to
start[len(start):] = end.

Why?

Well, this uses the slicing syntax.

 start[:3]
[1, 2, 3]
 start[3:]
[4]
 start[2:3]
[3]

Wonderously, all these really say are ranges in the list. Hence, you
can put lists in their place.

start[len(start):] = end means start[-1:] = end, so what you're
doing is saying the empty end part of the list is actually this new
list. Hopefully that makes sense.

Finally, there is another method. Instead of *changing* the list, you
can make a new list which is equal to the others added together.

 new = start + end

___

Theses methods all have their own upsides. If you want to change the
list, use .extend(). If you want to change the list, but by putting
the new list somewhere inside the old one, use slicing:

 start = [1, 2, 3, 4]
 end = [5, 6, 7, 8]

 start[2:2] = end
 print(start)
[1, 2, 5, 6, 7, 8, 3, 4]

Looping is good for when you want to generate the extra items as you go along.

Finally, if you want to keep the old list or use these inline, use +.

___

Note that, being in the unfortunate position of away from an
interpreter, none of my examples are copy-pastes. Hence they may be
wrong :/

# Not checked for errors, typos and my friends messing with it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can we append a list with another list in Python ?

2012-10-23 Thread Joshua Landau
On 23 October 2012 12:07, Jean-Michel Pichavant jeanmic...@sequans.comwrote:

 - Original Message -

  Thankyou.. but my problem is different than simply joining 2 lists
  and it is done now :)


 A lot of people though you were asking for joining lists, you description
 was misleading.

 I'll take a guess: you want to flatten a list of list.
 Nested list comprehensions can do the trick.

 aList =[[1,5], [2,'a']]
 [item for sublist in aList for item in sublist]

 ...
 [1, 5, 2, 'a']

 I find it rather difficult to read though.


We have a library function for this, in the one-and-only itertools.

 listoflists = [list(range(x, 2*x)) for x in range(5)]
  listoflists
 [[], [1], [2, 3], [3, 4, 5], [4, 5, 6, 7]]
  from itertools import chain
   list(chain.from_iterable(listoflists))
 [1, 2, 3, 3, 4, 5, 4, 5, 6, 7]


It does exactly what it says... fast and easy-to-read.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can we append a list with another list in Python ?

2012-10-23 Thread Joshua Landau
On 23 October 2012 21:03, Joshua Landau joshua.landau...@gmail.com wrote:

 On 23 October 2012 12:07, Jean-Michel Pichavant jeanmic...@sequans.comwrote:

 - Original Message -

  Thankyou.. but my problem is different than simply joining 2 lists
  and it is done now :)


 A lot of people though you were asking for joining lists, you description
 was misleading.

 I'll take a guess: you want to flatten a list of list.
 Nested list comprehensions can do the trick.

 aList =[[1,5], [2,'a']]
 [item for sublist in aList for item in sublist]

 ...
 [1, 5, 2, 'a']

 I find it rather difficult to read though.


 We have a library function for this, in the one-and-only itertools.

  listoflists = [list(range(x, 2*x)) for x in range(5)]
  listoflists
 [[], [1], [2, 3], [3, 4, 5], [4, 5, 6, 7]]
  from itertools import chain
   list(chain.from_iterable(listoflists))
 [1, 2, 3, 3, 4, 5, 4, 5, 6, 7]


 It does exactly what it says... fast and easy-to-read.


Note that I think what he really wanted is to go from

a, b, c = [list(x) for x in (range(10), range(11, 20), range(21, 30))]

to

 list(range(30))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can we append a list with another list in Python ?

2012-10-23 Thread Joshua Landau
On 23 October 2012 21:06, Joshua Landau joshua.landau...@gmail.com wrote:

 On 23 October 2012 21:03, Joshua Landau joshua.landau...@gmail.comwrote:

 On 23 October 2012 12:07, Jean-Michel Pichavant 
 jeanmic...@sequans.comwrote:

 - Original Message -

  Thankyou.. but my problem is different than simply joining 2 lists
  and it is done now :)


 A lot of people though you were asking for joining lists, you
 description was misleading.

 I'll take a guess: you want to flatten a list of list.
 Nested list comprehensions can do the trick.

 aList =[[1,5], [2,'a']]
 [item for sublist in aList for item in sublist]

 ...
 [1, 5, 2, 'a']

 I find it rather difficult to read though.


 We have a library function for this, in the one-and-only itertools.

  listoflists = [list(range(x, 2*x)) for x in range(5)]
  listoflists
 [[], [1], [2, 3], [3, 4, 5], [4, 5, 6, 7]]
  from itertools import chain
   list(chain.from_iterable(listoflists))
 [1, 2, 3, 3, 4, 5, 4, 5, 6, 7]


 It does exactly what it says... fast and easy-to-read.


 Note that I think what he really wanted is to go from

 a, b, c = [list(x) for x in (range(10), range(11, 20), range(21, 30))]

 to

 list(range(30))


UNDO! UNDO! UNDO!

I *meant *to say:

Note that I think what he really wanted is to go from

a, b, c = [list(x) for x in (range(10), range(11, 20), range(21, 30))]

to

 [a, b, c]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get each pair from a string.

2012-10-21 Thread Joshua Landau
On 21 October 2012 19:33, Vincent Davis vinc...@vincentdavis.net wrote:

 I am looking for a good way to get every pair from a string. For example,
 input:
 x = 'apple'
 output
 'ap'
 'pp'
 'pl'
 'le'

 I am not seeing a obvious way to do this without multiple for loops, but
 maybe there is not :-)
 In the end I am going to what to get triples, quads... also.


The best way for *sliceable* objects is probably your way. However, not all
items can be sliced.

One way is this:

Let us say you have a string:

  my_string = abcdefghijklmnopqrstuvwxyz
  my_string
 'abcdefghijklmnopqrstuvwxyz'


If you are to zip that, you get a zip object

   zip(my_string)
 zip object at 0x1b67f38


So you want to turn it back into a list:

  list(zip(my_string))
 [('a',), ('b',), ('c',), ('d',), ('e',), ('f',), ('g',), ('h',), ('i',),
 ('j',), ('k',), ('l',), ('m',), ('n',), ('o',), ('p',), ('q',), ('r',),
 ('s',), ('t',), ('u',), ('v',), ('w',), ('x',), ('y',), ('z',)]


So why would you want zip anyway? Let us see what it does with two inputs.

  list(zip(my_string, my_string))
 [('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd'), ('e', 'e'), ('f', 'f'),
 ('g', 'g'), ('h', 'h'), ('i', 'i'), ('j', 'j'), ('k', 'k'), ('l', 'l'),
 ('m', 'm'), ('n', 'n'), ('o', 'o'), ('p', 'p'), ('q', 'q'), ('r', 'r'),
 ('s', 's'), ('t', 't'), ('u', 'u'), ('v', 'v'), ('w', 'w'), ('x', 'x'),
 ('y', 'y'), ('z', 'z')]


I see. It goes over the first and takes an item, then over the second and
takes an item, and then puts them together. It then does this for all the
items in each.

All we want to do is offset the second item:

  list(zip(my_string, my_string[1:]))
 [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f'), ('f', 'g'),
 ('g', 'h'), ('h', 'i'), ('i', 'j'), ('j', 'k'), ('k', 'l'), ('l', 'm'),
 ('m', 'n'), ('n', 'o'), ('o', 'p'), ('p', 'q'), ('q', 'r'), ('r', 's'),
 ('s', 't'), ('t', 'u'), ('u', 'v'), ('v', 'w'), ('w', 'x'), ('x', 'y'),
 ('y', 'z')]


And then convert the results to single strings:

  [.join(strs) for strs in zip(my_string, my_string[1:])]
 ['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi', 'ij', 'jk', 'kl', 'lm',
 'mn', 'no', 'op', 'pq', 'qr', 'rs', 'st', 'tu', 'uv', 'vw', 'wx', 'xy',
 'yz']


And this can be generalised in a more complicated way:

  [.join(strs) for strs in zip(*[my_string[n:] for n in range(4)])]
 ['abcd', 'bcde', 'cdef', 'defg', 'efgh', 'fghi', 'ghij', 'hijk', 'ijkl',
 'jklm', 'klmn', 'lmno', 'mnop', 'nopq', 'opqr', 'pqrs', 'qrst', 'rstu',
 'stuv', 'tuvw', 'uvwx', 'vwxy', 'wxyz']


Which can work with iterables:

  from itertools import islice
  [.join(strs) for strs in zip(*[islice(my_string, n, None) for n in
 range(4)])]
 ['abcd', 'bcde', 'cdef', 'defg', 'efgh', 'fghi', 'ghij', 'hijk', 'ijkl',
 'jklm', 'klmn', 'lmno', 'mnop', 'nopq', 'opqr', 'pqrs', 'qrst', 'rstu',
 'stuv', 'tuvw', 'uvwx', 'vwxy', 'wxyz']


This will be much *faster* for short sequences made from massive strings
and much *slower* for long sequences made from medium-sized strings.
The first method *slices*, which copies a part of the whole string. This is
slow for large copies.
The second method* loops until it reaches the start*. This is slow when the
start is a long way in.

However, if you want to use slice-able items, the best way is the one
you've already worked out, as it does no extra copying or looping.
-- 
http://mail.python.org/mailman/listinfo/python-list


<    1   2   3   4   5   >