Re: Beginner question

2013-06-04 Thread Mitya Sirenef

On 06/04/2013 07:53 AM, Carlos Nepomuceno wrote:

On 4 Jun 2013 12:28,  Carlos Nepomuceno carlosnepomuc...@outlook.com wrote:

 [...]
  What's going on? Is there a way to make dict() to resolve the 
variables?

 Well yes.
 dict(**{a:0,b:1})
 The dict() constructor makes a dictionary from keyword arguments. So 
you just have to feed it keyword arguments using **.

 And if you're in a bad day,
 dict(**locals())

 That's exactly the same!
 dict(**{a:0,b:1})=={a:0,b:1}
 True

 Are there any benefits from using dict() instead of {}?



Other than what Steven already mentioned, a big advantage is that it's
easier to make a dict if you have a lot of keys that are valid
identifiers, and it's more readable, to boot:

dict(red=1, blue=2, orange=3, violet=4, crimson=5, ...)

VS.

{'red':1, 'blue':2, 'orange':3, 'violet':4, 'crimson':5, ...}

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Although the most acute judges of the witches and even the witches
themselves, were convinced of the guilt of witchery, the guilt nevertheless
was non-existent. It is thus with all guilt.  Friedrich Nietzsche

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


Re: howto remove the thousand separator

2013-04-14 Thread Mitya Sirenef

On 04/14/2013 02:57 PM, pyth0n3r wrote:

Hi,
 I came across a problem that when i deal with int data with ',' as 
thousand separator, such as 12,916, i can not change it into int() or 
float().

 How can i remove the comma in int data?
 Any reply will be appreciated!!

 Best,
 Chen




I would do int(num.replace(',', ''))

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

When a friend succeeds, I die a little.  Gore Vidal

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


Re: Functional vs. Object oriented API

2013-04-12 Thread Mitya Sirenef

On 04/12/2013 10:19 AM, Roy Smith wrote:

As part of our initial interview screen, we give applicants some small
coding problems to do.  One of the things we see a lot is what you could
call Java code smell.  This is our clue that the person is really a
Java hacker at heart who just dabbles in Python but isn't really fluent.
It's kind of like how I can walk into a Spanish restaurant and order
dinner or enquire where the men's room is, but everybody knows I'm a
gringo as soon as I open my mouth.

It's not just LongVerboseFunctionNamesInCamelCase().  Nor is it code
that looks like somebody bought the Gang of Four patterns book and is
trying to get their money's worth out of the investment.  The real dead
giveaway is when they write classes which contain a single static method
and nothing else.

That being said, I've noticed in my own coding, it's far more often that
I start out writing some functions and later regret not having initially
made it a class, than the other way around.



I've absolutely noticed the same thing for myself, over and over
again. I can't remember writing a class that I've regretted is not
a few functions, although it must have happened a few times.   -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Typing letters slowly using sys

2013-04-05 Thread Mitya Sirenef

On 04/05/2013 10:04 AM, mattgrav...@gmail.com wrote:

I am using sys to give the effect that I am typing letters slowly. Basically what I want 
to have happen is have it show Loading.. with the word loading appearing 
instantly and then the periods appearing slowly, as most loading screens do.
This is what I have.

dots = ('')
for x in dots:
  sys.stdout.write(x)
  sys.stdout.flush()
  time.sleep(0.2)

I cannot for the life of me figure out how to get the dots to appear on the same line as 
Loading. Every way that I have attempted, the word Loading appears and then 
the dots appear on the next line.


If you're printing in 2.x, you can do:

print Loading,

in 3.x,

print(Loading, end='')

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: In defence of 80-char lines

2013-04-04 Thread Mitya Sirenef

On 04/03/2013 09:36 PM, Steven D'Aprano wrote:

Although PEP 8 is only  compulsory for the Python standard library, many

 users like to stick to PEP 8 for external projects.

 http://www.python.org/dev/peps/pep-0008/

 With perhaps one glaring exception: many people hate, or ignore, PEP 8's
 recommendation to limit lines to 80 characters. (Strictly speaking, 79
 characters.)


 Here is a good defence of 80 char lines:

 http://wrongsideofmemphis.com/2013/03/25/80-chars-per-line-is-great/





I think one important consideration that wasn't mentioned yet is one of
Python principles: practicality beats purity.

I can see how someone could have a preference for 80 char width, there
are some valid reasons to prefer it. I think other reasons to prefer
(slightly) longer width outweigh them, but that's a judgement call.

However, if you work with other people's code, you will surely run into
all kinds of widths, 100, 120, 140+, etc. For someone with a rigid 80
limit, it's a real pain. I feel that somewhere around 100 width, must be
the reasonable middle ground: for me at soft 105 limit, editing 80 limit
code feels almost like my own, in fact the range of 80-110 is going to
fit neatly into my setup without any hassle.

120 is minimal hassle: I adjust Gvim to take a bit more space, resize
browser to take a bit less space and I'm set.

140 is a bit uncomfortable, but I generally notice that even when people
code to 140 limit, nearly all of their lines are actually going to be at
about 120 limit at most, with only a few offenders, so it's trivial to
adjust to 120 limit.

If people go over 140, that conclusively proves they're smoking crack
and the code needs to be refactored anyway.


I also find the argument about 80 width used in books a little odd. I
read webpages with 100-140 widths all the time with not the slightest
problem. As far as I know, no browser in existence lets you uniformly
adjust all pages to wrap at 80 limit except for lynx/links; if it was
hard to read at wider sizes, surely there would be at least one
graphical browser that would give that option (and get all the user
share from other browsers?)

Code is rather different from regular text. I would not want my books
formatted like this:

The story had held us, round the fire, sufficiently breathless, but
except the obvious
remark that it was
gruesome, as,

on Christmas Eve in an old house, a strange tale should essentially be,
I remember no comment uttered till somebody
happened to say that
it was the only case he had met in which such a visitation
had fallen on a
child.


Nor am I (warning: understatement) particularly enthusiastic about
editing code that looks like (formatted to 72 width):


try: request = self.request_class(environ) except UnicodeDecodeError:
logger.warning('Bad Request (UnicodeDecodeError)',
exc_info=sys.exc_info(), extra={ 'status_code': 400, }) response =
http.HttpResponseBadRequest() else: response =
self.get_response(request)

response._handler_class = self.__class__

