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"  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


New tutorials

2012-12-02 Thread Mitya Sirenef
Hi everyone, I'm making a series of python tutorials and I've just 
finished the introductory part: http://lightbird.net/larks/intro.html


Feedback is appreciated.. - mitya

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


Re: loops

2012-12-02 Thread Mitya Sirenef

On 12/02/2012 04:39 PM, Verde Denim wrote:

I'm just getting into py coding, and have come across an oddity in a py
book - while loops that don't work as expected...

import random

MIN = 1
MAX = 6

def main():
 again = 'y'

 while again == 'y':
 print('Rolling...')
 print('Values are: ')
 print(random.randint(MIN, MAX))
 print(random.randint(MIN, MAX))

 again = input('Roll again? (y = yes): ')

main()

Produces -
python dice_roll.py
Rolling...
Values are:
5
4
Roll again? (y = yes): y
Traceback (most recent call last):
   File "dice_roll.py", line 17, in 
 main()
   File "dice_roll.py", line 15, in main
 again = input('Roll again? (y = yes): ')
   File "", line 1, in 
NameError: name 'y' is not defined

This same loop structure appears in many places in this book "Starting
out with Python, 2nd ed, Tony Gaddis), and they all yield the same
error. Is there something I'm missing here?

Thanks for the input...


I believe that should be raw_input, not input . input() evaluates user's 
input

in local scope.  -m
--
http://mail.python.org/mailman/listinfo/python-list


Re: New tutorials

2012-12-03 Thread Mitya Sirenef

While referencing the python  tutorial, you should state how your

> tutorial complement the already existing one, possibly which issues
> you're trying to fix, or how different your approach is.

> Cheers,

> JM


Thanks for the feedback, I've added the following line to the Intro
section:

My guide will mostly use short, simple games to teach Python and 
Programming in general.



This will also be easy to see just by looking at the listing in the
index once I start adding sections.. the first one coming up!

 - mitya

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


Re: New tutorials

2012-12-03 Thread Mitya Sirenef

On 12/02/2012 09:54 AM, Mitya Sirenef wrote:
Hi everyone, I'm making a series of python tutorials and I've just 
finished the introductory part: http://lightbird.net/larks/intro.html



I've just uploaded a new section -- a tictactoe game:

<http://lightbird.net/larks/tictactoe.html>


I've also updated the Intro to state that Python version 3.2+ is required.

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


Re: New tutorials

2012-12-04 Thread Mitya Sirenef

On 12/02/2012 09:54 AM, Mitya Sirenef wrote:
Hi everyone, I'm making a series of python tutorials and I've just 
finished the introductory part: http://lightbird.net/larks/intro.html


Feedback is appreciated.. - mitya
<http://lightbird.net/larks/intro.html>



I've just added a new section 'blocky blocks', which is a clone of 
'jumping blocks' game:


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

I've used some rare unicode symbols in the game, they look a little 
strange in Gvim
but seem to work fine in my terminal and browser. If you experience 
issues, please

let me know. I've only tested in Linux terminal.

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


Re: New tutorials

2012-12-06 Thread Mitya Sirenef

On 12/02/2012 09:54 AM, Mitya Sirenef wrote:

Hi everyone, I'm making a  series of python tutorials and I've just

> finished the introductory part: http://lightbird.net/larks/intro.html
>
> Feedback is appreciated.. - mitya
> <http://lightbird.net/larks/intro.html>


I've added two more tutorials, Sudoku and Battleship games:

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

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


As with Blocky Blocks, I'm not sure unicode chars in Battleship will
work well for everyone on all OSes, I've only tested it on Linux
X terminal.   -m

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


Re: New tutorials

2012-12-06 Thread Mitya Sirenef

On 12/06/2012 12:16 PM, Jean-Michel Pichavant wrote:

- Original Message -

>> On 12/02/2012 09:54 AM, Mitya Sirenef wrote:
>>> Hi everyone, I'm making a series of python tutorials and I've just
>> > finished the introductory part:
>> > http://lightbird.net/larks/intro.html
>> >
>> > Feedback is appreciated.. - mitya
>> > <http://lightbird.net/larks/intro.html>
>>
>>
>> I've added two more tutorials, Sudoku and Battleship games:
>>
>> http://lightbird.net/larks/sudoku.html
>>
>> http://lightbird.net/larks/battleship.html
>>
>>
>> As with Blocky Blocks, I'm not sure unicode chars in Battleship will
>> work well for everyone on all OSes, I've only tested it on Linux
>> X terminal. -m
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>
> You should summarize the new python concept introduced by each 
tutorial so people can jump directly to the section they need.