try: status_text = STATUS_CODE_TEXT[response.status_code] except
KeyError: status_text = 'UNKNOWN STATUS CODE' status = '%s %s' %
(response.status_code, status_text) response_headers = [(str(k), str(v))
for k, v in response.items()] for c in response.cookies.values():
response_headers.append((str('Set-Cookie'), str(c.output(header=''
start_response(force_str(status), response_headers) return response


 -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: In defence of 80-char lines

2013-04-03 Thread Mitya Sirenef

On 04/03/2013 09:59 PM, Andrew Berg wrote:

While I agree that not having a  line take up hundreds of characters is a

 good thing, 80 is really arbitrary in 2013 and having any self-imposed
 hard limit is silly. When you put a single 4- or 5-character word on a
 new line because you don't want to go over 80 (or 120 or whatever), the
 code is /less/ readable. A better guideline is to make new lines as
 necessary to make things more readable rather than blindly stick to some
 hard limit and say it's more readable just because.

 Also, IMO, 80 is far too limiting and I find 120-130 much better. Then
 again, I like small font sizes and avoid lower resolution screens like
 the plague.


I have to agree. To some degree, it's a matter of taste: for me, 80c
limit looks ugly to the extreme, at least in Django; but 140+ looks even
uglier, and the longer line is, the uglier it looks. The optimal size
for Django code is a 105 char soft limit -- by soft limit I mean that
under 105 it's always one line, 105-110 I decide on a case-by-case basis
and over 110 is always split.

So my preference is: 105  120-130  140  80  140+

The trade-off is that on one hand, the code is more readable when a
single line is a single operation, from a cognitive standpoint, when
you're thinking about the logic of the function as a whole, or a subset
of a function if it's too long (which it shouldn't be, right?) On the
other hand, even if your monitor is wide, you probably still want to fit
in the browser window and the terminal window, and as the blog author
rightly notes, really long lines do get harder to read.

Again, I mostly work with Django and I suspect if I worked in regular
Python I would possibly gravitate towards 95-100 limit.

I find the blog author's point about fitting more text nonsensical: you
can obviously fit more text PER LINE if lines are longer! And you can
quite easily fit two 120-130 wide gvim screens on a modern monitor with
room to spare.

I'm sure eyesight acuity also figures into this: I prefer to work
without glasses -- otherwise my eyes get tired after a couple of hours;
but this means I can't see code on my second monitor. If I could, I
might have preferred having browser and terminal on one monitor and Gvim
with slightly longer width limits than I use now.

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The Bible is literature, not dogma.  George Santayana

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


Re: Doing both regex match and assignment within a If loop?

2013-03-29 Thread Mitya Sirenef

On 03/29/2013 04:27 AM, Peter Otten wrote:

(2)

 import re

 class Matcher:
 def __call__(self, expr, line):
 result = self.match = expr.match(line)
 return result
 def __getattr__(self, name):
 return getattr(self.match, name)


Perhaps it's a little simpler to do this?


self.match =  expr.match(line)

 return self.match


 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Frisbeetarianism is the belief that when you die, your soul goes up on
the roof and gets stuck.  George Carlin

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


Re: Help me pick an API design (OO vs functional)

2013-03-27 Thread Mitya Sirenef

On 03/27/2013 05:10 AM, Michael Herrmann wrote:

At the very least, for  small dialogs it's sipmpler to do:

 
  with press(CTRL + 's'):
   write(test.txt, into=File name)
   click(Save)
 I think what the context manager approach really has going for itself
 is the syntactic structure it gives to scripts, that makes it easy to
 see what is going on in which window. Semantically, however, I think
 the fit of this approach has some rough edges: The fact that there
 needs to be some special treatment for ALT + TAB, that actions such as
 `press` sometimes return values that are needed to continue the
 script and so on. It really has its appeal, but I think it's a bit too
 special and intricate to be used by a broad audience.



I think alt-tab has to be special in any case. Regular alt-tab would act
like the GOTO statement. As a programmer looking at a script you have no
idea where you just alt-tabbed to without possibly looking through
dozens of lines of previous code.

Keypresses that start a new window also seem pretty special to me.
They're inherently special. After all, the essential function of a
windowing system is when a new window is created, which means subsequent
operations have an entirely different meaning, in a text editor del
key will delete a character, in a file manager del key will delete a
file!

But, as I mentioned, if you can get away with treating simple dialogs
implicitly (and I don't see why you can't, at this point), that'd be the
preferred way for me.

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The condition of man is already close to satiety and arrogance, and
there is danger of destruction of everything in existence.
- a Brahmin to Onesicritus, 327 BC, reported in Strabo's Geography

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


Re: Help me pick an API design (OO vs functional)

2013-03-26 Thread Mitya Sirenef

On 03/26/2013 05:38 AM, Michael Herrmann wrote:

On Tuesday, March 26, 2013  12:40:45 AM UTC+1, Mitya Sirenef wrote:

 ...

 I think I would prefer context managers. I don't think it's a big
 problem for
 win users because this behaviour would be one of the first things 
documented

 in the start guide and would be all over example scripts, so a new user
 missing
 or forgetting it is not a realistic scenario.

 The advantages are that it's explicit, blocks are indented and it's
 impossible to
 miss which window is the action applied to, and at the same time 
actions are

 short and easy to type and read.

 Thank you for your reply. What do you think of Chris Angelico's points?


At the __exit__, further commands are no longer routed to that window;
if it was a nested context, window is switched to the outer context,
WHEN there are commands in it (i.e. on the first command). This seems
pretty intuitive to me:

with notepad1:
^S
with notepad2:
^S
write('something')




 He wrote:
 What happens at the __exit__ of the context manager? What happens if
 context managers are nested? I'd be inclined to the simpler option of
 an explicit switch (since focus doesn't really stack and it'd feel
 weird for focus to *sometimes* switch away when you're done working
 with one window), though the context manager syntax does have its
 advantages too.

 What I am most afraid of: that the window that's currently the 
context disappears:

 notepad = start(Notepad)
 with notepad:
 press(ALT + TAB)
 write(Am I in Notepad now?)


Alt-tab needs to be handled by a wrapper function that gives you the
object of the window you've switched to:

otherwin = alt_tab()
with otherwin:
...

If window is changed within 'with' block, the rest of block should be
ignored. Perhaps there could also be a way to switch this behaviour off,
for the entire script or for current block only.




 What do you think of designs #3 and #4?

 notepad_1 = start(Notepad)
 notepad_2 = start(Notepad)
 switch_to(notepad_1)
 write(Hello World!)
 press(CTRL + 'a', CTRL + 'c')
 switch_to(notepad_2)
 press(CTRL + 'v')

 notepad_1 = start(Notepad)
 notepad_2 = start(Notepad)
 notepad_1.activate()
 write(Hello World!)
 press(CTRL + 'a', CTRL + 'c')
 notepad_2.activate()
 press(CTRL + 'v')

 I somehow prefer activate over focus as in my feeling, you'd 
normally say that you focus *on* something, so it should be called 
focus_on or give_focus[_to]. Can you say, in everyday English, that 
you focus a window? I'm not a native speaker so maybe my feeling is 
misguided.



These are ok, too, but I feel it's much easier to send commands to a
wrong window vs. context managers. The same command in a different
window can have vastly different and dangerous effect. In other python
code that's generally not common at all, and would be bad style:

lst = lst1
lst.append('x')
del lst[3]
lst.insert(0, 'a')
lst = lst2
del lst[2]
lst.append('y')
lst = lst3
lst.insert(0, 'x')
lst += [1,2]


I think current window should also be acquired explicitly:

with get_current_window():
type(some kind of snippet)

For usage when a command should apply to all types of windows.

HTH, -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Food is an important part of a balanced diet.
Fran Lebowitz

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


Re: Help me pick an API design (OO vs functional)

2013-03-26 Thread Mitya Sirenef

On 03/26/2013 10:59 AM, Michael Herrmann wrote:

On Tuesday, March 26, 2013  2:41:38 PM UTC+1, Mitya Sirenef wrote:

 ...
 At the __exit__, further commands are no longer routed to that window;
 if it was a nested context, window is switched to the outer context,
 WHEN there are commands in it (i.e. on the first command). This seems
 pretty intuitive to me:

 with notepad1:
  ^S
  with notepad2:
  ^S
  write('something')


 ...
   What I am most afraid of: that the window that's currently the
   context disappears:

   notepad = start(Notepad)
   with notepad:
   press(ALT + TAB)
   write(Am I in Notepad now?)


 Alt-tab needs to be handled by a wrapper function that gives you the
 object of the window you've switched to:

 otherwin = alt_tab()
 with otherwin:
  ...

 If window is changed within 'with' block, the rest of block should be
 ignored. Perhaps there could also be a way to switch this behaviour off,
 for the entire script or for current block only.


   What do you think of designs #3 and #4?
   ...

 These are ok, too, but I feel it's much easier to send commands to a
 wrong window vs. context managers. The same command in a different
 window can have vastly different and dangerous effect. In other python
 code that's generally not common at all, and would be bad style:

 lst = lst1
 lst.append('x')
 del lst[3]
 lst.insert(0, 'a')
 lst = lst2
 del lst[2]
 lst.append('y')
 lst = lst3
 lst.insert(0, 'x')
 lst += [1,2]

 I think current window should also be acquired explicitly:

 with get_current_window():
  type(some kind of snippet)

 For usage when a command should apply to all types of windows.

 I was skeptical of your suggestion at first but trying it out on an 
example script made me see its appeal:


 notepad_main = start(Notepad)
 with notepad_main:
 write(Hello World!)
 save_dialogue = press(CTRL + 's')
 with save_dialogue:
 write(test.txt, into=File name)
 click(Save)
 click(Close)

 Forcing the library user to always use the with ... seems like 
overkill though. I think the gained precision does not justify this 
burden on the library user. Hm



I don't see why that's a big deal, I've used AHK extensively and in my
experience you don't switch windows all that often. I think it's best to
optimize to have easy to type and read commands while you're working in
the same window.

I think you could argue that dialogs that belong to the main window
should be handled implicitly, though. I think for other windows it'd
definitely be good to use context managers, but for quick/simple dialogs
it's too much hassle, although for large, complex dialogs that have
inner tabs and require a lot of work, it again starts to make sense.

At the very least, for small dialogs it's sipmpler to do:

with press(CTRL + 's'):
write(test.txt, into=File name)
click(Save)


 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Calamities are of two kinds: misfortunes to ourselves, and good fortune 
to others.

Ambrose Bierce, The Devil's Dictionary

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


Re: Help me pick an API design (OO vs functional)

2013-03-25 Thread Mitya Sirenef

On 03/25/2013 03:29 PM, Michael Herrmann wrote:

Hello everyone,

my name is Michael, I'm the lead developer of a Python GUI automation library for Windows 
called Automa: http://www.getautoma.com. We want to add some features to our library but 
are unsure how to best expose them via our API. It would be extremely helpful for us if 
you could let us know which API design feels right to you.

Our API already offers very simple commands for automating the GUI of a Windows 
computer. For example:

from automa.api import *
start(Notepad)
write(Hello World!)
press(CTRL + 's')
write(test.txt, into=File name)
click(Save)
click(Close)

When you execute this script, Automa starts Notepad and simulates key strokes, 
mouse movements and clicks to perform the required commands. At the moment, 
each action is performed in the currently active window.

We do not (yet) have a functionality that allows you to explicitly switch to a 
specific window. Such a functionality would for instance make it possible to 
open two Notepad windows using the start(...) command, and copy text between 
them.

One API design would be to have our start(...) function return a Window (say) 
object, whose methods allow you to do the same operations as the global functions 
write(...), press(...), click(...) etc., but in the respective window. In this design, 
the example of operating two Notepad windows could be written as

notepad_1 = start(Notepad)
notepad_2 = start(Notepad)
notepad_1.write(Hello World!)
notepad_1.press(CTRL + 'a', CTRL + 'c')
notepad_2.press(CTRL + 'v')

The problem with this design is that it effectively duplicates our API: We want to keep our 
global functions because they are so easy to read. If we add methods to a new Window 
class that do more or less the same, we feel that we are violating Python's principle that There should 
be one - and preferably only one - obvious way to do it.

An alternative design would be to make the window switching an explicit action. One way of doing 
this would be to add a new global function, say switch_to or activate, that 
takes a single parameter that identifies the window to be switched to. We could still have 
start(...) return a Window object, that could then be passed to our function:

notepad_1 = start(Notepad)
notepad_2 = start(Notepad)
switch_to(notepad_1)
write(Hello World!)
press(CTRL + 'a', CTRL + 'c')
switch_to(notepad_2)
press(CTRL + 'v')

Maybe our Window objects could also be used as context managers:

notepad_1 = start(Notepad)
notepad_2 = start(Notepad)
with notepad_1:
write(Hello World!)
press(CTRL + 'a', CTRL + 'c')
with notepad_2:
press(CTRL + 'v')

As a final idea, switching could also be done as a method of the Window class:

notepad_1 = start(Notepad)
notepad_2 = start(Notepad)
notepad_1.activate()
write(Hello World!)
press(CTRL + 'a', CTRL + 'c')
notepad_2.activate()
press(CTRL + 'v')

It would be extremely helpful for us if you could let me know which way of using the API you would prefer. If 
you opt for an explicit version, how would you call the respective method? activate / 
switch_to / focus or something else?

Thank you so much!

Best wishes,
Michael



I think I would prefer context managers. I don't think it's a big 
problem for

win users because this behaviour would be one of the first things documented
in the start guide and would be all over example scripts, so a new user 
missing

or forgetting it is not a realistic scenario.

The advantages are that it's explicit, blocks are indented and it's 
impossible to

miss which window is the action applied to, and at the same time actions are
short and easy to type and read.

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: What am I doing wrong in this simple tkinter example?

2013-03-16 Thread Mitya Sirenef

On 03/16/2013 10:53 AM, Yves S. Garret wrote:

Hi all, I'm well into Python  Programming for the Absolute Beginner in order 
to
 become more acquainted with the language. However, when I got to page 
304 and

 did my first example:

 http://bin.cakephp.org/view/1107093008

 And this is the error that I'm getting:

 http://bin.cakephp.org/view/399711843

 This is the code that came with the book:

 http://bin.cakephp.org/view/514822432


 What I don't understand is, why am I getting that error? I've done 
diff -w
 and the code looks for the most part the same. What am I doing wrong 
when I

 put the application together?


The error is that indexes are supposed to be integers, instead you have
a text string:

That's not the correct password, so I can't s hare the secret with you.


-m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The existence of any evil anywhere at any time absolutely ruins a total
optimism.  George Santayana

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


Re: What am I doing wrong in this simple tkinter example?

2013-03-16 Thread Mitya Sirenef

On 03/16/2013 11:16 AM, Yves S. Garret wrote:

On Saturday, March 16, 2013 11:10:07 AM UTC-4, Mitya Sirenef wrote:

On 03/16/2013 10:53 AM, Yves S. Garret wrote:


Hi all, I'm well into Python  Programming for the Absolute Beginner in order 
to

   become more acquainted with the language. However, when I got to page

304 and

   did my first example:

  

   http://bin.cakephp.org/view/1107093008

  

   And this is the error that I'm getting:

  

   http://bin.cakephp.org/view/399711843

  

   This is the code that came with the book:

  

   http://bin.cakephp.org/view/514822432

  

  

   What I don't understand is, why am I getting that error? I've done

diff -w

   and the code looks for the most part the same. What am I doing wrong

when I

   put the application together?





The error is that indexes are supposed to be integers, instead you have

a text string:



That's not the correct password, so I can't s hare the secret with you.





  -m





--

Lark's Tongue Guide to Python: http://lightbird.net/larks/



The existence of any evil anywhere at any time absolutely ruins a total

optimism.  George Santayana

*shrug*

In the example that I have posted from the book it works just fine.  I also used
this batch file to help me along.

longevity.py
pause

Hence the question mark over my head at the moment :) .


You are giving a message to the delete call, but delete call
needs an integer to work. In the book, it's not a delete call
but an insert call that's why it works there.

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Switch statement

2013-03-10 Thread Mitya Sirenef

On 03/10/2013 10:16 AM, Joseph L. Casale wrote:

I have a switch statement  composed using a dict:



 switch = {
 'a': func_a,
 'b': func_b,
 'c': func_c
 }
 switch.get(var, default)()


 As a result of multiple functions per choice, it migrated to:



 switch = {
 'a': (func_a1, func_a2),
 'b': (func_b1, func_b2),
 'c': (func_c, )
 }



 for f in switch.get(var, (default, )):
 f()


 As a result of only some of the functions now requiring unique 
arguments, I presume this
 needs to be migrated to a if/else statement? Is there a way to 
maintain the switch style with

 the ability in this scenario to cleanly pass args only to some functions?


 Thanks,
 jlc

You can have two dictionaries; you can also add a flag:
'a': (WITHARG, funca1, funca2)

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The cure for boredom is curiosity. There is no cure for curiosity.
Dorothy Parker

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


Re: suggestions for improving code fragment please

2013-02-28 Thread Mitya Sirenef

On 02/28/2013 02:47 PM, The Night Tripper wrote:

Hi there

 I'm being very dumb ... how can I simplify this fragment?


 if arglist:
 arglist.pop(0)
 if arglist:
 self.myparm1 = arglist.pop(0)
 if arglist:
 self.myparm2 = arglist.pop(0)
 if arglist:
 self.myparm3 = arglist.pop(0)
 if arglist:
 self.parm4 = arglist.pop(0)
 # ...

 Thanks
 J^n




I often use this convenience function:

def getitem(seq, index, default=None):
Get item from an `seq` at `index`, return default if index out of 
range.

try : return seq[index]
except IndexError : return default


If you're ok with setting myparm values to default None, you can do:

self.myparm1, self.myparm2, self.myparm3, self.myparm4 = \
(getitem(arglist, n) for n in range(4))


If you only want to set them when they are in arglist:

for n in range(4):
val = getitem(arglist, n)
if val is not None:
setattr(self, myparm%d % (n+1), val)

-m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

“So many books, so little time.”
― Frank Zappa

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


Re: Store a variable permanently

2013-02-28 Thread Mitya Sirenef

On 02/28/2013 10:35 PM, eli m wrote:
So i have a variable called  funds that i want to store the value of even after the program is 
exited. My funds variable holds the total value of funds i have. I add a 
certain number of funds each time i run the program by entering how much 
i want to add. How would i store the funds variable to keep its value?



Take a look at these examples from shelve module doc page:

http://docs.python.org/2/library/shelve.html#example

-m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Fashion is something barbarous, for it produces innovation without reason
and imitation without benefit.  George Santayana

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


Re: Do you feel bad because of the Python docs?

2013-02-27 Thread Mitya Sirenef

On 02/27/2013 08:22 AM, Antoine Pitrou wrote:

Mitya Sirenef msirenef  at lightbird.net writes:

 I think the issue with python documentation is that it ignores the 95/5
 rule: 95% of people who land on a module's page are only looking for 5%
 of its information.

 The 95/5 rule is generally a fallacy which ignores that the 5% which the
 readers are expecting to learn about is not the same 5% from reader 
to reader.

 (*)

 Which means that in the end you would really want a diversity of HOWTOs
 targeted at different usages of the stdlib. But it is a lot of work to
 write *and* maintain.

 (*) cf. http://www.joelonsoftware.com/items/2006/12/09.html

 Regards

 Antoine.



It would be absurd on my part to claim that they're precisely the same
5%. But then again, they don't have to be. Consider that some topics are
covered in the official tutorial while others are omitted -- the authors
of the tutorial were following the same rough 95/5 concept and the idea
that some readers will find stuff they don't need in the tutorial while
at the same time not finding some of what they DO need -- did not stop
them from writing the tutorial, nor does it mean the tutorial is not
useful. -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Do you feel bad because of the Python docs?

2013-02-26 Thread Mitya Sirenef

On 02/26/2013 07:54 AM, Steven D'Aprano wrote:

One week ago, JoePie91 wrote  a blog post challenging the Python

 community and the state of Python documentation, titled:

 The Python documentation is bad, and you should feel bad.

 http://joepie91.wordpress.com/2013/02/19/the-python-documentation-is-bad-
 and-you-should-feel-bad/

 It is valuable to contrast and compare the PHP and Python docs:

 http://php.net/manual/en/index.php
 http://www.python.org/doc/

 There's no doubt that one of PHP's strengths, perhaps its biggest
 strength, is the good state of documentation. But should we feel bad
 about Python's docs? I don't think that either the Python documentation
 or community is as bad as JoePie91 suggests. (Well, I won't speak for 
the

 people on Freenode's #python. It took me approximately three minutes to
 be banned from there, with no warning or explanation.)

 Another response to the blog post, by one of the core developers:

 http://blog.briancurtin.com/posts/why-i-dont-feel-so-bad.html





I think the issue with python documentation is that it ignores the 95/5
rule: 95% of people who land on a module's page are only looking for 5%
of its information. So ideally it'd be separated in two different pages
or two sections of the same page, something like:

===

Hi, chances are you are the 95% of people who isn't interested in the
intricacies, obscure edge cases et cetera. Here are the few common use
cases for this module:

...

...

...

===

Hi, the section above obviously did not suit your needs, so you must be
in the 5% who has no choice but to either read through or at least
glance through, or use search, to find what you need in the following
umpteen million of screenfuls:

... * 100


===

Why doesn't Python do that? Quite simply, it's a lot more work: you have
to separate most useful parts from the rest, which involves judgement
calls and will cause some disagreement and ultimately won't be perfect.
Once done, two separate sections need to be mainained and kept in sync.
It's important that they don't contradict each other.

Right now places like SO and mailing list act like the first section I
described. The issue is that they're not always up to date and not
guaranteed to be correct, are not in a consistent style and depth, are
not centralized.

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Is life not a thousand times too short for us to bore ourselves?
Friedrich Nietzsche

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


Re: Do you feel bad because of the Python docs?

2013-02-26 Thread Mitya Sirenef

Subject:   Re: Do you feel bad because of the Python docs?  To:
python-list@python.org Cc:Bcc:
-=-=-=-=-=-=-=-=-=# Don't remove this line #=-=-=-=-=-=-=-=-=- On
 02/26/2013 09:00 PM, Terry Reedy wrote:

On 2/26/2013 1:58 PM, Mitya  Sirenef wrote:


 I think the issue with python documentation is that it ignores the
 95/5 rule: 95% of people who land on a module's page are only looking
 for 5% of its information. So ideally it'd be separated in two
 different pages or two sections of the same page, something like:

 
===



 Hi, chances are you are the 95% of people who isn't interested in the
 intricacies, obscure edge cases et cetera. Here are the few common
 use cases for this module:

 ...

 ...

 ...

 
===



 Hi, the section above obviously did not suit your needs, so you must
 be in the 5% who has no choice but to either read through or at least
 glance through, or use search, to find what you need in the following
 umpteen million of screenfuls:

 ... * 100


 
===



 Why doesn't Python do that?

 We are not literally going to write text like that, but we did
 recently re-organized the doc for one module specifically to put the
 most commonly used stuff (about the 'convenience' functions) at the
 top instead of buried where it was.


Yes, I didn't mean it would be literally worded like that :-).





 Quite simply, it's a lot more work: you have to separate most useful
 parts from the rest, which involves judgement calls and will cause
 some disagreement and ultimately won't be perfect. Once done, two
 separate sections need to be mainained and kept in sync.

 In the case above, there is no duplication to be kept in sync. More
 the problem is that people working of the docs tend to either leave or
 move on to code. Report like 'This section is unclear' are not too
 helpful either.



I don't think that would work in the general case, for all modules,
because the 'inclusive' section should not be missing items that
logically belong there. For example, if I'm looking through string
formatting subsection, it would be confusing if some items were missing
because they were moved to the top together with other items from
different subsections.

In addition, the 'inclusive' section would have some advanced notes that
would not be included in the first section, even if items themselves may
be there.


For example, let's take timedelta section:

http://docs.python.org/2/library/datetime.html#timedelta-objects


At the end of this section there is a dozen lines of helpful examples.

I think vast majority of visitors need these examples (not a complete
list, just an example of examples), and it would be ideal if they were
shown at the very top of the page, without the need to scroll down:



from datetime import  timedelta, datetime

 three_days = timedelta(days=3)
 datetime.now()
datetime.datetime(2013, 2, 26, 21, 45, 44, 371334)

datetime.now() +  three_days

datetime.datetime(2013, 3, 1, 21, 45, 34, 427403)

old_date =  datetime(2013, 2, 10)

 if datetime.now() - old_date  timedelta(days=10):
...  print(It's been more than 10 days since %s % old_date)
It's been more than 10 days since 2013-02-10 00:00:00

year =  timedelta(weeks=40, days=84, hours=23,

...  minutes=50, seconds=600)  # adds up to 365 days

year.total_seconds()

31536000.0


(As a side note, I think it would be better if sections in datetime were
in separate pages, it would be easier to google and the navbar on the
left side is very crowded and rather hard to read - often I find myself
missing stuff that's in there and ending up just scrolling down through
the document until I find what I need -- it might be better if section
numbers were not included there, font for keywords was not fixed width
font, and topics didn't wrap so much - in case of datetime, all of the
topics have enough horizontal space not to wrap and yet 3 out of 7 do wrap!)


Of course, it can be argued that these are minor issues, that relevant
parts of documentation are still quite easy to get to, and if it takes a
few minutes longer, it's not the end of the world.

In my view, such small matters are more important than it looks, because
working on a project requires focus and if you spend just a few minutes
hunting around the doc pages, you start to lose the larger picture of
your design... I tend to remember the most important modules out of
standard lib because I've worked with them a lot in the last few years,
but I imagine it can be tough for people who program a bit as a hobby or
as a small part of their job.

I don't mean to say that Python docs are terrible, though. They're quite
good, especially as more examples were added in the last few years

Re: Do you feel bad because of the Python docs?

2013-02-26 Thread Mitya Sirenef

On 02/26/2013 10:09 PM, Mitya Sirenef wrote:

(As a side note, I think it  would be better if sections in datetime were

 in separate pages, it would be easier to google and the navbar on the
 left side is very crowded and rather hard to read - often I find myself
 missing stuff that's in there and ending up just scrolling down through
 the document until I find what I need -- it might be better if section
 numbers were not included there, font for keywords was not fixed width
 font, and topics didn't wrap so much - in case of datetime, all of the
 topics have enough horizontal space not to wrap and yet 3 out of 7 do 
wrap!)


In regard to Python doc topic menu readability -- compare to the django
topic menu:

https://docs.djangoproject.com/en/dev/topics/db/queries/

It's ridiculous how much more readable it is, at least to my eyes!

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: intX.__str__() ??

2013-02-24 Thread Mitya Sirenef

On 02/24/2013 12:29 PM, Michael Torrie wrote:



 I think he's maintaining existing code. It's unfortunate that his first
 exposure to python is code written by someone else in such a poor style,
 and in a way that definitely isn't pythonic. No wonder he's struggling
 to like python! Though I'm sure since his recent experience has been
 exclusively in C# that he probably uses hungarian notation as a matter
 of course. A hard habit to break! Is this a good time to introduce him
 to duck typing? Probably not.

 Another way to explain the double underscore methods is that they are
 how things like operator overloading is performed. Want to make a class
 that you can use the [index] notation on instances? Define the
 __get_attr__() method. And to define a class that you can then use

small correction: it should be __getattr__()


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Admiration for a quality or an art can be so strong that it deters us from
striving to possess it.  Friedrich Nietzsche

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


Re: intX.__str__() ??

2013-02-24 Thread Mitya Sirenef

On 02/24/2013 01:23 PM, Steven D'Aprano wrote:

On Sun, 24 Feb 2013 13:09:56  -0500, Mitya Sirenef wrote:


 On 02/24/2013 12:29 PM, Michael Torrie wrote:

  Another way to explain the double underscore methods is that they are
  how things like operator overloading is performed. Want to make a
  class that you can use the [index] notation on instances? Define the
  __get_attr__() method. And to define a class that you can then use

 small correction: it should be __getattr__()


 Correct correction: it should be __getitem__ to override instance[item]
 access. __getattr__ is for overriding instance.attribute.




Oh, yes.. I guess it pays to read more than a single sentence
when making corrections! -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Each religion, by the help of more or less myth, which it takes more or
less seriously, proposes some method of fortifying the human soul and
enabling it to make its peace with its destiny.  George Santayana

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


Re: Python Newbie

2013-02-24 Thread Mitya Sirenef

On 02/24/2013 02:40 PM, piterrr.dolin...@gmail.com wrote:

if (some statement): #  short form


 rather than

 if (some statement == true): # long form


 What all those ugly brackets are for?


 Mark,

 Back in the day when C was king, or take many newer long established
 languages (C#, Java), the use of () has been widespread and mandated
 by the compilers. I have never heard anyone moan about the requirement
 to use parentheses. Now come Python in which parens are optional, and
 all of a sudden they are considered bad and apparently widely
 abandoned. Do you really not see that code with parens is much more
 pleasing visually? I could understand someone's reluctance to use
 parens if they are very new to programming and Pythons is their first
 language. But my impression here is that most group contributors are
 long-time programmers and have long used () where they are required.
 Again, I'm really surprised the community as a whole ignores the
 programming heritage and dumps the parens in a heartbeat.

 Peter


When I write in English, I write: If it rains, I'll get an umbrella.
I do not write: If (it rains), I'll get an umbrella. The second example
isn't any clearer. The only reason you like unneeded parens is that
you're used to them. I've never heard of anyone missing this feature
after a month or two of using Python.

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The world is a perpetual caricature of itself; at every moment it is the
mockery and the contradiction of what it is pretending to be.
George Santayana

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


Re: Python Newbie

2013-02-24 Thread Mitya Sirenef

On 02/24/2013 04:44 PM, Chris Angelico wrote:

On Mon, Feb 25, 2013 at 8:08  AM, Roy Smith r...@panix.com wrote:

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

 no need to remember what's an object and what's not -- everything 
is an

 object

 Careful on the citations - Ethan Furman said that, I just quoted him.

 Well, not quite everything. If I write:

 if foo:
 do_this()
 and_this()

 the code block making up the body of the if statement is not an
 object. In some languages, it is.

 Maybe, but the code of an entire function *is*. Granted, it's not an
 object that can be built up manually (at least, not that I know of),
 and it offers only limited functionality (dis.dis, but not a lot
 else), so really it could be seen as just an implementation detail of
 the function object itself. But it's still an object.

 ChrisA


But if block doesn't have to be inside a function, right? It needs
to be inside a module, but then again everything is inside a module, but
it wouldn't be very object-oriented if the module was the only object in
Python :-).

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The press, the machine, the railway, the telegraph are premises whose
thousand-year conclusion no one has yet dared to draw.  Friedrich Nietzsche

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


Re: Python Newbie

2013-02-22 Thread Mitya Sirenef

On 02/22/2013 06:58 AM, Rui Maciel wrote:

Mitya Sirenef wrote:


 Looks very unclear and confusing to me. Whether it's C# or ruby or
 anything else, most devs don't indent like that;

 The Go programming language makes that style mandatory.


 Rui Maciel


I was referring to different indentation of the if block, not to braces
style.  -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The doer alone learneth.  Friedrich Nietzsche

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


Re: Python Newbie

2013-02-22 Thread Mitya Sirenef

On 02/22/2013 04:37 PM, piterrr.dolin...@gmail.com wrote:

Thanks to everyone for all the  posts, some friendly some not. I read all of 
them with genuine interest.


 So I am continuing to learn Python, here are my new observations for 
your consideration.


 There seems to be a heated argument about Python's apparently
 intentional ambiguity in conditional statements. Specifically, the
 issue is, is it more appropriate to write (as an example)


I would say it's not a case of ambiguity but that you want the language
syntax to provide you hints that are not directly relevant to the logic
of a statement.

if mylist:  # unambiguous check for whether mylist evaluates to boolean True

if mylist == []:  # gives you a hint that mylist is meant to be an empty
# or a non-empty list

But what if I have:

process(mylist)

where is my hint? Why is hint required in an if statement but not
required in other cases when mylist is used: function calls, loops,
summation, etc?

The point is, if variables have good names, the hint is not necessary
and if variables have terrible names, you have bigger problems to deal
with.




 if (some statement): # short form

 rather than

 if (some statement == true): # long form

 Some 50(?) years ago, C was designed so that everything other than 0
 evaluated to true and was false otherwise. Fast forward to recent
 memory, when C# was designed, Microsoft claims they reviewed all the
 features of C, C++ and Java, pulled the best features from each of


Fun fact: few language designers claim they took all the _worst_
features from other languages, or that they took a random sampling of
worst, best and middling features.


these languages and designed a  new language that would help minimize

 the potential for planting bugs. Say what you want about MS
 inventions, but my experience is that to require the long form
 notation was a good decision. For me the fact that the short notation
 is legal in Python is a stepback in language design. Python inventors,
 when creating what is after all considered a contemporary language,
 should have known better. Call me psychopath if you will (have seen
 this in one post), but I shall continue to use the aforementioned long
 form as I always have, and no Python is going to change that.


 Today I learned the hard way that all function parameters in Python
 are passed by reference (meaning whatever happens to them inside a
 function, new values are always passed to caller). Not good. I got
 caught up on this. To combat the mostly unwanted behavior, inside a
 function I have to reassign variables intended to be local to new
 variables. A pain. Can anyone offer ONE reason why Python was designed
 that way?


The idea is that copying should always be explicit so that if you don't
want the object to be copied, you pass it around and change it as
needed, and if you want the copy, you make a copy explicitly.

It makes sense to me because if you had a large sequence or mapping and
passed it to a hundred (or a thousand) functions, you'd have a hundred
or thousand copies - not good for performance. When you need a copy -
make a copy, what can be simpler than that?




 Out of curiosity, does anyone have any idea why function declarations
 are preceded by the keyword def rather than something more intuitive
 like function or at least func, perhaps?

But it's not a function, it's a function definition! Why are you not
demanding 'function definition' instead? function implies the function
object, which is what you use after you define the function definition.

Def is a bit aesthetically better and unambiguous (I thought you were a
fan of that?). func sounds like you work on a tough project and get too
deep in it and forget to shower for a few weeks no I mean days, what a
silly mistake to make (I guess I could just go back and fix it), but my
point is, function would work too but def is perfectly short and clear.




 Does anyone know what the benefit of writing the cryptic elif to
 mean else if is? Curiously, the default statement in an if/else
 chain is preceded by else and not el.


ruby, unix shells, c preprocessor also use elif; perl uses elsif, php
uses elseif.

It's a judgement call, I for one like elif a bit better because it's
shorter without sacrificing clarity.




 Someone said I am too narrow-sited appreciating C# and not open to
 alternate approaches to language design. Well if that someone says
 def is better than function and elif is better than else if,
 then dare I say, you are obsessed with Python!

 So far I am getting the impression that Python is a toy language of
 some kind (similar to Basic of the early 80's), not really suitable
 for serious work. The only difference between these languages
 (admittedly, a serious one) is the existence of extensive libraries.
 Otherwise there would be no good reason for Python to exist.
 Nevertheless, it does exist and I have to learn it. As long as someone
 is paying for my time, 

Re: Python Newbie

2013-02-22 Thread Mitya Sirenef

On 02/22/2013 09:18 PM, Chris Angelico wrote:

On Sat, Feb 23, 2013 at 1:02  PM, Steven D'Aprano

 steve+comp.lang.pyt...@pearwood.info wrote:
 On Fri, 22 Feb 2013 20:47:20 -0500, Mitya Sirenef wrote:

 It's been used for many important projects by a huge number of big
 companies:

 http://www.python.org/about/success/

 Unlike Java and C#, it's not backed by a marketing effort of a large
 company, so its success is entirely due to its value.

 +1 QOTW


 Well said. While Sun (now Oracle) have spent millions marketing 
Java, and

 Microsoft done the same for C#, Python has got where it is almost
 entirely on merit and word-of-mouth.

 It's worth noting, though, that there are self-perpetuating aspects to
 it. I can happily distribute a .py file to a Linux audience, because
 many Linux distros come with a Python already installed, or at very
 least can grab one easily via the package manager. No matter how
 awesome Fred's Awesome Internet Language is, it's not going to be as
 good a choice as something that people can simply 'apt-get install',
 'yum install', or whatever they're most familiar with. I don't have
 enough history with Python to know when that status began to be
 achieved, nor how it happened, but I'd guess that exciting/interesting
 a distro manager is different from being the best choice for writing
 an application.

 That said, though, Python is very good at both halves. But there might
 very well be a language far superior for writing (say) a GUI app, that
 just doesn't have the traction that Python does thanks to its
 usefulness in the plumbing.

 ChrisA


Sure, that's true; I mostly meant it in context of stuff listed on that
page, and when compared to languages of similar age.

It's also worth noting that if there's a new language that is somewhat
better than all established languages, but not to the extent that it
will ever replace them (because of network effects), it's not really
better for any practical purposes -- present and future[*] ecosystem is a
part of a language's value proposition.

 -m

[*] of course, future is hard to predict, especially when it hasn't yet
happened.


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

True friends stab you in the front.
Oscar Wilde

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


Re: Python Newbie

2013-02-21 Thread Mitya Sirenef

On 02/21/2013 04:26 PM, Piterrr wrote:

Hi folks.

 I am a long time C sharp dev, just learning Python now due to job
 requirements. My initial impression is that Python has got to be the
 most ambiguous and vague language I have seen to date. I have major
 issues with the fact that white space matters. How do you deal with
 this? For example, you open a source file in different editors and the
 indentation levels change even though i only have spaces, no tabs
 (compare Windows Notepad and Notepad++). Which editor do you trust? In
 addition, code is difficult to read because you cannot lay it out in
 easily discernable blocks. For example, I always tend to indent a full
 'if' statement block so that it is easier to see where the if block
 starts and ends. Can't do that in Python. What is even more
 frustrating is that Python is inconsistent with its syntax. For
 example, when I write if (myVariable != 0): then this is OK but for
 (i in intAry): results in syntax error. Apparently Python has
 problems with my use of parentheses. How reta
 rded. I
 think I will rather find another job than eat my nerves with Python.
 Any comments on this before I quit my job?


I think you need to distinguish between your own stylistic preference
and considerations of writing in a style that is clear and readable for
other developers who will be working with your code.

For example:

...

if condition {
...
}

...


Looks very unclear and confusing to me. Whether it's C# or ruby or
anything else, most devs don't indent like that; and that raises a
question - was an outer block accidentally deleted? How do I know if it's
your personal style or a mistake?

Even if I know it is intentional, it's not clear why an if block is
treated in a special way... what about for loops, try/except blocks,
etc? To me, if operator being at the same indentation indicates that it
is executed after the statements that precede it and before the ones
that follow it -- can't get any clearer than that!

Things like:

if (condition == value)

look like unnecessary visual noise to me. Parens are useful and are
meant to group conditions when their number becomes unwieldy and hard to
read and to override operator order of precendence (or rather to avoid
having to remember it):

if (condition == value * modifier) or (condition2 == default_value):

In regard to truthy evaluation -- it makes more sense if variables
have good names, as they should; for example:

if mylist: .. do something with the list ..

if mystring: .. process string ..

if my_things_count:
.. there were some things, process them ..
else:
.. there were no things! ..


In all of these cases, my intent is to ask if the value is empty or not,
or blank, or holds some non-false contents. It may also be a custom
object which is responsible for telling me, in a standardized way, if
it's blank/False or not. In 99.8% of cases, do I care if mystring is
None or '' or False? Of course not! Do I care if mylist is None or []?
Almost certainly not.

And the nice thing is, in the rare case that you do care, you'll
write 'if mylist is None:' -- and that alerts the reader to the fact
that mylist's specific value is important.

Reducing unnecessary visual noise in the code is a worthy goal -- it
lets your eyes focus more on the logic of the program.

HTH, -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Language is like money, without which specific relative values may well
exist and be felt, but cannot be reduced to a common denominator.
George Santayana

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


Re: Dictionaries with tuples or tuples of tuples

2013-02-18 Thread Mitya Sirenef

On 02/18/2013 07:52 PM, Jon Reyes wrote:
So I have a dictionary and the  key is a number. The values are either a single tuple or a tuple of 
tuples. Is there a better way to go about accessing the values of the 
dictionary? All the tuples contain four elements.


 So say:
 col = {1: (0,1,2,3): 2: ((0,1,2,3),(2,3,4,5))}

 Then to access the values of the tuple I'd do this:

 for key,value in col.iteritems():
 if isinstance(value[0], tuple):
 #iterate through the tuples of a tuple
 else:
 #iterate through the tuple

 At first I was thinking that I could just put the same keys with just 
single tuples on a dictionary but only one tuple exists when I iterate 
through the dictionary. I'm sorry, I'm really new at Python and I just 
grab anything I can when I need it from Google and the Python docs.


It would be easier to process if, when adding a single tuple
to the dict, you could wrap it inside a tuple: (mytup,)

If your data set is not very large and you don't mind the
slight performance hit, you can simplify processing step:

for k,v in col.iteritems():
if not isinstance(v[0], tuple):
v = (v,)
for tup in v: ...


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Although the most acute judges of the witches and even the witches
themselves, were convinced of the guilt of witchery, the guilt nevertheless
was non-existent. It is thus with all guilt.  Friedrich Nietzsche

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


Re: Dictionaries with tuples or tuples of tuples

2013-02-18 Thread Mitya Sirenef

On 02/18/2013 08:38 PM, Jon Reyes wrote:
Hi Mark. Well, doesn't  iteritems() work the same? or am I missing something? By the way I'm 
sure I read the dictionaries part of Python but I'm unsure if it would 
take int's as a key for dictionaries. I've been weaned on Java where the 
keys of hashmaps are always Strings.


 PS: Just checked, wow I could use ints as keys. Awesome!

In fact, any hashable object can be a key in a dict, so you can define
your own custom objects and use them as keys -- this can be
extremely useful sometimes!

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Oaths are the fossils of piety.  George Santayana

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


Re: Dictionaries with tuples or tuples of tuples

2013-02-18 Thread Mitya Sirenef

On 02/18/2013 09:17 PM, Jon Reyes wrote:

Thanks Dave and Mitya for  enlightening me about dictionaries. I'm still 
confused about this though:


  so that if two
 key objects are equal, they stay equal, and if they differ, they stay
 different. 

 What does this mean? I won't be comparing key objects with one 
another. Also, when I had two keys with the same value the value of the 
other key disappeared so I assume in runtime if there are multiple keys 
of the same value only the last one will appear.


You won't be, but dict will.

Dict is by definition a mapping where a value is assigned to a unique
key. If you have two keys and two values, and then change one key to
be equal to the second key, that's not kosher, because which value it's
supposed to return when you try to get it by that key?

So in effect, key's hash value should not change. If key is immutable,
you can be certain that it's hash value will not change. If it's
mutable, you have to make sure not to change the key in a way that'd
make its hash value different than it was.

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Graphic design is the paradise of individuality, eccentricity, heresy,
abnormality, hobbies and humors.  George Santayana

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


Re: Dictionaries with tuples or tuples of tuples

2013-02-18 Thread Mitya Sirenef

On 02/18/2013 10:14 PM, Dave Angel wrote:

On 02/18/2013 09:54 PM, Mitya  Sirenef wrote:

 On 02/18/2013 09:17 PM, Jon Reyes wrote:
 Thanks Dave and Mitya for enlightening me about dictionaries. I'm
 still confused about this though:
 
   so that if two
  key objects are equal, they stay equal, and if they differ, they stay
  different. 
 
  What does this mean? I won't be comparing key objects with one
 another. Also, when I had two keys with the same value the value of the
 other key disappeared so I assume in runtime if there are multiple keys
 of the same value only the last one will appear.

 You won't be, but dict will.

 Dict is by definition a mapping where a value is assigned to a unique
 key. If you have two keys and two values, and then change one key to
 be equal to the second key, that's not kosher, because which value it's
 supposed to return when you try to get it by that key?

 So in effect, key's hash value should not change. If key is immutable,
 you can be certain that it's hash value will not change. If it's
 mutable, you have to make sure not to change the key in a way that'd
 make its hash value different than it was.

 -m


 It's a little stronger than that, since equal hashes cannot assure
 equal data. The equality of each object pair in a dict must not
 change over time, not just the hashes of the individual objects.


Ah, yes - that's true; if hashes were unequal and then the key is
changed to be equal to the first key, both mydict[key1] and mydict[key2]
will give you value1, but iterating over dict items will print key1,
value1; key2, value2. And that's not a good thing.  -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

True friends stab you in the front.
Oscar Wilde

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


Re: Small program ideas

2013-02-15 Thread Mitya Sirenef

On 02/15/2013 10:22 PM, eli m wrote:

Any small program ideas? I would prefer to stick to command line ones. Thanks.


How about these two:

 - simulation of a street crossing with green/red lights allowing cars 
and pedestrians to pass in one direction then another


 - simulation of an elevator in a building: buttons on each floor to 
call the elevator, buttons inside to go to a particular floor,
   multiple floors can be selected at the same time, creating a queue 
of floors to go to.


 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Small program ideas

2013-02-15 Thread Mitya Sirenef

On 02/15/2013 10:57 PM, eli m wrote:

On Friday, February 15, 2013 7:52:57 PM UTC-8, Mitya Sirenef wrote:

On 02/15/2013 10:22 PM, eli m wrote:


Any small program ideas? I would prefer to stick to command line ones. Thanks.



How about these two:



   - simulation of a street crossing with green/red lights allowing cars

and pedestrians to pass in one direction then another



   - simulation of an elevator in a building: buttons on each floor to

call the elevator, buttons inside to go to a particular floor,

 multiple floors can be selected at the same time, creating a queue

of floors to go to.



   -m



--

Lark's Tongue Guide to Python: http://lightbird.net/larks/

Could i make these text and not visual? That is what i am trying to do.



Of course - just think up some textual representation before starting on 
the code. -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Multiple ways to access attributes

2013-02-10 Thread Mitya Sirenef

On 02/10/2013 05:44 PM, ISE Development wrote:

Is it considered acceptable  practice (e.g. not confusing, not

 surprising or not Pythonic) to allow multiple ways to access
 the same attributes?

 For example, supposing I am providing access to external
 devices, that these parameters may vary slightly between
 devices (e.g. different models, etc...) and that the device
 may be queried for parameter meta-data (such as name, data
 type, data value constraints), would the following API be
 acceptable (in the sense alluded to above)? Or would it be
 generally considered a distortion of Python idealogy (e.g.
 like PERL's 'more than one way to do it' approach)?


There should be one-- and preferably only one --obvious way to do it.

The reason for this guideline is that if there were many similar ways to
do the same thing (in the language itself), without one way standing out
as an obvious, idiomatic choice, you would end up with every program
using its own approach and it would be much harder to read and
understand other people's programs. If there's one obvious, preferred
way, you can look at code from hundreds of people and you will know
immediately what they are doing and why.

This does not apply to your case. You are already creating a custom
interface for working with options.

Does your approach make the code more readable and easier to work with?
If yes, this is perfectly fine.

[snip]

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Many possessions, if they do not make a man better, are at least expected
to make his children happier; and this pathetic hope is behind many
exertions.  George Santayana

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


Re: Please provide a better explanation of tuples and dictionaries

2013-01-29 Thread Mitya Sirenef

On 01/29/2013 09:55 PM, Daniel W. Rouse Jr. wrote:

Hi all,


 I have recently started learning Python (2.7.3) but need a better 
explanation of how to use tuples and dictionaries.


 I am currently using Learning Python by Mark Lutz and David Ascher, 
published by O'Reilly (ISBN 1-56592-464-9)--but I find the explanations 
insufficient and the number of examples to be sparse. I do understand 
some ANSI C programming in addition to Python (and the book often 
wanders off into a comparison of C and Python in its numerous 
footnotes), but I need a better real-world example of how tuples and 
dictionaries are being used in actual Python code.


 Any recommendations of a better book that doesn't try to write such 
compact and clever code for a learning book? Or, can an anyone provide 
an example of more than a three-line example of a tuple or dictionary?


 The purpose of my learning Python in this case is not for enterprise 
level or web-based application level testing at this point. I initially 
intend to use it for Software QA Test Automation purposes.


 Thanks in advance for any replies.


It's not finished yet, but you may find my text-movie tutorial on
dicts useful:

http://lightbird.net/larks/tmovies/dicts.html

 -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Idleness is the mother of psychology.  Friedrich Nietzsche

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


Re: what is the difference between commenting and uncommenting the __init__ method in this class?

2013-01-28 Thread Mitya Sirenef

On 01/28/2013 09:09 PM, iMath wrote:

what is the difference between  commenting and uncommenting the __init__ method 
in this class?



 class CounterList(list):
 counter = 0

 ## def __init__(self, *args):
 ## super(CounterList, self).__init__(*args)

 def __getitem__(self, index):

 self.__class__.counter += 1
 return super(CounterList, self).__getitem__(index)



No difference as this code doesn't do anything else in the __init__() it
overrides. Normally you would add some additional processing there but
if you don't need to, there is no reason to override __init__(),
therefore it's clearer and better to delete those 2 lines.

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

It is always pleasant to be urged to do something on the ground that one
can do it well.  George Santayana

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


Re: Formatting a column's value output

2013-01-27 Thread Mitya Sirenef

On 01/27/2013 03:24 PM, Κώστας Παπαδόπουλος wrote:

Τη Κυριακή, 27 Ιανουαρίου 2013  9:12:16 μ.μ. UTC+2, ο χρήστης ru...@yahoo.com 
έγραψε:

 python code

 Yes indeed, there is no need to use a loop since i know the exact 
number of items i'am expecting. Thanks you very much for clarifying this 
to me:

 One last thing i want to ask you:

 
 try:
 cur.execute( '''SELECT host, userOS, browser, hits, lastvisit FROM 
visitors
 WHERE counterID = (SELECT ID FROM counters WHERE URL = %s) ORDER BY 
lastvisit DESC''', (htmlpage,) )

 except MySQLdb.Error, e:
 print ( Query Error: , sys.exc_info()[1].excepinfo()[2] )
 else:
 data = cur.fetchall()

 for host, useros, browser, hits, lastvisit in data:
 print ( tr )

 for item in host, useros, browser, hits, lastvisit.strftime('%A %e 
%b, %H:%M').decode('cp1253').encode('utf8'):

 print ( tdcenterbfont color=white %s /td % item )

 sys.exit(0)
 ===

 That would be also written as:

 for row in data:
 print (tr)
 for item in row:
 print( blah blah blah )

 And that would make the code easier to read and more clear, but its 
that 'lastvisit' column's value than needs formating,hence it makes me 
use the above syntax.


 Is there any simpler way to write the above working code without the 
need to specify all of the columns' names into the loop?



You can write:

 for row in data:
 print (tr)
 row = list(row)
 row[-1] = row[-1].strftime(...)
 for item in row:
 print( blah blah blah )


 - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The existence of any evil anywhere at any time absolutely ruins a total
optimism.  George Santayana

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


Re: Using filepath method to identify an .html page

2013-01-22 Thread Mitya Sirenef

On 01/22/2013 12:33 PM, rusi wrote:

On Jan 22, 8:59 pm, Ferrous  Cranus nikos.gr...@gmail.com wrote:
 I just need a way to CONVERT a string(absolute path) to a 4-digit 
unique number with INT!!!

 That's all i want!! But i cannot make it work :(

 I just need a way to eat my soup with a screwdriver.
 No I WONT use a spoon.

 Im starving
 HELP


Well done, sir!  :-)



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Life is not a spectacle or a feast; it is a predicament.  George Santayana

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


Re: ANN: Python training text movies

2013-01-21 Thread Mitya Sirenef

On 01/21/2013 02:30 AM, rusi wrote:

On Jan 13, 12:08 pm, Mitya  Sirenef msire...@lightbird.net wrote:

 Sure: they play back a list of instructions on use of string methods and
 list comprehensions along with demonstration in a mock-up of the
 interpreter with a different display effect for commands typed into (and
 printed out by) the interpeter. The speed can be changed and the
 playback can be paused.

 Hi Mitya.
 What do you use for making these 'text-movies'?
 [Asking after some googling]

I'm using this script:

https://github.com/pythonbyexample/PBE/tree/master/jstmovie/

sample source file is in tmovies/src/

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Depression is rage spread thin.  George Santayana

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


Re: ANN: Python training text movies

2013-01-21 Thread Mitya Sirenef

On 01/21/2013 03:07 AM, Franck Ditter wrote:

Ok I can make my way with  jstmovie. Some remarks and questions :


 - Use encoding='utf-8' inside open of method __init__ of class Tutorial
 in jstmovie.py. Otherwise foreign languages are stuck.

 - To use the software outside Python, we need to have proper indentation
 as real spaces. We should be able to distinguish Arial type for usual
 text and fixed font for code.


Not sure I understand about indentation.. You mean like wrapping
everything in a textarea tag? Right now everything is in div,
which leads to all spaces being compressed in html when viewed.





 - Should have some colors.

 Wadda wadda byadda/b # blue annotation


I'm thinking of possibly using something like ReStructured text
and having css styles. Not sure yet.





 Cool and useful software,

 franck



Thanks!

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

He who would learn to fly one day must first learn to stand and walk and
run and climb and dance; one cannot fly into flying.  Friedrich Nietzsche

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


Re: ANN: Python training text movies

2013-01-21 Thread Mitya Sirenef

On 01/21/2013 03:07 AM, Franck Ditter wrote:

Ok I can make my way with  jstmovie. Some remarks and questions :


 - Use encoding='utf-8' inside open of method __init__ of class Tutorial
 in jstmovie.py. Otherwise foreign languages are stuck.


Thanks, will fix this..  -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

By nature's kindly disposition most questions which it is beyond a man's
power to answer do not occur to him at all.  George Santayana

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


Re: ANN: Python training text movies

2013-01-21 Thread Mitya Sirenef

On 01/21/2013 06:30 AM, Franck Ditter wrote:

In article  mailman.731.1358757093.2939.python-l...@python.org,

 Mitya Sirenef msire...@lightbird.net wrote:

  - To use the software outside Python, we need to have proper 
indentation

  as real spaces. We should be able to distinguish Arial type for usual
  text and fixed font for code.


 Not sure I understand about indentation.. You mean like wrapping
 everything in a textarea tag? Right now everything is in div,
 which leads to all spaces being compressed in html when viewed.

 SOme spaces are translated in nbsp;, others in actual spaces.
 Say for Scheme, if I write this in foo.txt :

 (define z (* 3+2i 1+i)) ; notation a+bi
 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz

 I get this in foo.html (spaces missing) :

 (define z (* 3+2i 1+i)) ; notation a+bi
 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz

 franck


This applies to Python and all other languages equally, that's why I was
confused. I've fixed this issue and added utf-8, and moved the files to
a new location  also copied utils.py file which I forgot yesterday.


https://github.com/pythonbyexample/PBE/tree/master/jstmovie


 -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The world is a perpetual caricature of itself; at every moment it is the
mockery and the contradiction of what it is pretending to be.
George Santayana

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


Re: ANN: Python training text movies

2013-01-20 Thread Mitya Sirenef

On 01/20/2013 12:54 PM, Franck Ditter wrote:

In article  nobody-a71b2d.18413120012...@news.free.fr,

 Franck Ditter nob...@nowhere.org wrote:

 In article nobody-b6cd7f.18373820012...@news.free.fr,
 Franck Ditter nob...@nowhere.org wrote:

 In article mailman.696.1358622153.2939.python-l...@python.org,
 Mitya Sirenef msire...@lightbird.net wrote:

 On 01/19/2013 04:32 AM, Franck Ditter wrote:
 In article mailman.488.1358146579.2939.python-l...@python.org,
 Mitya Sirenef msire...@lightbird.net wrote:

 On 01/14/2013 01:34 AM, Franck Ditter wrote:
 In article mailman.469.1358088303.2939.python-l...@python.org,
 Jason Friedman ja...@powerpull.net wrote:

 That is right; I would also add that it may be overwhelming 
for a newbie
 to be reading through a large wall of text -- here you have 
blank
 space after the current paragraph so the attention is focused 
even more

 on the last few lines.

 Additionally, since instructions scroll automatically, I can 
space them

 out more than you would conventionally do in a manual.

 Pretty cool.
 When reading the source of the Web page which shows the scroll,
 I can't find the reference to the text displayed. Only text...
 How may we use the software which generates the Javascript ?
 Thanks, it's cool.

 franck
 Thanks!

 the text is in var commands = ...

 You can download the generator script here:

 https://github.com/pythonbyexample/PBE/blob/master/code/jstmovie.py

 (you also need to grab tmovies dir)
 When looking at the source of the page :
 http://lightbird.net/larks/tmovies/strings.html
 I find commands = []
 I can't guess where the strings displayed come from...

 franck

 Look 10 lines below that line.


 I have also added a related page that allows you to paste your own
 text to make a movie; it's linked from the same page with the
 list of generated t-movies.

 (that page does not let you use typewriter effect or custom pauses
 though).

 - mitya

 I'm probably blind but 10 line after the line commands = [], I find :

 var commands = [
 [
 text,
  
 ],
 [
 text,
  
 ],
 ]

 but nothing concrete ! How come ?

 franck

 OK OK found ! Thanks.

 franck

 When executing jstmovie.py, it complains :
 'template.html' not found in tmovies...

 franck

 tmovies/template.html

As I've said upthread, you need to download tmovies dir from
the same repository where jstmovie.py is located:

https://github.com/pythonbyexample/PBE/tree/master/code/


 - mitya



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Admiration for a quality or an art can be so strong that it deters us from
striving to possess it.  Friedrich Nietzsche

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


Re: RE Help splitting CVS data

2013-01-20 Thread Mitya Sirenef

On 01/20/2013 05:04 PM, Garry wrote:

I'm trying to manipulate family tree data using Python.
I'm using linux and Python 2.7.3 and have data files saved as Linux formatted 
cvs files
The data appears in this format:

Marriage,Husband,Wife,Date,Place,Source,Note0x0a
Note: the Source field or the Note field can contain quoted data (same as the 
Place field)

Actual data:
[F0244],[I0690],[I0354],1916-06-08,Neely's Landing, Cape Gir. Co, MO,,0x0a
[F0245],[I0692],[I0355],1919-09-04,Cape Girardeau Co, MO,,0x0a

code snippet follows:

import os
import re
#I'm using the following regex in an attempt to decode the data:
RegExp2 = 
^(\[[A-Z]\d{1,}\])\,(\[[A-Z]\d{1,}\])\,(\[[A-Z]\d{1,}\])\,(\d{,4}\-\d{,2}\-\d{,2})\,(.*|\.*\)\,(.*|\.*\)\,(.*|\.*\)
#
line = [F0244],[I0690],[I0354],1916-06-08,\Neely's Landing, Cape Gir. Co, 
MO\,,
#
(Marriage,Husband,Wife,Date,Place,Source,Note) = re.split(RegExp2,line)
#
#However, this does not decode the 7 fields.
# The following error is displayed:
Traceback (most recent call last):
   File stdin, line 1, in module
ValueError: too many values to unpack
#
# When I use xx the fields apparently get unpacked.
xx = re.split(RegExp2,line)
#

print xx[0]
print xx[1]

[F0244]

print xx[5]

Neely's Landing, Cape Gir. Co, MO

print xx[6]
print xx[7]
print xx[8]

Why is there an extra NULL field before and after my record contents?
I'm stuck, comments and solutions greatly appreciated.

Garry




Gosh, you really don't want to use regex to split csv lines like that

Use csv module:

 s
'[F0244],[I0690],[I0354],1916-06-08,Neely\'s Landing, Cape Gir. Co, 
MO,,0x0a'

 import csv
 r = csv.reader([s])
 for l in r: print(l)
...
['[F0244]', '[I0690]', '[I0354]', '1916-06-08', Neely's Landing, Cape 
Gir. Co, MO, '', '0x0a']



the arg to csv.reader can be the file object (or a list of lines).

 - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: To make a method or attribute private

2013-01-20 Thread Mitya Sirenef

On 01/20/2013 09:24 PM, alex23 wrote:

On Jan 21, 9:32 am, Dave Angel  d...@davea.name wrote:

 On 01/20/2013 06:14 PM, alex23 wrote:

 On Jan 20, 7:23 pm, Chris Angelico ros...@gmail.com wrote:
 On Sun, Jan 20, 2013 at 8:17 PM, iMath redstone-c...@163.com wrote:
 so what is your opinion about single leading underscore and 
private methods or attributes?


 Didn't this get discussed recently?

 http://mail.python.org/pipermail/python-list/2013-January/638687.html

 ChrisA

 Isn't that a link to the same post that started this thread? :)

 No, that's the one that started the earlier thread, by the same name,
 three whole days ago. iMath posted an apparently complete duplicate of
 his earlier message.

 The link is to a post of the same date as the original of this thread,
 and the very first response is mine, same as with this thread. I'm
 still not seeing the dupe?

I do see the duplicate in my reader..  -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

To knock a thing down, especially if it is cocked at an arrogant angle, is
a deep delight of the blood.
George Santayana


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


Re: Else statement executing when it shouldnt

2013-01-20 Thread Mitya Sirenef

On 01/20/2013 11:40 PM, eli m wrote:
an else statement is running  when it shouldnt be. It is on the last line. Whenever i am in the math 
or game function, when i type in main, it goes back to the start of the 
program, but it also says not a valid function. I am stumped!

 Here is my code:
 #Cmd
 #Created By Eli M.
 #import modules
 import random
 import math
 gtn = 0
 print (Type in help for a list of cmd functions)
 #initiate main loop
 cmd = 0
 while cmd == 0:
 #ask for input on function
 function = raw_input(Type in a function:)
 #start math loop
 if function == math:
 run = 0
 while run == 0:
 #ask for math operation
 type = raw_input(What math operation do you want to use?)
 if type == multiplication:
 x = raw_input(Type in your first number:)
 y = raw_input(Multiply your first number by:)
 try:
 ans = int(x) * int(y)
 print (ans)
 try:
 ans = float(x) * float(y)
 print (ans)
 except ValueError, err:
 print (Not a valid number)
 except OverflowError, err:
 print (Number too large)
 #division math function
 if type == division:
 x = raw_input(Type in your first number:)
 y = raw_input(Divide your first number by:)
 try:
 ans = float(x) / float(y)
 print (ans)
 except ZeroDivisionError, err:
 print (Can't divide by zero)
 except ValueError, err:
 print (Not a valid number)
 except OverflowError, err:
 print (Number too large)
 #subtraction math function
 if type == subtraction:
 x = raw_input(Type in your first number:)
 y = raw_input(Subtract your first number by:)
 try:
 ans = float(x) - float(y)
 print (ans)
 except ValueError, err:
 print (Not a valid number)
 #addition math function
 if type == addition:
 x = raw_input(Type in your first number:)
 y = raw_input(Add your first number by:)
 try:
 ans = float(x) + float(y)
 print (ans)
 except ValueError, err:
 try:
 ans = int(x) + int(y)
 print (ans)
 except ValueError, err:
 print (Not a valid number)
 except OverflowError, err:
 print (Number too large)
 #square root math function
 if type == square root:
 x = raw_input(Type in your number:)
 try:
 y = float(x)
 z = math.sqrt(y)
 print (z)
 except ValueError, err:
 print (Not a valid number)
 except OverflowError, err:
 print (Number too large)

 #to the power of... math function
 if type == power:
 x = raw_input(Type in your number:)
 y = raw_input(Multiply your first number by the power of:)
 try:
 ans = float(x) ** float(y)
 print (ans)
 except OverflowError, err:
 print (Number too large)
 except ValueError, err:
 print (Not a valid number)
 #break the math loop
 if type == main:
 run = 1
 #absolute value math function
 if type == absolute value:
 try:
 x = float(raw_input(Type in your number:))
 y = math.fabs(x)
 print (y)
 except ValueError, err:
 print (Not a valid number)
 if function == random number:
 try:
 x = int(raw_input(Minimum number:))
 y = int(raw_input(Maximum number:))
 num = random.randint(x, y)
 print (num)
 except ValueError, err:
 print (Not a valid number)
 if function == games:
 games = 0
 while games == 0:
 gamechoice = raw_input(What game do you want to play:)
 if gamechoice == guess the number:
 run = 0
 while run == 0:
 print (I am thinking of a number between 1 and 20)
 num = random.randint(1, 20)
 num = int(num)
 guesses = 0
 guessestaken = 0
 while guesses == 0:
 try:
 guess = raw_input(Your guess:)
 guess = int(guess)
 guessestaken = (guessestaken) + 1
 guessestaken = int(guessestaken)
 if guess == (num):
 print 'Correct! It took you', int(guessestaken), 'guesses!'
 playagain = raw_input(Do you want to play again?)
 if playagain == yes:
 guesses = 1
 if playagain == no:
 run = 1
 guesses = 1
 if guess  num:
 print (My number is lower)
 if guess  num:
 print (My number is higher)
 except TypeError, err:
 print (Not a valid number)
 if gamechoice == main:
 games = 1

 #help function
 if function == help:
 helpfunc = 0
 while helpfunc == 0:
 #show functions
 print (Functions:)
 print (Math: multiplication, division, subtraction, addition, square 
root, power, absolute value)

 print (Random Number)
 print (Games: Guess the number)
 helpmain = raw_input(Type in main to go back)
 if helpmain == main:
 #end helpfunction loop
 helpfunc = 1
 cmd = 0
 else:
 print (Not a valid function)


Your else is lined up with while, not with if.

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

When a friend succeeds, I die a little.  Gore Vidal

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


Re: Else statement executing when it shouldnt

2013-01-20 Thread Mitya Sirenef

On 01/20/2013 11:59 PM, eli m wrote:






 Your else is lined up with while, not with if.



 -m





 --

 Lark's Tongue Guide to Python: http://lightbird.net/larks/



 When a friend succeeds, I die a little. Gore Vidal
 Its lined up. It got messed up when i copied the code into the post.


I would recommend using while True: and break vs. while var: as you
have. In most cases while True: works better, especially in case of long
and/or nested 'while' loops, as you have.

'while True' blocks have two advantages: 1. you can break the loop at
any location and 2. when looking at the code, you can tell on which
condition it breaks by looking at the break line.

Even more importantly, break it up into a few functions. The code as you
have it is too hard to work with and to debug.

It's hard to tell what your 'else' is lined up to, or whether some other
lines are mis-aligned, as well.

Generally, try to avoid making a loop if it's 20+ lines; if there are
nested loops, it makes things even worse. Compare:

if something:
while True:
 if not process(): break

def process():
 [... 20 lines that loop ...]
 [ return None to break the loop ]

Now this is really clear, because just by looking at the first three
lines, I know what the loop is supposed to do (process something), that
it continues looping until it returns a false value; when looking at
the function body I don't need to care which block it aligns to, I
already know the entire function body is in the while loop.

HTH, -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The irrational in the human has something about it altogether repulsive and
terrible, as we see in the maniac, the miser, the drunkard or the ape.
George Santayana

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


Re: Safely add a key to a dict only if it does not already exist?

2013-01-19 Thread Mitya Sirenef

On 01/19/2013 02:35 AM, Mitya Sirenef wrote:

On 01/19/2013 02:27 AM, Vito De Tullio wrote:

Chris Rebert wrote:


How can I add a key in a thread-safe manner?

I'm not entirely sure, but have you investigated dict.setdefault() ?
but how setdefault makes sense in this context? It's used to set a 
default
value when you try to retrieve an element from the dict, not when you 
try to

set a new one ...



I guess setdefault with a sentinel default value, then set to your
new value if d[k] is sentinel?

 - mitya




Er, that makes no sense.. just setdefault to desired value. -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: ANN: Python training text movies

2013-01-19 Thread Mitya Sirenef

On 01/19/2013 04:32 AM, Franck Ditter wrote:

In article mailman.488.1358146579.2939.python-l...@python.org,
  Mitya Sirenef msire...@lightbird.net wrote:


On 01/14/2013 01:34 AM, Franck Ditter wrote:

In article mailman.469.1358088303.2939.python-l...@python.org,
   Jason Friedman ja...@powerpull.net wrote:


That is right; I would also add that it may be overwhelming for a newbie
to be reading through a large wall of text -- here you have blank
space after the current paragraph so the attention is focused even more
on the last few lines.

Additionally, since instructions scroll automatically, I can space them
out more than you would conventionally do in a manual.


Pretty cool.

When reading the source of the Web page which shows the scroll,
I can't find the reference to the text displayed. Only text...
How may we use the software which generates the Javascript ?
Thanks, it's cool.

  franck

Thanks!

   the text is in var commands = ...

You can download the generator script here:

https://github.com/pythonbyexample/PBE/blob/master/code/jstmovie.py

(you also need to grab  tmovies dir)

When looking at the source of the page :
http://lightbird.net/larks/tmovies/strings.html
I find commands = []
I can't guess where the strings displayed come from...

 franck


Look 10 lines below that line.


I have also added a related page that allows you to paste your own
text to make a movie; it's linked from the same page with the
list of generated t-movies.

(that page does not let you use typewriter effect or custom pauses
though).

 - mitya



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Any algorithm to preserve whitespaces?

2013-01-19 Thread Mitya Sirenef

On 01/19/2013 05:13 AM, Santosh Kumar wrote:

I have a working script which takes argv[1] as an input, deassembles
each line, and then each word. Then after it capitalizes all its word
(upcases the first letter) and then prints it out on the stdout.

That script does the capitalization work fine, but, when it reassemble
the the words, it does it like this:

 lines.append(' '.join(words))

The biggest problem is, even when the input file has many spaces, it
strips it down to one.

A file with this line:

This line containsmany   spaces
becomes:

This Line Contains Many Spaces


The whole script will look clumsy here. I have put it up on GitHub,
here is it: https://github.com/santosh/capitalizr.py/blob/master/capitalizr


You know that mystr.title() can do this?

 - m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Safely add a key to a dict only if it does not already exist?

2013-01-18 Thread Mitya Sirenef

On 01/19/2013 02:27 AM, Vito De Tullio wrote:

Chris Rebert wrote:


How can I add a key in a thread-safe manner?

I'm not entirely sure, but have you investigated dict.setdefault() ?

but how setdefault makes sense in this context? It's used to set a default
value when you try to retrieve an element from the dict, not when you try to
set a new one ...



I guess setdefault with a sentinel default value, then set to your
new value if d[k] is sentinel?

 - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: For Loop in List

2013-01-13 Thread Mitya Sirenef

On 01/13/2013 07:45 AM, subhabangal...@gmail.com wrote:

Dear Group,

I have a list like,


list1=[1,2,3,4,5,6,7,8,9,10,11,12]

Now, if I want to take a slice of it, I can.
It may be done in,

list2=list1[:3]
print list2

[1, 2, 3]

If I want to iterate the list, I may do as,


for i in list1:

print Iterated Value Is:,i


Iterated Value Is: 1
Iterated Value Is: 2
Iterated Value Is: 3
Iterated Value Is: 4
Iterated Value Is: 5
Iterated Value Is: 6
Iterated Value Is: 7
Iterated Value Is: 8
Iterated Value Is: 9
Iterated Value Is: 10
Iterated Value Is: 11
Iterated Value Is: 12

Now, I want to combine iterator with a slicing condition like


for i=list2 in list1:

print Iterated Value Is:,i

So, that I get the list in the slices like,
[1,2,3]
[4,5,6]
[7,8,9]
[10,11,12]

But if I do this I get a Syntax Error, is there a solution?

If anyone of the learned members may kindly let me know?

Apology for any indentation error,etc.

Thanking You in Advance,

Regards,
Subhabrata







Another good answer is to use a recipe from itertools docs page.
There are a lot of good recipes there and you may want to keep
them all in a module you can import from when needed. Here
is the recipe:

def grouper(n, iterable, fillvalue=None):
From itertools recipes: collect data into fixed-length chunks or 
blocks.

# grouper(3, 'ABCDEFG', 'x') -- ABC DEF Gxx
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args)

 list(grouper(3, range(12))
...
...
...
... )
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]


HTH, - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: ANN: Python training text movies

2013-01-13 Thread Mitya Sirenef

On 01/14/2013 01:34 AM, Franck Ditter wrote:

In article mailman.469.1358088303.2939.python-l...@python.org,
  Jason Friedman ja...@powerpull.net wrote:


That is right; I would also add that it may be overwhelming for a newbie
to be reading through a large wall of text -- here you have blank
space after the current paragraph so the attention is focused even more
on the last few lines.

Additionally, since instructions scroll automatically, I can space them
out more than you would conventionally do in a manual.


Pretty cool.

When reading the source of the Web page which shows the scroll,
I can't find the reference to the text displayed. Only text...
How may we use the software which generates the Javascript ?
Thanks, it's cool.

 franck


Thanks!

 the text is in var commands = ...

You can download the generator script here:

https://github.com/pythonbyexample/PBE/blob/master/code/jstmovie.py

(you also need to grab  tmovies dir)



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: ANN: Python training text movies

2013-01-12 Thread Mitya Sirenef

On 01/13/2013 01:35 AM, Steven D'Aprano wrote:

On Sun, 13 Jan 2013 00:11:53  -0500, AK wrote:


 I don't know what to call these, so for now I'll call them training
 text movies until I come up with a better name..

 I hope these will be helpful, especially to new students of Python.

 http://lightbird.net/larks/tmovies.html


 For the benefit of those who don't have web access at the moment, or who
 don't like to click on random links they don't know anything about, 
would

 you like to say a few words describing what text movies are, and how
 you think these may be helpful?





Sure: they play back a list of instructions on use of string methods and
list comprehensions along with demonstration in a mock-up of the
interpreter with a different display effect for commands typed into (and
printed out by) the interpeter. The speed can be changed and the
playback can be paused.

 - mitya



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: ANN: Python training text movies

2013-01-12 Thread Mitya Sirenef

On 01/13/2013 02:28 AM, Terry Reedy wrote:

On 1/13/2013 2:08 AM, Mitya  Sirenef wrote:

 On 01/13/2013 01:35 AM, Steven D'Aprano wrote:
 On Sun, 13 Jan 2013 00:11:53 -0500, AK wrote:
 
  I don't know what to call these, so for now I'll call them training
  text movies until I come up with a better name..
 
  I hope these will be helpful, especially to new students of Python.
 
  http://lightbird.net/larks/tmovies.html
 
 
  For the benefit of those who don't have web access at the moment, 
or who

  don't like to click on random links they don't know anything about,
 would
  you like to say a few words describing what text movies are, and how
  you think these may be helpful?
 
 
 


 Sure: they play back a list of instructions on use of string methods and
 list comprehensions along with demonstration in a mock-up of the
 interpreter with a different display effect for commands typed into (and
 printed out by) the interpeter. The speed can be changed and the
 playback can be paused.

 They are simulated videos of an interactive interpreter session, with
 entered commands appearing all at once instead of char by char, and
 with the extra features mentioned above. I presume the purported
 advantage over an after-the-fact transcript is focusing watcher
 attention on each entry and response.


That is right; I would also add that it may be overwhelming for a newbie
to be reading through a large wall of text -- here you have blank
space after the current paragraph so the attention is focused even more
on the last few lines.

Additionally, since instructions scroll automatically, I can space them
out more than you would conventionally do in a manual.

 - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: help

2013-01-11 Thread Mitya Sirenef

On 01/11/2013 09:24 AM, Matt Jones wrote:
Pay isn't linked to the people in any way.  A dictionary would serve 
this purpose better (at least in this simple example).


database = {
'Mac' : 1000,
'Sam' : 2000
}

name = raw_input('Enter your name:')
if name in database.keys(): print your pay is $, database[name]



This can be simplified a bit as:

database = dict(Mac=1000, Sam=2000)
name = raw_input('Enter your name: ')
if name in database:
  print your pay is $, database[name]



 -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: functon invoke or not

2013-01-09 Thread Mitya Sirenef

On Wed 09 Jan 2013 03:23:56 AM EST, skyworld wrote:

Hi,

I see someone's code as this:

class ABC: 
 def __init__(self, env):
  ...
  self.jmpTable['batchQ']['submit_job']  = self.lsf_submit
  ...
 def lsf_submit(self, cmd,env):
  .

what confused me is why there is no parentheses for self.lsf_submit in
self.jmpTable['batchQ']['submit_job']  = self.lsf_submit? what does
this piece of code mean? thanks.



Presumably it will be called at a later point:

def f(): print 'foo'

lst = [f]
# la la
lst[0]()


HTH,  -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Psycopg2 SyntaxError: invalid syntax on INSERT INTO database

2013-01-09 Thread Mitya Sirenef

On Wed 09 Jan 2013 07:19:10 PM EST, andydtay...@gmail.com wrote:

Hi John,

He're the code I would like to see work. The cursor_to is an oversight. I 
extracted this element from some other code in an attempt to isolate/resolve 
the problem myself, hence having a simplified table version. Which works 
actually, but unfortunately that's not educating me suffieciently. Actual error 
message I see follows.

- - - - - - - - - - - - - - - - - - - - - - - - -
Code:

#!/usr/bin/python
import psycopg2
import sys

def main():
db = psycopg2.connect(
   host = 'localhost',
   database = 'gisdb',
   user = 'postgres',
   password = '##'
)
cursor = db.cursor()
cursor.execute(DROP TABLE IF EXISTS tubecross)
cursor.execute(CREATE TABLE tubecross (id serial PRIMARY KEY, station_code 
char, SAJ interval, SPB interval, SOQ interval);)
cursor.execute(INSERT INTO tubecross (station_code, SAJ, SPB, SOQ) VALUES (%s, 
%s, %s, %s),(SAJ, 00:00, 00:22, 00:27))
db.commit()

if __name__ == __main__:
main()

- - - - - - - - - - - - - - - - - - - - - - - - -
Error Message:

andyt@andyt-ThinkPad-X61:~/projects/django-stringer/Other/TFLJPAPI$ python 
creat_db_exp.py
   File creat_db_exp.py, line 15
 cursor.execute(INSERT INTO tubecross (station_code, SAJ, SPB, SOQ) VALUES (%s, 
%s, %s, %s),(SAJ, 00:00, 00:22, 00:27))

  ^
SyntaxError: invalid syntax


Thanks for your help



00:00 etc are not quoted?

- mitya



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Psycopg2 SyntaxError: invalid syntax on INSERT INTO database

2013-01-09 Thread Mitya Sirenef

On Wed 09 Jan 2013 09:20:10 PM EST, andydtay...@gmail.com wrote:

Thanks for your help guys.

I was actually doing a few things wrong, but I have got this script to work by 
declaring fields as varchar and all values as strings. But I would like to log 
journey time values in hours/minutes, so I will have to look into the following:

1. Retrieving this data from postgres as text, converting it and using it. I 
will need to add/subtract on this time value; or
2. Recognising it as a time class in the first instance by using the string 
parsing function.

Regards,

Andy



Why not store as an int, in minutes, and then parse into h:m
when displaying?

- m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to do this? List loop (matrix?) iteration

2013-01-08 Thread Mitya Sirenef

On Tue 08 Jan 2013 07:19:59 PM EST, andydtay...@gmail.com wrote:

Hi!

I might be missing the obvious, or I may have found something more complicated 
than the VBA I am used to. Could it be I need to use a maths library?

For a given list of k items I'd like to turn it into an k*k matrix of item 
pairs.

List_sample = ['a', 'b', 'c']

Output:

aa ab ac
ba bb bc
ca cb cc

I'd like to have 2 hooks into this process
1. I want the opportunity to use a value pair each time they are generated 
(because I need to send these to an api and get a number back to put into a 
temporary list or dictionary - still tbd).
2. I'd also like to know each time a row is completed so I can bank that 
temporary list to a database table. Else build one big list and do it at the 
end, I'm still figuring this out.

#Code I've tried:

stn_count = len(stn_list_short)
for rowcount in range (0, stn_count):
   for colcount in range (0, stn_count):
  print stn_list_long[rowcount] stn_list_long[colcount]

I've found itertools, tee, and product and felt I was getting warmer. I'm still 
looking, but any pointers would be appreciated!

Thanks,

Andy





You can use itertools.product(abc, repeat=2) together with itertools 
recipe grouper() from the same page:


http://docs.python.org/3.3/library/itertools.html?highlight=itertools#itertools


HTH, -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-06 Thread Mitya Sirenef

On 01/06/2013 01:32 AM, Mitya Sirenef wrote:

On 01/05/2013 03:35 AM, Sia wrote:

I have strings such as:


 tA.-2AG.-2AG,-2ag
 or
 .+3ACG.+5CAACG.+3ACG.+3ACG

 The plus and minus signs are always followed by a number (say, i). I 
want python to find each single plus or minus, remove the sign, the 
number after it and remove i characters after that. So the two strings 
above become:


 tA..,
 and
 ...

 How can I do that?
 Thanks.


I think it's a bit cleaner and nicer to do something similar to
itertools.takewhile but takewhile 'eats' a single next value.
I was actually doing some stuff that also needed this. I wonder if
there's a more elegant, robust way to do this?

Here's what I got for now:


class BIterator(object):
Iterator with 'buffered' takewhile.

def __init__(self, seq):
self.seq= iter(seq)
self.buffer = []
self.end_marker = object()
self.last   = None

def consume(self, n):
for _ in range(n): self.next()

def next(self):
val = self.buffer.pop() if self.buffer else next(self.seq, 
self.end_marker)

self.last = val
return val

def takewhile(self, test):
lst = []
while True:
val = self.next()
if val is self.end_marker:
return lst
elif test(val):
lst.append(val)
else:
self.buffer.append(val)
return lst

def joined_takewhile(self, test):
return ''.join(self.takewhile(test))

def done(self):
return bool(self.last is self.end_marker)


s = .+3ACG.+5CAACG.+3ACG.+3ACG
not_plusminus = lambda x: x not in +-
isdigit   = lambda x: x.isdigit()

def process(s):
lst = []
s   = BIterator(s)

while True:
lst.extend(s.takewhile(not_plusminus))
if s.done(): break
s.next()
n = int(s.joined_takewhile(isdigit))
s.consume(n)

return ''.join(lst)


print(process(s))


Obviously it assumes the input is well-formed, but the logic would be
very easy to change to, for example, check for s.done() after each step.

 - mitya





I've added some refinements:



class BIterator(object):
Iterator with 'buffered' takewhile and takeuntil.

def __init__(self, seq):
self.seq= iter(seq)
self.buffer = []
self.end_marker = object()
self.last   = None

def __bool__(self):
return self.last is not self.end_marker

def __next__(self):
val = self.buffer.pop() if self.buffer else next(self.seq, 
self.end_marker)

self.last = val
return val

def consume(self, n):
for _ in range(n): next(self)

def takewhile(self, test):
lst = []
while True:
val = next(self)
if val is self.end_marker:
return lst
elif test(val):
lst.append(val)
else:
self.buffer.append(val)
return lst

def takeuntil(self, test):
negtest = lambda x: not test(x)
return self.takewhile(negtest)

def joined_takewhile(self, test):
return ''.join(self.takewhile(test))

def joined_takeuntil(self, test):
return ''.join(self.takeuntil(test))


def process(s):
s = BIterator(s)
lst   = []
plusminus = lambda x: x in +-
isdigit   = lambda x: x.isdigit()

while s:
lst.extend(s.takeuntil(plusminus))
next(s)
n = s.joined_takewhile(isdigit) or 0
s.consume(int(n))

return ''.join(lst)


s = .+3ACG.+5CAACG.+3ACG.+3ACG
print(process(s))




--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: psycopg2 cursor.execute CREATE TABLE issue

2013-01-06 Thread Mitya Sirenef

On Sun 06 Jan 2013 04:38:29 PM EST, andydtay...@gmail.com wrote:

Hi all,

I'm trying to create a process which will create a new table and populate it.

But something is preventing this from working, and I don't know enough to 
figure it out, despite having spent most of today reading up. The code executes 
with no error, yet no table is created or populated.

Can anyone offer me some advice? code below.

Thanks,

Andy

#!/usr/bin/python
import psycopg2
import sys

def main():
db = psycopg2.connect(
   host = 'localhost',
   database = 'gisdb',
   user = 'postgres',
   password = 'L1ncoln0ut@'
)
cursor = db.cursor()
cursor.execute(CREATE TABLE test (id serial PRIMARY KEY, num integer, data 
varchar);)
cursor.execute(INSERT INTO test (num, data) VALUES (%s, %s),(100, 
abc'def))

if __name__ == __main__:
main()



To commit a transaction, you need to do a db.commit() call.

-m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
--
http://mail.python.org/mailman/listinfo/python-list


Re: psycopg2 cursor.execute CREATE TABLE issue

2013-01-06 Thread Mitya Sirenef

On Sun 06 Jan 2013 04:53:32 PM EST, andydtay...@gmail.com wrote:

Wow it's as simple as that! I'm afraid my database experience is in Microsoft 
Access in Windows and not at the command line, so that wasn't intuitive for me.

Thanks again,

Andy



IIRC I made the same mistake when I was using psycopg for the first 
time.

I think wrapper libraries like sqlalchemy usually have myrecord.save()
method which is more intuitive.

-m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Mitya Sirenef

On 01/05/2013 03:35 AM, Sia wrote:

I have strings such as:


 tA.-2AG.-2AG,-2ag
 or
 .+3ACG.+5CAACG.+3ACG.+3ACG

 The plus and minus signs are always followed by a number (say, i). I 
want python to find each single plus or minus, remove the sign, the 
number after it and remove i characters after that. So the two strings 
above become:


 tA..,
 and
 ...

 How can I do that?
 Thanks.


I think it's a bit cleaner and nicer to do something similar to
itertools.takewhile but takewhile 'eats' a single next value.
I was actually doing some stuff that also needed this. I wonder if
there's a more elegant, robust way to do this?

Here's what I got for now:


class BIterator(object):
Iterator with 'buffered' takewhile.

def __init__(self, seq):
self.seq= iter(seq)
self.buffer = []
self.end_marker = object()
self.last   = None

def consume(self, n):
for _ in range(n): self.next()

def next(self):
val = self.buffer.pop() if self.buffer else next(self.seq, 
self.end_marker)

self.last = val
return val

def takewhile(self, test):
lst = []
while True:
val = self.next()
if val is self.end_marker:
return lst
elif test(val):
lst.append(val)
else:
self.buffer.append(val)
return lst

def joined_takewhile(self, test):
return ''.join(self.takewhile(test))

def done(self):
return bool(self.last is self.end_marker)


s = .+3ACG.+5CAACG.+3ACG.+3ACG
not_plusminus = lambda x: x not in +-
isdigit   = lambda x: x.isdigit()

def process(s):
lst = []
s   = BIterator(s)

while True:
lst.extend(s.takewhile(not_plusminus))
if s.done(): break
s.next()
n = int(s.joined_takewhile(isdigit))
s.consume(n)

return ''.join(lst)


print(process(s))


Obviously it assumes the input is well-formed, but the logic would be
very easy to change to, for example, check for s.done() after each step.

 - mitya



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Can't seem to start on this

2013-01-03 Thread Mitya Sirenef

On 01/03/2013 07:53 AM, Kene Meniru wrote:

Mitya Sirenef wrote:



 So, how many instances do you want to make.. what kind of different
 functionality / properties they will have?

 - mitya


 I am porting a modeling system I created using POV-Ray scene description
 language available at sourceforge at
 http://sourceforge.net/projects/kobldes/

 The user can create as many marks as possible (limited by memory 
available).

 The difference between each mark are the parameters provided i.e. name,
 length, and position in the scene. If the user wishes to customize 
part of
 the program they must update the classes or create new ones before 
using it
 in the scene. File A in my previous illustrations can be considered 
the

 scene file.




I'm not familiar with POV-Ray. I want to note that with python standard
style, class names look like this: ClassName, instances look like this:
instance_name; it sounds like you want LMark to be an instance? Or you
want instances in A to use class naming style?

Second, is the LMark instance only used to perform one set of actions?
If that's the case, you can have users instantiate it in A and the
__init__ method will do the set of actions you need -- this will be just
as easy for the user as the alternative.

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Can't seem to start on this

2013-01-03 Thread Mitya Sirenef

On 01/03/2013 02:30 PM, Kene Meniru wrote:

Mitya Sirenef wrote:



 I'm not familiar with POV-Ray. I want to note that with python standard
 style, class names look like this: ClassName, instances look like this:
 instance_name; it sounds like you want LMark to be an instance? Or you
 want instances in A to use class naming style?


 Think of A as an extension of the user interface. I want to make the
 user's life as easy as possible and in this case, part of that is to 
write
 as few text as possible. Using the abbreviated LMark is laziness on 
my part.
 I wanted to differentiate the boundary class LinearMark, which the 
user will

 type in A from the entity class LMark which will have the actual data
 about a linear mark object. LMark is actually called LinearMarkData.

 Second, is the LMark instance only used to perform one set of actions?
 If that's the case, you can have users instantiate it in A and the
 __init__ method will do the set of actions you need -- this will be just
 as easy for the user as the alternative.

 -m


 So far this is working for me. I am not sure if you mean something
 different. I have a command in A like:

 Site(New Site, borderNum) # Creates a building site object in B

 In B, the Site class (which is a subclass of the main class that
 coordinates the creation of the entire building) receives this call,
 processes the parameters with any required calculations and calls 
another
 class called SiteData (from module C) which generates the object 
called
 New Site with the number of boundaries provided. Site then stores 
SiteData
 in a dictionary provided in its super class. The super class 
coordinates the

 creation of the entire building so all objects can interact with the
 properties of the objects in the dictionary (of building components).

 So in effect no instantiation is performed in A. The user calls 
classes in
 B with the appropriate parameters to create the building components 
which

 are then created and stored for later access by other components.


Ok but if the user creates two sites, how does he then manipulate them,
if you are not binding instances in A? (e.g. you are not doing site1 =
Site(New Site)).

If the user only ever needs one site, that's fine.

 -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Can't seem to start on this

2013-01-03 Thread Mitya Sirenef

On 01/03/2013 07:08 PM, Kene Meniru wrote:

LinearSide.put(Dining, (x,y,z))  # moves 'Dining' to x,y,z location

The put function of the LinearSide boundary class finds Dining (which is
an entity class called LinearSideData) in the dictionary and then allows
this LinearSideData class to calculate its new location using the x,y,z
values provided.



That's what I thought, just wanted to confirm.

However, if your objective to make it as easy for the user as possible,
is it not easier to bind dining to a name and then do this?:

dining.move(x, y, z)


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Can't seem to start on this

2013-01-03 Thread Mitya Sirenef

On 01/03/2013 07:43 PM, Kene Meniru wrote:

Mitya Sirenef wrote:


That's what I thought, just wanted to confirm.

However, if your objective to make it as easy for the user as possible,
is it not easier to bind dining to a name and then do this?:

dining.move(x, y, z)


Absolutely. I just found that out after replying to your comment! It
actually decreases typing. Also discovered the module Logging. Interesting
using python indeed :-)




I agree -- Python is really nice, I'm glad you seem to be
enjoying it!

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: New to python, do I need an IDE or is vim still good enough?

2013-01-02 Thread Mitya Sirenef

On 01/02/2013 04:33 PM, Michael Torrie wrote:

On 01/01/2013 11:43 AM, Mitya  Sirenef wrote:

 Therefore, deleting 3 WORDs is 3daW (mnemonic: del a WORD 3 times).

 Interesting. I typically use just d3w. 3daW seems to delete 3 lines
 for me, the same result as d3enter. Another favorite command is d or
 c followed by a number and then the right arrow key, for manipulating
 letters instead of words.


d3w is a different command, it means delete 3 words *ahead* from cursor.
e.g.:

func() lst[] lst2[ind] foo bar

Now put the cursor on letter 'c' (4th from beginning) and use the
command 3daW, it should delete the 3 WORDs, leaving just the 'foo bar'.






 In any case, I can be way more productive with just a few commands
 (maybe 3 or 4 commands or concepts) in Vim than in almost any GUI
 editor. In my experience, Vim users almost always find this to be true
 for them as well. Vim really hits the sweet spot for productivity and
 usability. The only thing about Vim that I find clunky is how code
 folding macros work, and also code completion hacks (which I have never
 needed anyway).


Vim does have a lot of flaws, alas. The highest ones on my list is that
python integration (as a scripting language) is wonky; python can't be
run alongside Vim process; double-escaping is terrible (stuff like
\ltblah); process of development is slowed down too much by
over-emphasis on backwards compatibility; the way arguments and counts
are implemented between mappings, commands and functions is byzantine
and way overcomplicated..

That said, Vim is still 1k% better than emacs and 3k% better than
anything else :-).

It's really odd that large companies like google, microsoft, ibm,
facebook don't all chip in to give Bram a few million to hire a few
people and knock the Vim out into the stratosphere, given how much these
companies' employees used Vim for many hours, daily, to great benefit
for said companies. Oh well.

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: New to python, do I need an IDE or is vim still good enough?

2013-01-02 Thread Mitya Sirenef

On 01/02/2013 10:17 PM, Wayne Werner wrote:

On Tue, 1 Jan 2013, Mitya Sirenef wrote:


On 01/01/2013 02:02 PM, Roy Smith wrote:
That's true with Vim, as well, especially when I'm making a custom
mapping and I can NEVER remember what some combination does, even though
if I actually needed to use it, it pops right out, so to find out, I
have to try it and then I say, of course, dammit, I use this command 50
times every single day!; so it's a curious case of one-directional
memory.


I've found writing macros helps me a lot in this regard. I do 
qastuffqaP

fairly frequently.

-W



But how does that help remember commands?

(I also use recording, but I use qq because it's easier to type
and I have a Q mapping that plays back q register).

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Can't seem to start on this

2013-01-02 Thread Mitya Sirenef

On 01/02/2013 11:32 PM, Kene Meniru wrote:

This sounds so simple but being  new to python I am finding it hard to get

 started. I want to create a module which I will call B. There will be
 other modules called C, D, etc, which will most likely be 
imported in
 B. Then I want the user to import B ONLY into another file I will 
call

 A in which commands such as the following will be entered:

 snap_size = 10
 LinearMark(name)
 LinearMark.put(name, length, rotation, (x,y,z))

 The file A allows the user to enter commands that provide global 
variables
 as well as to use classes provided in modules C, D, etc, in the 
manner

 shown in the sample above. For example snap_size is a global setting.
 LinearMark(name) creates a linear mark of the provided name.
 LinearMark.put(...) places the LinearMark object using the provided
 parameters, etc.

 How can I make this possible? I am guessing I have to instantiate the
 classes in file B but typing LinearMark(name) in file A generates an
 error. Eventually I will provide a gui but I want to separate usage 
so there

 is no dependence on the gui to run this application.

 Please help.




Where is snap_size from? Where is LinearMark from? You don't need to
instantiate LinearMark in B, do it in A.

What error do you get when you instantiate LinearMark in A? Please
paste.

If LinearMark is imported in from C, you can do:

B.py
from C import LinearMark

A.py
from B import LinearMark

lmark = LinearMark(name)
lmark.put(...)

Or do you want to use class method of LinearMark?

Since you don't provide any code, it's really hard to tell what you're
doing

 HTH, -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Can't seem to start on this

2013-01-02 Thread Mitya Sirenef

On 01/03/2013 12:32 AM, Kene Meniru wrote:

Mitya Sirenef wrote:




 Where is snap_size from? Where is LinearMark from? You don't need to
 instantiate LinearMark in B, do it in A.


 I want to hide as much of the python syntax from the file A so the 
user
 just concentrates on using the classes as illustrated. snap_size is a 
global
 setting. LinearMark is a class in module C described as LMark but 
with the

 interface class as LinearMark in B.


Well, that might be ok depending on what you need the instances to do.
Often instantiation provides some kind of customization that makes
instance different from other instances. If you do that for your users,
they won't be able to customize their instances, unless you provide a
separate 'initialize' method, but then it's just as much work for the
users to use that method as compared to passing args on instantiation.

So, how many instances do you want to make.. what kind of different
functionality / properties they will have?

 - mitya



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: New to python, do I need an IDE or is vim still good enough?

2013-01-01 Thread Mitya Sirenef

On 12/31/2012 10:46 PM, Steven D'Aprano wrote:

On Sat, 29 Dec 2012 14:00:23  -0500, Mitya Sirenef wrote:


 I think the general idea is that with editors like Vim you don't get
 distracted by having to do some kind of an editor task, letting you keep
 your full attention on the code logic. For instance, if I need to change
 a block inside parens, I type ci) (stands for change inside parens),
 while with a regular editor I'd have to do it manually and by the time
 I'm done, I'd forget the bigger picture of what I'm doing with the code.

 See, by the time I remembered what obscure (to me) command to type, or
 searched the help files and the Internet, I'd have forgotten what the
 hell it was I was trying to do. Well, almost. My memory is not quite that
 bad, but it would certainly be a much bigger disruption to my coding than
 just doing the edit by hand.


I would agree with you if I had to look up a command every time I use
it. The way it really works for me is that either I use a command often
enough that I remember it from the first time I looked it up, and the
memory is reinforced every time I use it, OR it's such a rare command
that looking it up is not a problem (obviously if it's faster to do it
by hand than to look it up, I can do that, as well, which in Vim means
using lower level commands that still don't require you leaving the home
row.)




 I do love the power of command line tools, but I think that for rich
 applications like editors, the interface is so clunky that I'd rather use
 a less-powerful editor, and do more editing manually, than try to
 memorize hundreds of commands.


Clunky is the last word I'd use to describe it (ok maybe for Emacs :-)
I probably remember about 200 commands, plus or minus, but a lot of them
fit into a consistent scheme which makes them much easier to remember:
there's (change delete yank vis-select)*(inner outer)*(letter word WORD 
paragraph )]} )


(Where word includes 'keyword' characters and WORD is separated by spaces).

So, these correspond to commands (cdyv)(ia)(lwWp)]}).

Therefore, deleting 3 WORDs is 3daW (mnemonic: del a WORD 3 times).

I think I have a pretty bad memory but I remembered all of these
commands a few at a time without too much trouble. And they're extremely
useful even now as I'm editing this email.





 With a GUI app, I can run the mouse over the menus and see a high-level
 overview of everything the app can do in a matter of a second or two.
 (Perhaps three or five seconds if the app over-uses hierarchical menus.)
 But with a text interface, commands are much less discoverable. I can
 also use *spacial* memory to zero in on commands much more easily than
 verbal memory -- I have no idea whether the command I want is called
 Spam or Ham or Tinned Bully Beef, but I know it's in the top
 quarter of the Lunch menu, and I will recognise it when I see it.


It's not a binary choice, GVim has a customizable menu system with a
simple text format for adding menus (from Vim manual):

To create a new menu item, use the :menu commands.  They are 
mostly like
the :map set of commands but the first argument is a menu item 
name, given

as a path of menus and submenus with a '.' between them. eg:

   :menu File.Save  :wCR
   :inoremenu File.Save  C-O:wCR
   :menu Edit.Big\ Changes.Delete\ All\ Spaces  :%s/[ ^I]//gCR




 On the other hand, it's a lot harder to use a GUI app over a slow SSH
 connection to a remote machine in a foreign country over a flaky link
 than it is to use a command line or text-interface app.