That's a good idea, I was thining of something along the same lines, I
wanted to add a few more games first but I guess there's enough of them
already to make this useful. I'll try to add an 'index' section
tomorrow.




>
> I have the feeling this is not really a python tutorial, it's a bunch
> of mini games that happen to be written in python. Am I right ? If I'm
> wrong, you should definitely organize your doc by python concepts,
> linking each concept to any related tutorial.


It is meant as a python tutorial, it's just not fleshed out yet. I want
to add a few games and take a step back and figure out what order to put
them in and how to spread out detailed explanation across all sections.

Thanks for the feedback!

 -m




> JM
>
>


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


Re: Issue with seeded map generation

2012-12-08 Thread Mitya Sirenef

On 12/08/2012 04:32 PM, Graham Fielding wrote:

Hey, all!

>
> I've managed to get my project to a semi-playable state (everything 
functions, if not precisely the way I'd like it to). One small issue is 
that when the player movs from one level to the next, the items and 
monsters in the previous level all 'reset' and return to the positions 
they had when the level was seeded.

>
> I've puzzled over (and attempted) quite a few workarounds, and had no 
success. I don't want to pickle the entire level (that would be overkill 
for what I need), but I want to update the item/monster locations so the 
player can drop an item and come back to it later.

>
> Should I add something to the 'drop_item' function, or call soemthing 
in make_map?

>
>

How many levels do you have and how much does each take up in memory? It
might be ok to to simply save the level in memory under its number; if
the map takes up a lot of space you can make objects take up less memory
by using __slots__, and then change levels by doing something like this:

def change_level(num):
  self.levels[self.current_lvl] = self.levelmap
  if num in self.levels:
self.levelmap = self.levels[num]
  else: [handle new level creation]
  self.current_lvl = num

 -m

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Mitya Sirenef

On 12/11/2012 05:39 PM, Dave Cinege wrote:

On Tuesday 11 December 2012  16:53:12 Ian Kelly wrote:

>
>> Just out of curiosity, how old are we talking? enumerate was added in
>> Python 2.3, which is nearly 10 years old. Prior to 2.2 I don't think
>> it was even possible to subclass dict, which would make your Thesaurus
>> implementation unusable, so are these systems running Python 2.2?
>
> I'm finally beyond 2.2 and getting rid of 2.4 soon. Just started 
using 2.6 5

> months ago.
>
> Thesaurus initially came about from me doing this:
> class Global:
> pass
> g = Global()
>
> As a way to organize/consolidate global vars and eliminate the global
> statement.


I think that's the key issue here. I find that when code is well
structured, you pretty much never have a need for global statements,
anyway.

By the way, the Thesaurus class reminds me of using the old recipe
called 'Bunch':

http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/

like this:

b = Bunch(x=1) b.stuff = Bunch(y=2)

b.stuff.y 2

I've also seen an answer on StackOverflow that uses automatic recursive
'Bunching':

http://stackoverflow.com/questions/1123000/does-python-have-anonymous-classes

I've seen another variation of recursive bunching, I think it was by
Alex Martelli on StackOverflow, but I can't find it now, I believe it
used defaultdict as part of it..

This approach can be handy sometimes but has drawbacks, as others have
pointed out.

I think the issue is that it's not a "solution for avoiding globals",
which is not a problem in need of solution, but this can be a quick and
dirty way to organize a few levels of dicts/Bunches and usually people
come up with a custom variation on these recipes that suit their
program.


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

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Mitya Sirenef

On 12/11/2012 07:53 PM, Mitya Sirenef wrote:

By the way, the Thesaurus class reminds me of using the old recipe
called 'Bunch':

http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/ 



like this:

b = Bunch(x=1) b.stuff = Bunch(y=2)

b.stuff.y 2 


Sorry, this was meant to be:

b = Bunch(x=1)
b.stuff = Bunch(y=2)

b.stuff.y
 2

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


Re: Hollow square program

2012-12-12 Thread Mitya Sirenef

On 12/12/2012 11:48 AM, siimnur...@gmail.com wrote:
Hey, I need to write a program  that prints out a square, which is empty on the inside. So far, I've 

made a program that outputs a square, which is full on the inside.
> P.S. Between every asterisk there needs to be a space(" ")
> Here's my code:
>
> print("Rows: ")
> rows = int(input())
> for i in range(rows):
> for j in range(rows):
> print("* ", end="")
> print("")