With GVim, you can use gui menus just as easily when you open a file
remotely.





 Another example: ap stands for indent a paragraph (separated by blank
 lines). And there are many dozens if not hundreds such commands that
 let you stay focused on the logic of your code.

 Ah yes, the famous a for indent mnemonic. *wink*


Well, 'a' is mnemonic for 'a', fittingly ;-).  is for indent, just as 
is for dedent. 'a' is to distinguish from inner paragraph command,
which omits blank lines after the paragraph (which matter for other
commands, but not for indent/dedent.): ip .


 - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: New to python, do I need an IDE or is vim still good enough?

2013-01-01 Thread Mitya Sirenef

On 01/01/2013 02:02 PM, Roy Smith wrote:

In article  mailman.1528.1357065822.29569.python-l...@python.org,

 Mitya Sirenef msire...@lightbird.net wrote:

 Clunky is the last word I'd use to describe it (ok maybe for Emacs :-)
 I probably remember about 200 commands, plus or minus, but a lot of them
 fit into a consistent scheme which makes them much easier to remember

 At some point, it becomes muscle memory, which means you don't even
 consciously know what you're typing. Your brain just says, delete the
 next three words and your fingers move in some way which causes that to
 happen. This is certainly true with emacs, and I imagine it's just as
 true with people who use inferior editors :-)

 I used to do a bunch of pair programming with another emacs power user.
 Every once in a while, one of us would say something like, What did you
 just do?, when the other performed some emacs technique one of us was
 not familiar with. Invariably, the answer would be, I don't know, and
 you would have to back up and recreate the key sequence. Or, just run
 C-? l, which tells you the last 100 characters you typed.

 Case in point. I use C-? l moderately often, when I make some typo and
 I'm not sure what I did wrong. But, despite the fact that my fingers
 now how to perform show me the last stuff I typed, I had to go hunting
 to find the actual keystrokes which does that when typing the above
 paragraph :-)