Small note: print("") is the same as print()

The general idea is: make a string that represents top/bottom of the
square, make a string for the middle part, print out the first string,
then print out middle part n-2 times, then print out first string again.

Did you know you can multiply strings? e.g.:

space  = ' '
border = '*'
line   = border + space*70

 -m

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

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


Re: unpacking first few items of iterable

2012-12-13 Thread Mitya Sirenef

On 12/13/2012 03:09 PM, Daniel Fetchinson wrote:

Hi folks, I swear I used to know this but can't find it anywhere:

What's the standard idiom for unpacking the first few items of an
iterable whose total length is unknown?

Something like

a, b, c, _ = myiterable

where _ could eat up a variable number of items, in case I'm only
interested in the first 3 items?

If you're using python3, you can simply do:

a, b, c, *rest = myiterable

Thanks, sounds great, how about python2?



If you know the sequence has at least n items, you
can do a, b, c = seq[:3]

 -m

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

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


Re: unpacking first few items of iterable

2012-12-13 Thread Mitya Sirenef

On 12/13/2012 03:39 PM, Daniel Fetchinson wrote:

Hi folks, I swear I used to know this but can't find it anywhere:

What's the standard idiom for unpacking the first few items of an
iterable whose total length is unknown?

Something like

a, b, c, _ = myiterable

where _ could eat up a variable number of items, in case I'm only
interested in the first 3 items?

If you're using python3, you can simply do:

a, b, c, *rest = myiterable

Thanks, sounds great, how about python2?


If you know the sequence has at least n items, you
can do a, b, c = seq[:3]

Yeah, that's probably the simplest, without all the fancy stuff :)

Cheers,
Daniel





Well, fancy stuff is good too, I'm a great fan of fancy stuff :)

 -m

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

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


Re: Trying to make a basic Python score counter in a game... will not count.

2012-12-16 Thread Mitya Sirenef

On 12/16/2012 12:00 PM, Darrien Glasser wrote:
Hey guys, I'm working on a  Python rock paper scissors (lizard spock) game, and the beginning is 
complete. After I finished it, I thought, "You know what? I think I can 
make this even better, and add a score counter." And so I did.

>
> The problem is that it doesn't seem to actually keep track of score. 
In fact it always keeps the score at 0 for both players. It's fully 
functional otherwise, but it's bothering me that I can't get it to work.

>
> Currently using Windows Python 32 bit v2.6.8
>
> Download of the code here:
>
> https://www.box.com/s/2lupxeyk5jvsxs0zkdfb
>
> Copy of the code here:
>
> http://pastebin.com/MNdgiuSY
>
> Thanks in advance for your help...


I was actually thinking of making a simple rock paper scissors game so I
went ahead and cobbled it together, using a design with a class and
generally a structured approach.. It keeps the scores, too, and you can
set both players to be AI, or one to be AI, or both to be humans:

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

(it needs python3 but can be easily changed to work with python2.x)


 - mitya

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

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


Re: Trying to make a basic Python score counter in a game... will not count.

2012-12-16 Thread Mitya Sirenef

On 12/16/2012 01:17 PM, tbg wrote:

On Sunday, December 16, 2012 1:07:16 PM UTC-5, Mitya Sirenef wrote:

On 12/16/2012 12:00 PM, Darrien Glasser wrote:


Hey guys, I'm working on a  Python rock paper scissors (lizard spock) game, and 
the beginning is

complete. After I finished it, I thought, "You know what? I think I can

make this even better, and add a score counter." And so I did.

  >

  > The problem is that it doesn't seem to actually keep track of score.

In fact it always keeps the score at 0 for both players. It's fully

functional otherwise, but it's bothering me that I can't get it to work.

  >

  > Currently using Windows Python 32 bit v2.6.8

  >

  > Download of the code here:

  >

  > https://www.box.com/s/2lupxeyk5jvsxs0zkdfb

  >

  > Copy of the code here:

  >

  > http://pastebin.com/MNdgiuSY

  >

  > Thanks in advance for your help...





I was actually thinking of making a simple rock paper scissors game so I

went ahead and cobbled it together, using a design with a class and

generally a structured approach.. It keeps the scores, too, and you can

set both players to be AI, or one to be AI, or both to be humans:



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



(it needs python3 but can be easily changed to work with python2.x)





   - mitya



--

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

Well there goes my hopes and dreams of being the first one to do that. Nice job 
by the way.