That's true with Vim, as well, especially when I'm making a custom
mapping and I can NEVER remember what some combination does, even though
if I actually needed to use it, it pops right out, so to find out, I
have to try it and then I say, of course, dammit, I use this command 50
times every single day!; so it's a curious case of one-directional
memory.


subliminal 1-nanosecond BLINK TAG comment=hope this works, fingers
crossed content=let's face it, Vim is BETTER as it has always been!



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Considering taking a hammer to the computer...

2012-12-31 Thread Mitya Sirenef

On 12/31/2012 06:42 PM, worldsbiggestsabres...@gmail.com wrote:

Hey :)


 I'm trying to help my son with an assignment and spending hours 
making an inch of progress. I know nothing about programming and I'm 
trying to learn, on my own, at a rate faster than possible. I would love 
a little help!


 My son is taking an introductory course and his assignment is to use 
the loops for and while to create a program which calculates a hotel's 
occupancy rate. He has managed all of the inputs but needs help with 
the following:


 1) The first question asked is how many floors are in the hotel - and 
then the questions are asked floor by floor. We can't figure out how to 
get the program to stop questioning when the number of floors is reached.


 2) He has programmed specific calculations for each floor, and now 
needs to have calculations for the entire hotel based on the input about 
each floor.



 Here is what he has done so far:


 #This program will calculate the occupancy rate of a hotel
 floor_number = 0


 number_of_floors = int(input(How many floors are in the hotel?: ))
 while number_of_floors  1:
 print (Invalid input!)
 number_of_floors = input(Enter the number of floors in the hotel: )
 while number_of_floors  1:
 floor_number = floor_number + 1
 print()
 print (For floor #,floor_number)
 rooms_on_floor = int(input(How many rooms are on the floor ?:  ))
 while rooms_on_floor  10:
 print (Invalid input!)
 rooms_on_floor = int(input(Enter the number of rooms on floor: ))

 occupied_rooms = int(input(How many rooms on the floor are 
occupied?: ))


 #CALCULATE OCCUPANCY RATE FOR FLOOR
 occupancy_rate = occupied_rooms / rooms_on_floor
 print (The occupancy rate for this floor is ,occupancy_rate)



 The following is what we believe needs to go in the program at the 
end except we can't figure out how to calculate it and make it all work 
:/ (alot of the terms have nothing at all to identify them yet...)


 hotel_occupancy = total_occupied / total_rooms
 print (The occupancy rate for this hotel is ,hotel_occupancy)
 print (The total number of rooms at this hotel is ,total_rooms)
 print (The number of occupied rooms at this hotel is ,total_occupied)
 vacant_rooms = total_rooms - total_occupied
 print (The number of vacant rooms at this hotel is ,vacant_rooms)

 We've searched and read and we found things about the break and 
pass commands but his teacher will not allow them because they haven't 
been taught yet.


 If you have any ideas and can take a minute to help, that would be 
great :)


 Thank you!


Hi! First I want to note that this task would be easier and better to do
with a break statement, so it's quite unfortunate that the teacher did
not cover the right tools (and very basic ones, in fact) and yet given
this task.

Another question: are you allowed to use functions? (I'm guessing not).

You can do this task much easier if you write it out in pseudo code
before you go to python code. For example, to convert your existing
code to pseudo code:

* set floor_number to 0
* get number of floors from the user

* as long as number of floors is less than 1:
* print invalid input
* get number of floors from the user

* as long as number of floors is more than 1:
* increment floor_number

* get number of rooms
* as long as number of rooms is less than 10:
* get number of rooms

* get occupied_rooms
* occupancy_rate = occupied rooms / number of rooms

* how do we keep track of total rooms and total occupied rooms here??


Does it make it easier to think about the logic of the program?

 - mitya



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Considering taking a hammer to the computer...

2012-12-31 Thread Mitya Sirenef

On 12/31/2012 07:29 PM, Mitya Sirenef wrote:



Hi! First I want to note that this task would be easier and better to do
with a break statement, so it's quite unfortunate that the teacher did
not cover the right tools (and very basic ones, in fact) and yet given
this task.

Another question: are you allowed to use functions? (I'm guessing not).

You can do this task much easier if you write it out in pseudo code
before you go to python code. For example, to convert your existing
code to pseudo code:

* set floor_number to 0
* get number of floors from the user

* as long as number of floors is less than 1:
* print invalid input
* get number of floors from the user

* as long as number of floors is more than 1:
* increment floor_number

* get number of rooms
* as long as number of rooms is less than 10:
* get number of rooms

* get occupied_rooms
* occupancy_rate = occupied rooms / number of rooms

* how do we keep track of total rooms and total occupied rooms here??


Does it make it easier to think about the logic of the program?

 - mitya




I forgot to add this:

question = How many floors are in the hotel?: 
number_of_floors = int(input(question))

while number_of_floors  1:
print(Invalid input!)
number_of_floors = int(input(question))


It's easier to save the question in a variable and use it two
times (and do the same in the next loop); it's not clear
why/if the questions should be different as you're asking
the user for the same thing.

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Considering taking a hammer to the computer...

2012-12-31 Thread Mitya Sirenef

On 12/31/2012 08:30 PM, worldsbiggestsabres...@gmail.com wrote:

Here is what I've learned:

1) There's a bunch of extremely helpful and wonderful people here.

2) There's a bunch of very intelligent people here.