Well you were the first :-)  I just did it to illustrate a modular 
approach, I think a

simple game like that is a great learning opportunity.

I posted an update with some small cleanups just now..

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

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


Re: Trying to make a basic Python score counter in a game... will not count.

2012-12-16 Thread Mitya Sirenef

On 12/16/2012 01:07 PM, Mitya Sirenef wrote:

On 12/16/2012 12:00 PM, Darrien  Glasser wrote:
>> Hey guys, I'm working on a Python rock paper scissors (lizard spock) 
game, and the beginning is
> complete. After I finished it, I thought, "You know what? I think I 
can make this even better, and add a score counter." And so I did.

> >
> > The problem is that it doesn't seem to actually keep track of 
score. In fact it always keeps the score at 0 for both players. It's 
fully functional otherwise, but it's bothering me that I can't get it to 
work.

> >
> > Currently using Windows Python 32 bit v2.6.8
> >
> > Download of the code here:
> >
> > https://www.box.com/s/2lupxeyk5jvsxs0zkdfb
> >
> > Copy of the code here:
> >
> > http://pastebin.com/MNdgiuSY
> >
> > Thanks in advance for your help...
>
>
> I was actually thinking of making a simple rock paper scissors game so I
> went ahead and cobbled it together, using a design with a class and
> generally a structured approach.. It keeps the scores, too, and you can
> set both players to be AI, or one to be AI, or both to be humans:
>
> https://github.com/pythonbyexample/PBE/blob/master/code/rockpaper.py
>
> (it needs python3 but can be easily changed to work with python2.x)
>
>
> - mitya
>


If anyone's interested, I've simplified the code further by making use
of my TextInput utility class; I've also made the game into a tutorial,
it can be found here:

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


The updated full code is really tiny (it requires utils.py which is
linked at the top of tutorial):


import sys
from random import choice as randchoice
from time import sleep

from utils import TextInput

players= 'XY'
ai_players = 'Y'
moves  = "rps"
wins   = ("rp", "sr", "ps")   # choice on the right side wins
status = "%5s %3d %5s %3d moves: %s %s"
pause_time = 0.3


class RockPaperScissors(object):
def run(self):
self.textinput = TextInput("(r|p|s)")
scores = [0, 0]

while True:
choice1, choice2 = (self.get_move(p) for p in players)

if choice1 != choice2:
winplayer = 1 if (choice1+choice2 in wins) else 0
scores[winplayer] += 1

print(status % (players[0], scores[0], players[1], 
scores[1], choice1, choice2))

sleep(pause_time)

def get_move(self, player):
if player in ai_players : return randchoice(moves)
else: return self.textinput.getval()


if __name__ == "__main__":
try  : RockPaperScissors().run()
except KeyboardInterrupt : pass


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

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


Re: Delete dict and subdict items of some name

2012-12-17 Thread Mitya Sirenef

On 12/17/2012 12:27 PM, Gnarlodious wrote:

Hello. What I want to do is delete every dictionary key/value of the name 
'Favicon' regardless of depth in subdicts, of which there are many. What is the 
best way to do it?

-- Gnarlie


Something like this should work:

def delkey(d, key):
if isinstance(d, dict):
if key in d: del d[key]
for val in d.values():
delkey(val, key)


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

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


Re: Delete dict and subdict items of some name

2012-12-17 Thread Mitya Sirenef

On 12/17/2012 01:30 PM, Tim Chase wrote:

On 12/17/12 11:43, Mitya Sirenef wrote:

On 12/17/2012 12:27 PM, Gnarlodious wrote:

Hello. What I want to do is delete every dictionary key/value
of the name 'Favicon' regardless of depth in subdicts, of which
there are many. What is the best way to do it?

Something like this should work:

def delkey(d, key):
  if isinstance(d, dict):
  if key in d: del d[key]
  for val in d.values():
  delkey(val, key)

Unless you have something hatefully recursive like

   d = {}
   d["hello"] = d

:-)


True -- didn't think of that..!

I guess then adding a check 'if val is not d: delkey(val, key)'
would take care of it?

 -m


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

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


Re: Delete dict and subdict items of some name

2012-12-17 Thread Mitya Sirenef

On 12/17/2012 05:00 PM, Dave Angel wrote:

On 12/17/2012 04:33 PM, Mitya Sirenef wrote:

On 12/17/2012 01:30 PM, Tim Chase wrote:

On 12/17/12 11:43, Mitya Sirenef wrote:

On 12/17/2012 12:27 PM, Gnarlodious wrote:

Hello. What I want to do is delete every dictionary key/value
of the name 'Favicon' regardless of depth in subdicts, of which
there are many. What is the best way to do it?

Something like this should work:

def delkey(d, key):
   if isinstance(d, dict):
   if key in d: del d[key]
   for val in d.values():
   delkey(val, key)

Unless you have something hatefully recursive like

d = {}
d["hello"] = d

:-)

True -- didn't think of that..!

I guess then adding a check 'if val is not d: delkey(val, key)'
would take care of it?


No, that would only cover the self-recursive case.  If there's a dict
which contains another one, which contains the first, then the recursion
is indirect, and much harder to check for.

Checking reliably for arbitrary recursion patterns is tricky, but
do-able.  Most people degenerate into just setting an arbitrary max
depth.  But I can describe two approaches to this kind of problem.

1) build a list of the recursion path at present, and compare against
the whole path, rather than just the tail.  If there are any matches, quit.

2) make the iterator an object, and instantiate two of them.  Then each
recursive level, iterate the main one once, and the secondary one
twice.  If the two ever match, you have a loop.  Deciding what to do at
that point is tricky because you may have processed some nodes multiple
times already.  But at least it'll terminate, and it doesn't use linear
memory to do so.  I call this one the lollypop algorithm.




Thanks, this is quite interesting..


--
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


Re: help with making my code more efficient

2012-12-20 Thread Mitya Sirenef

On 12/20/2012 09:39 PM, Mitya Sirenef wrote:

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.




Actually, it might be slower.. this version of in_range should be better:

def in_range(timeval):
return any( abs(timeval-v) <= diffrng for v in match_times )



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

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


Re: Pass and return

2012-12-20 Thread Mitya Sirenef

On 12/21/2012 12:23 AM, iMath wrote:

Pass and return
Are these two functions the same ?

def test():
return
  
def test():

pass


I believe they are the same, but these statements have
different meanings in other circumstances, e.g.:

Class A(object): pass

def test():
  if x: return
  else: # do something

In first example, (in a class), return would be invalid.

In second example, return would return None from function,
pass would result in continuing execution after if/else block.

Btw you can use disassemble function to look into what
these functions do:

>>> def a(): pass
>>> def b():return
>>> from dis import dis
>>> dis(a)
  1   0 LOAD_CONST   0 (None)
  3 RETURN_VALUE
>>> dis(b)
  1   0 LOAD_CONST   0 (None)
  3 RETURN_VALUE


So indeed they should be the same..

 -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-20 Thread Mitya Sirenef

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.

 -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  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: 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 

 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: 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 



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: 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

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
 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  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: 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  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: 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: 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 <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 23 or 9 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: 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?

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  :w
   :inoremenu File.Save  :w
   :menu Edit.Big\ Changes.Delete\ All\ Spaces  :%s/[ ^I]//g




> 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  ,

> Mitya Sirenef  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.






--
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 d3. 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
\blah); 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 
qaq"aP

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: 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: 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: 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: 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: 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: 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: 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: 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 ,
  Jason Friedman  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: 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: 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 ,
  Mitya Sirenef  wrote:


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

In article ,
   Jason Friedman  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: ANN: Python training "text movies"

2013-01-20 Thread Mitya Sirenef

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

In article  ,

> Franck Ditter  wrote:
>
>> In article ,
>> Franck Ditter  wrote:
>>
>>> In article ,
>>> Mitya Sirenef  wrote:
>>>
>>>> On 01/19/2013 04:32 AM, Franck Ditter wrote:
>>>>> In article ,
>>>>> Mitya Sirenef  wrote:
>>>>>
>>>>>> On 01/14/2013 01:34 AM, Franck Ditter wrote:
>>>>>>> In article ,
>>>>>>> Jason Friedman  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 "", line 1, in 
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   wrote:

>> On 01/20/2013 06:14 PM, alex23 wrote:
>>
>>> On Jan 20, 7:23 pm, Chris Angelico  wrote:
 On Sun, Jan 20, 2013 at 8:17 PM, iMath  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: 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  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 yadda # 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  ,

> Mitya Sirenef  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  , 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: 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  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: 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 
έγραψε:

>> 
>
> 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 ( "" )
>
> for item in host, useros, browser, hits, lastvisit.strftime('%A %e 
%b, %H:%M').decode('cp1253').encode('utf8'):

> print ( " %s " % 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: 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: 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: 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: 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: 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: 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: 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 exis

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

>  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: 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


  1   2   >