3) I still don't have any idea what I'm doing.

4) It's New Year's Eve and I'm trying to learn Python...?

I'm going to read all of this over and over until it makes sense to me!  Thank 
you all SO MUCH!!!



You're welcome and don't hesitate to ask follow-up question,
Happy new year!

 - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-29 Thread Mitya Sirenef

On 12/29/2012 12:44 PM, Monte Milanuk wrote:
Maybe its because I'm still  just a hobbyist when it comes to coding, but I spend far more time 
'thinking' about what I'm doing than typing things in... so shaving a 
few seconds here and there are less important to me.



I think the general idea is that with editors like Vim you don't get
distracted by having to do some kind of an editor task, letting you keep
your full attention on the code logic. For instance, if I need to change
a block inside parens, I type ci) (stands for change inside parens),
while with a regular editor I'd have to do it manually and by the time
I'm done, I'd forget the bigger picture of what I'm doing with the code.
Another example: ap stands for indent a paragraph (separated by blank
lines). And there are many dozens if not hundreds such commands that
let you stay focused on the logic of your code.

The trade-off, of course, is that you have to remember all (or most) of
the commands, but I figured if I spend the next 20-30+ years programming
in some version of Vim, it's well worth the initial investment.

By the way, to help me remember the commands, I wrote a small script
that lets me type in a few characters of a command or its description
and filters out the list of matching commands. It really helps,
especially when I change a lot of my mappings.

 - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: dict comprehension question.

2012-12-29 Thread Mitya Sirenef

On 12/29/2012 02:48 PM, Quint Rankid wrote:

Newbie question.  I've googled a little and haven't found the answer.

Given a list like:
w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
I would like to be able to do the following as a dict comprehension.
a = {}
for x in w:
 a[x] = a.get(x,0) + 1
results in a having the value:
{1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}

I've tried a few things
eg
a1 = {x:self.get(x,0)+1 for x in w}
results in error messages.

And
a2 = {x:a2.get(x,0)+1 for x in w}
also results in error messages.

Trying to set a variable to a dict before doing the comprehension
a3 = {}
a3 = {x:a3.get(x,0)+1 for x in w}
gets this result, which isn't what I wanted.
{1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}

I'm not sure that it's possible to do this, and if not, perhaps the
most obvious question is what instance does the get method bind to?

TIA


Will this do?:

 w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
 {x: w.count(x) for x in w}
{1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}


 - mitya

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: dict comprehension question.

2012-12-29 Thread Mitya Sirenef

On 12/29/2012 03:01 PM, Mitya Sirenef wrote:

On 12/29/2012 02:48 PM, Quint  Rankid wrote:

 Newbie question. I've googled a little and haven't found the answer.

 Given a list like:
 w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
 I would like to be able to do the following as a dict comprehension.
 a = {}
 for x in w:
 a[x] = a.get(x,0) + 1
 results in a having the value:
 {1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}

 I've tried a few things
 eg
 a1 = {x:self.get(x,0)+1 for x in w}
 results in error messages.

 And
 a2 = {x:a2.get(x,0)+1 for x in w}
 also results in error messages.

 Trying to set a variable to a dict before doing the comprehension
 a3 = {}
 a3 = {x:a3.get(x,0)+1 for x in w}
 gets this result, which isn't what I wanted.
 {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}

 I'm not sure that it's possible to do this, and if not, perhaps the
 most obvious question is what instance does the get method bind to?

 TIA

 Will this do?:

  w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
  {x: w.count(x) for x in w}
 {1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}


 - mitya


I should probably add that this might be inefficient for large lists as
it repeats count for each item. If you need it for large lists, profile
against the 'for loop' version and decide if performance is good enough
for you, for small lists it's a nice and compact solution.

In a more general case, you can't refer to the list/dict/etc
comprehension as it's being constructed, that's just not a design goal
of comprehensions.

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Facing issue with Python loggin logger for printing object value

2012-12-29 Thread Mitya Sirenef

On 12/29/2012 03:50 PM, Morten Engvoldsen wrote:

Hi Dave,

 It is able to log the message with:
 logger.debug(value of payment_line is  +repr(payment_line))

 The output is:
 value of payment_line is []

 So it means payment_line is an empty list, so may be it could be 
reason it's not able to enter into the loop since the message in the for 
loop is not logged in the log file.


 Thanks and good night.. :)


You can easily test how iteration over empty list works:



l=[]

 for x in l: print(x)
...




i.e. nothing is printed because loop runs 0 times.


 -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: dict comprehension question.

2012-12-29 Thread Mitya Sirenef

On 12/29/2012 03:15 PM, Joel Goldstick wrote:




On Sat, Dec 29, 2012 at 3:09 PM, Mitya Sirenef msire...@lightbird.net 
mailto:msire...@lightbird.net wrote:


On 12/29/2012 03:01 PM, Mitya Sirenef wrote:

On 12/29/2012 02:48 PM, Quint  Rankid wrote:

 Newbie question. I've googled a little and haven't found the
answer.

 Given a list like:
 w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
 I would like to be able to do the following as a dict
comprehension.
 a = {}
 for x in w:
 a[x] = a.get(x,0) + 1
 results in a having the value:
 {1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}

 I've tried a few things
 eg
 a1 = {x:self.get(x,0)+1 for x in w}
 results in error messages.

 And
 a2 = {x:a2.get(x,0)+1 for x in w}
 also results in error messages.

 Trying to set a variable to a dict before doing the comprehension
 a3 = {}
 a3 = {x:a3.get(x,0)+1 for x in w}
 gets this result, which isn't what I wanted.
 {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}

 I'm not sure that it's possible to do this, and if not, perhaps the
 most obvious question is what instance does the get method bind to?

 TIA

 Will this do?:

  w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
  {x: w.count(x) for x in w}
 {1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}


 - mitya


I should probably add that this might be inefficient for large
lists as
it repeats count for each item. If you need it for large lists,
profile
against the 'for loop' version and decide if performance is good
enough
for you, for small lists it's a nice and compact solution.

In a more general case, you can't refer to the list/dict/etc
comprehension as it's being constructed, that's just not a design goal
of comprehensions.


Would this help:

  w = [1,2,3,1,2,4,4,5,6,1]
  s = set(w)
  s
 set([1, 2, 3, 4, 5, 6])
  {x:w.count(x) for x in s}
 {1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}




Indeed, this is much better -- I didn't think of it..


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-29 Thread Mitya Sirenef

On 12/29/2012 04:52 PM, Roy Smith wrote:

In the big for loop, a couple  of lines down, no, not there, the other

 for loop, yeah, now go down a couple of lines, no that's too far, back
 up one. Yeah there. On that line, why do you ...

 with:

 On line 647, why do you ...


It's even better when it prints line # from top of screen, I have a
handy mapping that jumps directly to a line # and it's much easier to
type 23space or 9space when you jump around a lot.

 - mitya

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-29 Thread Mitya Sirenef

On 12/29/2012 05:30 PM, Chris Angelico wrote:

In the big for loop, a couple of lines down, no, not there, the other
for loop, yeah, now go down a couple of lines, no that's too far, back
up one.  Yeah there.  On that line, why do you ...

with:

On line 647, why do you ...

Absolutely! Though it's roughly as good to have the current cursor
position shown in a status line somewhere, and takes up less real
estate.


I have to disagree -- if someone is standing next to you
and they want to refer to a particular line, they can't
really tell you move the cursor to that line there, so I
can read its line number from status line and then tell
you I'm referring to that line.

 - mitya

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Wrapping statements in Python in SPSS

2012-12-28 Thread Mitya Sirenef

On 12/28/2012 12:33 PM, alankrin...@gmail.com wrote:
I think 396 just comes from the  end of the Python loop, without indicating which line in the loop is 

at issue.

 Here is the full code from this section of the loop:


 for (
 msr, brk, dmn, src, dspd1, dspd2, dspd3, dspd4, dspd5, dspd6, dspd7, 
dspd8, dspd9, dspd10, dspd11, dspd12,
 period1, period2, period3, period4, period5, period6, period7, 
period8, period9, period10, period11, period12

 ) in zip(
 Measure, BreakVariable, Dimension, Sources, 
DimensionSourceTimeFrame1, DimensionSourceTimeFrame2, 
DimensionSourceTimeFrame3, DimensionSourceTimeFrame4,
 DimensionSourceTimeFrame5, DimensionSourceTimeFrame6, 
DimensionSourceTimeFrame7, DimensionSourceTimeFrame8, 
DimensionSourceTimeFrame9,
 DimensionSourceTimeFrame10, DimensionSourceTimeFrame11, 
DimensionSourceTimeFrame12,
 TimeFrame1, TimeFrame2, TimeFrame3, TimeFrame4, TimeFrame5, 
TimeFrame6, TimeFrame7, TimeFrame8, TimeFrame9, TimeFrame10, 
TimeFrame11, TimeFrame12

 ):


 spss.Submit(r


 Alan



By the way, when lines run so long they can get hard to manage, edit,
understand, et cetera. You should consider setting things up cleanly
before doing the loop and using a list of names for columns like so:


def main():
l1, l2   = [1,2], [3,4]
zipped   = zip(l1, l2)
colnames = first second.split()

for columns in zipped:
coldict = dict(zip(colnames, columns))
print(coldict, coldict)

main()


This produces output:

coldict {'second': 3, 'first': 1}
coldict {'second': 4, 'first': 2}

.. and then you can pass the coldict on to your string.

 - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Wrapping statements in Python in SPSS

2012-12-28 Thread Mitya Sirenef

On 12/28/2012 12:55 PM, Mitya Sirenef wrote:

On 12/28/2012 12:33 PM, alankrin...@gmail.com wrote:
I think 396 just comes from the  end of the Python loop, without 
indicating which line in the loop is 

at issue.

 Here is the full code from this section of the loop:


 for (
 msr, brk, dmn, src, dspd1, dspd2, dspd3, dspd4, dspd5, dspd6, dspd7, 
dspd8, dspd9, dspd10, dspd11, dspd12,
 period1, period2, period3, period4, period5, period6, period7, 
period8, period9, period10, period11, period12

 ) in zip(
 Measure, BreakVariable, Dimension, Sources, 
DimensionSourceTimeFrame1, DimensionSourceTimeFrame2, 
DimensionSourceTimeFrame3, DimensionSourceTimeFrame4,
 DimensionSourceTimeFrame5, DimensionSourceTimeFrame6, 
DimensionSourceTimeFrame7, DimensionSourceTimeFrame8, 
DimensionSourceTimeFrame9,
 DimensionSourceTimeFrame10, DimensionSourceTimeFrame11, 
DimensionSourceTimeFrame12,
 TimeFrame1, TimeFrame2, TimeFrame3, TimeFrame4, TimeFrame5, 
TimeFrame6, TimeFrame7, TimeFrame8, TimeFrame9, TimeFrame10, 
TimeFrame11, TimeFrame12

 ):


 spss.Submit(r


 Alan



By the way, when lines run so long they can get hard to manage, edit,
understand, et cetera. You should consider setting things up cleanly
before doing the loop and using a list of names for columns like so:


def main():
l1, l2   = [1,2], [3,4]
zipped   = zip(l1, l2)
colnames = first second.split()

for columns in zipped:
coldict = dict(zip(colnames, columns))
print(coldict, coldict)




Should really be 'for column in zipped:' !

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Wrapping statements in Python in SPSS

2012-12-28 Thread Mitya Sirenef

On 12/28/2012 01:05 PM, Mitya Sirenef wrote:

On 12/28/2012 12:55 PM, Mitya  Sirenef wrote:

 On 12/28/2012 12:33 PM, alankrin...@gmail.com wrote:
 I think 396 just comes from the end of the Python loop, without 
indicating which line in the loop is

 at issue.
 
  Here is the full code from this section of the loop:
 
 
  for (
  msr, brk, dmn, src, dspd1, dspd2, dspd3, dspd4, dspd5, dspd6, 
dspd7, dspd8, dspd9, dspd10, dspd11, dspd12,
  period1, period2, period3, period4, period5, period6, period7, 
period8, period9, period10, period11, period12

  ) in zip(
  Measure, BreakVariable, Dimension, Sources, 
DimensionSourceTimeFrame1, DimensionSourceTimeFrame2, 
DimensionSourceTimeFrame3, DimensionSourceTimeFrame4,
  DimensionSourceTimeFrame5, DimensionSourceTimeFrame6, 
DimensionSourceTimeFrame7, DimensionSourceTimeFrame8, 
DimensionSourceTimeFrame9,
  DimensionSourceTimeFrame10, DimensionSourceTimeFrame11, 
DimensionSourceTimeFrame12,
  TimeFrame1, TimeFrame2, TimeFrame3, TimeFrame4, TimeFrame5, 
TimeFrame6, TimeFrame7, TimeFrame8, TimeFrame9, TimeFrame10, 
TimeFrame11, TimeFrame12

  ):
 
 
  spss.Submit(r
 
 
  Alan
 
 

 By the way, when lines run so long they can get hard to manage, edit,
 understand, et cetera. You should consider setting things up cleanly
 before doing the loop and using a list of names for columns like so:


 def main():
 l1, l2 = [1,2], [3,4]
 zipped = zip(l1, l2)
 colnames = first second.split()

 for columns in zipped:
 coldict = dict(zip(colnames, columns))
 print(coldict, coldict)



 Should really be 'for column in zipped:' !

 -m


Doh - the code is good, but I got a little confused with variable names.
This should be more like it:

def main():
c1, c2   = [1,2], [3,4]
zipped   = zip(c1, c2)
colnames = first second.split()

for values in zipped:
valdict = dict(zip(colnames, values))
print(valdict, valdict)

main()


 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Finding the name of a function while defining it

2012-12-27 Thread Mitya Sirenef

On 12/27/2012 02:45 AM, Abhas Bhattacharya wrote:

On Thursday, 27 December 2012 10:22:15 UTC+5:30, Tim Roberts  wrote:

Abhas Bhattacharya abhasbhattachar...@gmail.com wrote:


While I am defining a function, how can I access the name (separately as
string as well as object) of the function without explicitly naming
it(hard-coding the name)?
For eg. I am writing like:
def abc():
#how do i access the function abc here without hard-coding the name?



Why?  Of what value would that be?



Note that I'm not merely being obstructionist here.  What you're asking

here is not something that a Python programmer would normally ask.  The

compiled code in a function, for example, exists as an object without a

name.  That unnamed object can be bound to one or more function names, but

the code doesn't know that.  Example:



def one():

 print( Here's one )



two = one



That creates one function object, bound to two names.  What name would you

expect to grab inside the function?



Even more obscure:



two = lamba : one

one = two



Which one of these is the name of the function?

--

Tim Roberts, t...@probo.com

Providenza  Boekelheide, Inc.

It is of quite value to me.
Because I have this situation:
I have used a dictionary with function_name:value pair in the top of the 
code. Now when some function is called, I need to print the value assigned to its name in 
the dictionary (the functions are defined after the dictionary). Now there is only one 
bad way-around for me: I need to hard-code the name in the function like this:
def function_name():
 print(dict_name.get(function_name))
but ofcourse it is a bad thing to do because I have a lot of this type of  
functions. It would be better if I can can use the same code for all of them, 
because they are all essentially doing the same thing.

Now, for your questions:
If i call one() and two() respectively, i would like to see one and two.
I dont have much knowledge of lambda functions, neither am i going to use them, 
so that's something I cant answer.


How about defining a function that prints value and then calls a function?

def call(func_name):
  print(mydict[func_name])
  globals()[func_name]()


You could also define a custom class that does the same thing on attribute
lookup and do something like Call.func_name() .

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Finding the name of a function while defining it

2012-12-27 Thread Mitya Sirenef

On 12/27/2012 03:26 AM, Abhas Bhattacharya wrote:

On Thursday, 27 December 2012 13:33:34 UTC+5:30, Mitya Sirenef  wrote:

How about defining a function that prints value and then calls a function?



def call(func_name):

print(mydict[func_name])

globals()[func_name]()





You could also define a custom class that does the same thing on attribute

lookup and do something like Call.func_name() .



   -m



--

Lark's Tongue Guide to Python: http://lightbird.net/larks/

Can you explain me what this means?
globals()[func_name]()


globals() is a globals dictionary that maps function
names to function objects (along with other things),
so we get the function object by name and then
run it.

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Can you please help me?

2012-12-26 Thread Mitya Sirenef

On 12/26/2012 04:40 PM, 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!


This is the code:


shop_again = 'y'

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

 elif (customer == 1):
 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: ))


 if (order == 1):
 yoda = eval(input(How many Yoda Figures do you want? : ))
 total = 10 * yoda
 print(Total:, total)
 print(Current order:, yoda, at, total)
 if (order == 2):
 movie = eval(input(How many Star Wars Movie DVDs do you want? : ))
 total = 20 * movie
 print(Total:, total)
 print(Current order:, movie, at, total)
 if (order == 3):
 legos = eval(input(How many Death Star Lego Sets do you want? : ))
 total = 200 * legos
 print(Total:, total)
 print(Current order:, legos, at, total)
 
 shop_again = input(Would you like to keep shopping? 'Y' for yes, 'N' for no: )

 print()
print(Your order before shipping and discounts: ,total)
print()
print(Answer a trivia question for a discount!)
discount = eval(input(On what planet did Yoda live when Luke Skywalker first met 
him? 1) Earth 2) Dagobah 3) Pluto :))
if (discount == 1):
 print(Sorry, that answer was wrong!)
if (discount == 2):
 print(That's correct, you get a 10% discount!)
if (discount == 3):
 print(Sorry, that answer was wrong!)
print()
if (discount == 2):
 (total * .9)
 print(Your total before shipping: ,total)
 


print(1) Regular Shipping: 3-4 business days, $5.00 per $50 ordered. 2) Express 
Shipping: overnight, $10 per $50 ordered. 3) Super Saver Shipping: 7-10 business days, 
free.)
shipping = eval(input(Please select the shipping method you want: ))

if (shipping == 1):
 
 total == total % 50

 total == total * 5
 print(Your total is: ,total)
if (shipping == 2):
 total == total/50
 total == total % 50
 total == total * 10
 print(Your total is: ,total)
if(shipping == 3):
 print(Your total is: ,total)
print()
print(Thanks for shopping here! Please come again!)
  



I think before worrying about totals, et cetera, you need
to approach this in a more modular way. Here's an
example of using 3 functions to do the product menu,
where each choice gets 1 count of product, without
option to specify quantity:


from collections import defaultdict

prompt  =  
cart= defaultdict(int)
product_tpl = %d) %-15s [ $%d ]
products= {
1: (Yoda, 10),
2: (DVD, 20),
3: (Lego Set, 200)
}

def product_menu():
while True:
print(Select item to order, 'f' when finished.)
for pid, prod in products.items():
print(product_tpl % (pid, prod[0], prod[1]))

inp = input(prompt)
if inp == 'f': return
product = getproduct(inp)

if product : cart[product] += 1
else   : print(Invalid Input)
print()

def getproduct(inp):
try:
return products[int(inp)]
except (ValueError, KeyError):
return None

def main():
product_menu()

for (name, price), count in cart.items():
print(product: %s, price: %d, count: %d % (name, price, count))
total = sum(price*count for (name, price), count in cart.items())
print(Total for the order is: $%d % total)

main()


A few notes:

The code is a lot simpler when you define the collection of products
outside of the selection loop. It also means you can reuse the products
dict in other functions.

It's easier, usually, to work with 'while True' loops because you have
precise control of where it breaks, either with a break statement
or with a return. In the type of loop you used, you had to define
the default value at the top, then change that value, and then
by looking at 

Re: Can you please help me?

2012-12-26 Thread Mitya Sirenef

On 12/26/2012 06:21 PM, bobflipperdoo...@gmail.com wrote:

Thank you very much for your reply.  I actually just deleted this post as you 
were replying!  I had figured out a few things and then got confused about a 
few others :/  If you have a chance, can you look at the other post?  Thank 
you!!



Fortunately, my reply is as relevant to the 2nd post just as much as to 
the 1st :-).

I must be able to see future!

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Please help if you can!

2012-12-26 Thread Mitya Sirenef

On 12/26/2012 07:04 PM, 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.



I'm sorry to hear that, I just want to clarify - the teacher did not yet 
cover

the use of lists, dictionaries and functions?

If that's the case, I have to agree with you that he's probably not a very
good teacher because this task can be done much easier and better
with those 3 concepts, all of which are very easy. If you are barred from
using them, Joshua's post will be most helpful.

If you are curious about the 3 concepts I mentioned, they are covered
in the official python tutorial, but the quick rundown is:

list: a list of items, e.g. a shopping list:

shoplist = [tea, cake, blueberries]

dictionary: a collection of keys/values, like words/definitions in a 
dictionary:


shopping_cart = {yoda: 3, dvd: 5}  # 3 of yoda figures, 5 dvds


function: a way to group a bunch of code together:

def main():
  # do something
  # do something else
  # la la la

main()

The nice thing about functions is that if you need to repeat
something, let's say, two thousand times, you just call the
function two thousand times, e.g.:

for x in range(2000): main()

Which is much easier than typing in two thousand copies of the same code
 (don't ask me how I know!)

 - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Please help if you can!

2012-12-26 Thread Mitya Sirenef

On 12/26/2012 08:00 PM, Chris Angelico wrote:

On Thu, Dec 27, 2012 at 11:45 AM, Joshua Landau
joshua.landau...@gmail.com wrote:

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!)


One of the regulars on the list has posted a run-down of how to post
from Google Groups without annoying everyone, and among other things,
it recommends manually deleting all the blank lines. To my mind,
though, this would be insane and inane tedium. I recommend signing up



I have to agree - I saw that howto as well and it occurred to me
that if we have to delete blank lines manually we might
as well use postal pigeons with tiny little papyrus scrolls -
at least those don't insert blank lines automatically!

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Please help if you can!

2012-12-26 Thread Mitya Sirenef

On 12/26/2012 08:23 PM, Chris Angelico wrote:

On Thu, Dec 27, 2012 at 12:17 PM, Mitya Sirenef msire...@lightbird.net wrote:

I have to agree - I saw that howto as well and it occurred to me
that if we have to delete blank lines manually we might
as well use postal pigeons with tiny little papyrus scrolls -
at least those don't insert blank lines automatically!

Yes, but they have poor latency, and packet loss due to hawks is a
major problem. But an RFC 1149 network is plausible, even if not
viable in most situations.

ChrisA


I don't know, I played starcraft II by pigeon-net and it
worked just fine. Yes, latency is quite bad but it gives
you more time to think about strategy...

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: How to get time.strptime()?

2012-12-26 Thread Mitya Sirenef

On 12/26/2012 10:09 PM, Gnarlodious wrote:
This is problem that has unduly vexed me. When you start learning 
Python they don't tell you about these sharp edges. Someone needs to 
explain. -- Gnarlie 


In fact, if there were no bugs, there would be no need to explain nor to 
pick the

right time / place for explanations. Why doesn't Python warn that it's not
100% perfect? Are people just supposed to know this, magically?

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Command Line Progress Bar

2012-12-25 Thread Mitya Sirenef

On 12/26/2012 01:17 AM, Kevin Anthony wrote:

Hello,
I'm writing a file processing script(Linux), and i would like to have 
a progress bar.  But i would also like to be able to print messages. 
 Is there a simple way of doing this without implementing something 
like ncurses?


--
Thanks
Kevin Anthony
www.NoSideRacing.com http://www.NoSideRacing.com



Sure, you just need to print messages then the progress bar, without 
printing newline, then
sys.stdout.flush(), then in the next loop start by printing '\r' to 
erase the progress bar.


That is, if you want messages to scroll up. You can also use half a line 
for the progress
bar and the other half for a short message, then you print both with 
sys.stdout.flush()

and erase both with '\r'.

 - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Python, email temperature

2012-12-23 Thread Mitya Sirenef

On 12/23/2012 08:46 AM, KarlE wrote:

On Saturday, December 22, 2012 9:36:41 PM UTC+1, KarlE wrote:

Hi!



Im totally new to Python, and im using it on my Raspberry pi. I found a program 
that sends an email, and one that checks the temperature of my CPU, but i cant 
seem to combine the to into the funktion that i want, sending me the CPU temp 
via Email.



The two programs work very well on their own, but this doesnt work.



this works: server.sendmail(fromaddr, toaddrs, msg)

but this doesnt: server.sendmail(fromaddr, toaddrs, cpu_temperature)



despite the command print cputemp working in the same program.



When i run the program i get the error:



Traceback (most recent call last):

   File sendcpu.py, line 36, in module

 msg = cpu_temperature

NameError: name 'cpu_temperature' is not defined



Does anyone know why the program claims that cpu_temperature isnt defined, when 
it is?



Thanx!



//Alexander

Ok, im back with a little more understanding of python! I got the program 
working, every time my Raspberry Pi reboots i get an Email containing 
information about the boot and the CPU temperature.

The issue now is that there seems to be a limitation to how long the message string can 
be, about 32 letters. The code below works well, but when i add more letters to the 
string ord and pass about 32 in size the email comes through emptpy...

I cant find any information about limitations to strings in Python, or the 
email module. can anyone give me a pointer?

(the code lines my appear with different tabbings due to beeing copied from my 
raspberry pi with Putty, but this is not an issue, all the lines are on the 
same tab)

#!/usr/bin/env python
from __future__ import division
from subprocess import PIPE, Popen
import psutil
import smtplib

def get_cpu_temperature():
 process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
 output, _error = process.communicate()
 return float(output[output.index('=') + 1:output.rindex(')])


def main():
 cpu_temperature = get_cpu_temperature()
 cpu_usage = psutil.cpu_percent()

 ram = psutil.phymem_usage()
 ram_percent_used = ram.percent

 disk = psutil.disk_usage('/')
 disk_percent_used = disk.percent

 print 'CPU temperature: ', cpu_temperature

 fromaddr = 'xxx'
 toaddrs  = 'xxx'
 username = 'xxx'
 password = 'xxx'

 ord = Subject: Pi Boot, CPU:  + str(cpu_temperature)

 print len(ord)
 server = smtplib.SMTP('smtp.gmail.com:587')
 server.starttls()
 server.login(username,password)
 server.sendmail(fromaddr, toaddrs, ord)
 server.quit()

main()



I'm not sure if Raspberry Pi has it, but usually you want to
use the email module, as in example on this page:

http://docs.python.org/2/library/email-examples.html#email-examples

I think what happens is that because your message starts
with 'Subject:', it's interpreted as subject header instead of
an email. You can try adding two newlines after Subject:,
that might help... but using email module is best if possible.

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Pass and return

2012-12-21 Thread Mitya Sirenef

On 12/21/2012 03:52 AM, Duncan Booth wrote:

Mitya Sirenef msire...@lightbird.net wrote:


On 12/21/2012 12:23 AM, iMath wrote:

Pass and return
Are these two functions the same ?

def test():
  return
   
def test():

  pass


  From the point of style, of course, the latter is
much better because that's the idiomatic way
to define a no-op function. With a return, it
looks like you might have forgotten to add the
value to return or deleted it by mistake.


I would say it is *an* idiomatic way to define a no-op function.

Another idiomatic way is to use a doc-string as the only body,
that way you can also explain why you feel the need for an empty
function.



That's true, a docstring is preferable in many cases.  -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: help with making my code more efficient

2012-12-20 Thread Mitya Sirenef

On 12/20/2012 08:46 PM, larry.mart...@gmail.com wrote:

On Thursday, December 20, 2012 6:17:04 PM UTC-7, Dave Angel wrote:

On 12/20/2012 07:19 PM, larry.mart...@gmail.com wrote:


I have a list of tuples that contains a tool_id, a time, and a message. I want 
to select from this list all the elements where the message matches some 
string, and all the other elements where the time is within some diff of any 
matching message for that tool.
Here is how I am currently doing this:

No, it's not.  This is a fragment of code, without enough clues as to

what else is going.  We can guess, but that's likely to make a mess.

Of course it's a fragment - it's part of a large program and I was just showing 
the relevant parts.


First question is whether this code works exactly correctly?

Yes, the code works. I end up with just the rows I want.


Are you only concerned about speed, not fixing features?

Don't know what you mean by 'fixing features'. The code does what I want, it 
just takes too long.


As far as I can tell, the logic that includes the time comparison is bogus.

Not at all.


You don't do  anything there to worry about the value of tup[2], just whether 
some
item has a nearby time.  Of course, I could misunderstand the spec.

The data comes from a database. tup[2] is a datetime column. tdiff comes from a 
datetime.timedelta()


Are you making a global called 'self' ?  That name is by convention only
used in methods to designate the instance object.  What's the attribute
self?

Yes, self is my instance object. self.message contains the string of interest 
that I need to look for.


Can cdata have duplicates, and are they significant?

No, it will not have duplicates.


Are you including  the time building that as part of your 2 hour measurement?

No, the 2 hours is just the time to run the

cdata[:] = [tup for tup in cdata if determine(tup)]


Is the list sorted in any way?

Yes, the list is sorted by tool and datetime.


Chances are your performance bottleneck is the doubly-nested loop.  You
have a list comprehension at top-level code, and inside it calls a
function that also loops over the 600,000 items.  So the inner loop gets
executed 360 billion times.  You can cut this down drastically by some
judicious sorting, as well as by having a map of lists, where the map is
keyed by the tool.

Thanks. I will try that.


# record time for each message matching the specified message for each tool
messageTimes = {}

You're building a dictionary;  are you actually using the value (1), or
  is only the key relevant?

Only the keys.


A set is a dict without a value.

Yes, I could use a set, but I don't think that would make it measurably faster.


But more mportantly, you never look up anything in this dictionary.  So why
isn't it a list?  For that matter, why don't you just use the
messageTimes list?

Yes, it could be a list too.
  

for row in cdata:   # tool, time, message
 if self.message in row[2]:
 messageTimes[row[0], row[1]] = 1
# now pull out each message that is within the time diff for each matched 
message
# as well as the matched messages themselves
def determine(tup):
 if self.message in tup[2]: return True  # matched message
 for (tool, date_time) in messageTimes:
 if tool == tup[0]:
 if abs(date_time-tup[1]) = tdiff:
return True
 return False
 
cdata[:] = [tup for tup in cdata if determine(tup)]



As the code exists, there's no need to copy the list.  Just do a simple
bind.

This statement is to remove the items from cdata that I don't want. I don't 
know what you mean by bind. I'm not familiar with that python function.





This code works, but it takes way too long to run - e.g. when cdata has 600,000 
elements (which is typical for my app) it takes 2 hours for this to run.
Can anyone give me some suggestions on speeding this up?



This code probably is not faster but it's simpler and may be easier for 
you to work with

to experiment with speed-improving changes:


diffrng = 1

L = [
 # id, time, string
 (1, 5, ok),
 (1, 6, ok),
 (1, 7, no),
 (1, 8, no),
 ]

match_times = [t[1] for t in L if ok in t[2]]

def in_range(timeval):
return bool( min([abs(timeval-v) for v in match_times]) = diffrng )

print([t for t in L if in_range(t[1])])


But it really sounds like you could look into optimizing the db
query and db indexes, etc.


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


  1   2   >