Re: local variable 'a' referenced b

2012-10-03 Thread Demian Brecht
>
> One problem with short examples is they mask the reason for the code to
> be structured that way.
>
>
Couldn't agree more (I don't think I've ever written a nested function
outside a closure). I made the assumption that the OP wasn't asking about
closures based on his code samples. In hindsight, should have likely asked
for clarification first.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: design question:game skill system

2012-10-03 Thread Jean-Michel Pichavant


- Original Message -
> Hello all:
> I'm looking at a skill/perk system, where the player builds up his
> char
> by using perk points to add abilities.
> Each perk is under a category, and generally costs go up as you
> increase
> the perk.
> So I'm trying to figure something out; first, I'd really like the
> cost
> calculation and all of that to be dynamic, so that I don't have to
> write
> a calculateCost per object. I'd also like to be able to specify
> dependencies and say a level, as well as other factors before a
> player
> can obtain a perk and have them self documenting. The idea is that a
> player could do something like:
> data perk extended health
> and it would tell them they require health at 50 before they can
> purchase extended health, as well as the cost, the increase per level
> and the total overall cost.
> Any ideas on how to set this up would be really appreciated.
> Finally, I'm curious how to store and calculate these. I thought
> about
> using a uid per perk, then storing something like: {uid:level} on the
> player, but means that I have to lookup the name somehow still in the
> main perk database, then use that uid to check if the player has it.
> Are
> there better ways of storing skills? I'm also thinking about
> calculation; currently the CalculateMaxHp method would have to add up
> all the possible perks for health, then add stats and all that. That
> could get really rough on performance if it's called often; would
> something like a cache work, where you have something like:
> {attribute:dirty}? So if I call CalculateHealth, it checks for the
> dirty
> flag, and if it doesn't exist just returns the previous max HP, but
> if
> the dirty flag is set, it recalculates? Then anything modifying
> health
> (level gains, perks, stat increases/etc) would just set the dirty
> flag
> and call calculate?
> Thoughts/ideas would be welcome.
> Thanks,

Hi,

Again, do not think about performances before actually having an issue with 
them. What's the point to optimize something that doesn't need it ?

For your cache problem, google "python memoize decorator" for a bunch of 
decorators that will allow you to cache your data without any effort.

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


Re: unit testing class hierarchies

2012-10-03 Thread Oscar Benjamin
On 3 October 2012 02:20, Steven D'Aprano
 wrote:
>
> But surely, regardless of where that functionality is defined, you still
> need to test that both D1 and D2 exhibit the correct behaviour? Otherwise
> D2 (say) may break that functionality and your tests won't notice.
>
> Given a class hierarchy like this:
>
> class AbstractBaseClass:
> spam = "spam"
>
> class D1(AbstractBaseClass): pass
> class D2(D1): pass
>
>
> I write tests like this:
>
> class TestD1CommonBehaviour(unittest.TestCase):
> cls = D1
> def testSpam(self):
>  self.assertTrue(self.cls.spam == "spam")
> def testHam(self):
>  self.assertFalse(hasattr(self.cls, 'ham'))
>
> class TestD2CommonBehaviour(TestD1CommonBehaviour):
> cls = D2

That's an excellent idea. I wanted a convenient way to run the same
tests on two classes in order to test both a pure python and a
cython-accelerator module implementation of the same class. I find it
difficult to work out how to do such simple things with unittest
because of its Java-like insistence on organising all tests into
classes. I can't immediately remember what solution I came up with but
yours is definitely better.


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


Re: Experimental Python-based shell

2012-10-03 Thread Jorgen Grahn
On Tue, 2012-10-02, Jonathan Hayward wrote:
> I've made an experimental Python-based Unix/Linux shell at:
>
> http://JonathansCorner.com/cjsh/
>
> An experimental Unix/Linux command line shell, implemented in Python
> 3, that takes advantage of some more recent concepts in terms of
> usability and searching above pinpointing files in heirarchies.
>
> I invite you to try it.

Hard to do without a manual page, or any documentation at all except
for a tiny "hello world"-style example ...

/Jorgen

-- 
  // Jorgen GrahnO  o   .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Experimental Python-based shell

2012-10-03 Thread Amirouche Boubekki
Héllo,

2012/10/3 Jonathan Hayward 

> I've made an experimental Python-based Unix/Linux shell at:
>
> http://JonathansCorner.com/cjsh/
>
> An experimental Unix/Linux command line shell, implemented in Python 3,
> that takes advantage of some more recent concepts in terms of usability and
> searching above pinpointing files in heirarchies.
>

This sound like a great idea!  What are the other benefits of it except the
file lookup thing ? Does it do fuzzy match yet ?

Is there any repository on bitbucket or github ?

Thanks,

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


Combinations of lists

2012-10-03 Thread Steen Lysgaard

Hi,

I am looking for a clever way to compute all combinations of two lists. 
Look at this example:


h = ['A','A','B','B']
m = ['a','b']

the resulting combinations should be of the same length as h and each 
element in m can be used twice. The sought after result using h and m 
from above is:


[['aA', 'aA', 'bB', 'bB'],
 ['aA', 'aB', 'bA', 'bB'],
 ['aB', 'aB', 'bA', 'bA']]

(the order of the results does not matter i.e. ['aA', 'aA', 'bB', 'bB'] 
and ['aA', 'bB', 'aA', 'bB'] are considered the same)


This is achieved by the code below, this however needs to go through all 
possible combinations (faculty of len(h)) and rule out duplicates as 
they occur and this is too much if for example len(h) is 16.


Can anyone guide me to a better solution?

Thanks,
Steen

h = ['A','A','B','B']
m = ['a','b']

c = []
for i in h:
c.append([])
for j in m:
c[-1].append(j+i)
c[-1].append(j+i)

combs = []

for a in permutations(range(len(h)),len(h)):
comb = []
for i in range(len(h)):
comb.append(c[i][a[i]])
comb.sort()

if comb not in combs:
combs.append(comb)

print combs

print len(combs)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Combinations of lists

2012-10-03 Thread Alain Ketterlin
Steen Lysgaard  writes:

> I am looking for a clever way to compute all combinations of two
> lists. Look at this example:
>
> h = ['A','A','B','B']
> m = ['a','b']
>
> the resulting combinations should be of the same length as h and each
> element in m can be used twice. The sought after result using h and m
> from above is:
>
> [['aA', 'aA', 'bB', 'bB'],
>  ['aA', 'aB', 'bA', 'bB'],
>  ['aB', 'aB', 'bA', 'bA']]

I can't make sense of your explanation, which doesn't seem to match your
example (the result is not of the same size as h).

Here is a way to compute { xh | x in m }, where xh is a list where x is
prepended to each element of h.

result = [ [ x+l for l in h ] for x in m ]

If there is no duplicate in the original lists, then there will be no
duplicate in the result. Is that what you are looking for?

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


Re: Experimental Python-based shell

2012-10-03 Thread Jonathan Hayward
The chief benefit besides the searching, so far, is that you can use Py3k
mixed with shell commands as the scripting language--so script in Python
instead of bash.

When using Python for scripting, Python lines are indented by an extra tab
(or four spaces) while shell-like commands are not indented. So:

cjsh> for index in range(10):
> echo %(index)d
>
0
1
2
3
4
5
6
7
8
9

Echo could (and maybe should) be a built-in, but it isn't. The output is
os.system()'ed to bash, which echoes based on a command that includes the
value of a Python variable. The implementation is a bit crude, but it is
reasonably powerful.

I have other things on the agenda, like making it able to run scripts and
doing fuzzy matching, but for now those are the main two attractions.

On Wed, Oct 3, 2012 at 8:52 AM, Amirouche Boubekki <
amirouche.boube...@gmail.com> wrote:

> Héllo,
>
> 2012/10/3 Jonathan Hayward 
>
>> I've made an experimental Python-based Unix/Linux shell at:
>>
>> http://JonathansCorner.com/cjsh/
>>
>> An experimental Unix/Linux command line shell, implemented in Python 3,
>> that takes advantage of some more recent concepts in terms of usability and
>> searching above pinpointing files in heirarchies.
>>
>
> This sound like a great idea!  What are the other benefits of it except
> the file lookup thing ? Does it do fuzzy match yet ?
>
> Is there any repository on bitbucket or github ?
>
> Thanks,
>
> Amirouche
>



-- 
[image: Christos Jonathan Hayward] 
Christos Jonathan Hayward, an Orthodox Christian author.

*Amazon * • Author
Bio
 • *Email * •
Facebook
 • Google Plus  •
*Kindle
* • LinkedIn  •
*Professional
* • Twitter  •
*Web
* • What's New? 
I invite you to visit my "theology, literature, and other creative works"
site. *See one page of my website! *
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Combinations of lists

2012-10-03 Thread Steven D'Aprano
On Wed, 03 Oct 2012 16:26:43 +0200, Steen Lysgaard wrote:

> Hi,
> 
> I am looking for a clever way to compute all combinations of two lists.
> Look at this example:
> 
> h = ['A','A','B','B']
> m = ['a','b']
> 
> the resulting combinations should be of the same length as h and each
> element in m can be used twice. 

Why twice? What if you had these?

h = ['A', 'A', 'B', 'B', 'C', 'D', 'E', 'E']
m = ['a', 'b', 'c']

Would you still use each element in m twice? Or some other number?



> The sought after result using h and m from above is:
> 
> [['aA', 'aA', 'bB', 'bB'],
>   ['aA', 'aB', 'bA', 'bB'],
>   ['aB', 'aB', 'bA', 'bA']]
> 
> (the order of the results does not matter i.e. ['aA', 'aA', 'bB', 'bB']
> and ['aA', 'bB', 'aA', 'bB'] are considered the same)
> 
> This is achieved by the code below, this however needs to go through all
> possible combinations (faculty of len(h)) and rule out duplicates as
> they occur and this is too much if for example len(h) is 16.

I don't understand this requirement. In the example above, you don't rule 
out duplicates. Both 'aA' and 'bB' are duplicated. What duplicates are 
you ruling out?



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


Help me abstract this (and stop me from using eval)

2012-10-03 Thread Daniel Klein
Hi!

I've got import scripts for a bunch of csv files into an sqlite database. I 
have one csv file per language. I don't write directly to the sqlite db; this 
is a django app and I'm creating items in my django models. 

My script (scripts, unfortunately) work just fine, but it feels beyond stupid 
to have one script per language--importgerman, importfrench etc. The problem is 
that I don't know how to abstract which language I'm currently writing to. 
Here's the central loop:

http://pastebin.com/NBT6feNB

This is for the Polish version of the script, of course, the one that gets fed 
pl.csv. For those unfamiliar with django, I need to first retrieve the message 
instance for issue name / long text / short text / category name. Hence the 
ugly tempmes stuff. 

So ideally I would tell the script which language I'm currently importing and 
based on that it would write to the appropriate text fields. But I don't know 
how to abstract this:

tempmes.polish = row[1]

Well, I do. Like this:

eval("tempmes." + language + " = row[1]")

But... eval is evil, no? There's got to be a better way? 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Combinations of lists

2012-10-03 Thread Manuel Pégourié-Gonnard
Steven D'Aprano scripsit :

> On Wed, 03 Oct 2012 16:26:43 +0200, Steen Lysgaard wrote:
>
>> This is achieved by the code below, this however needs to go through all
>> possible combinations (faculty of len(h)) and rule out duplicates as
>> they occur and this is too much if for example len(h) is 16.
>
> I don't understand this requirement. In the example above, you don't rule 
> out duplicates. Both 'aA' and 'bB' are duplicated. What duplicates are 
> you ruling out?
>
I think the requirement is that r[i] != r[j] as soon as i != j, if r is
the resulting list of lists. (As opposed to having r[i][j] != r[i][k] for all i
and j != k.)

-- 
Manuel Pégourié-Gonnard - http://people.math.jussieu.fr/~mpg/


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


Re: Experimental Python-based shell

2012-10-03 Thread Amirouche Boubekki
2012/10/3 Jonathan Hayward 

> The chief benefit besides the searching, so far, is that you can use Py3k
> mixed with shell commands as the scripting language--so script in Python
> instead of bash.
>
> When using Python for scripting, Python lines are indented by an extra tab
> (or four spaces) while shell-like commands are not indented. So:
>
> cjsh> for index in range(10):
> > echo %(index)d
> >
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
>
> Echo could (and maybe should) be a built-in, but it isn't. The output is
> os.system()'ed to bash, which echoes based on a command that includes the
> value of a Python variable. The implementation is a bit crude, but it is
> reasonably powerful.
>
> I have other things on the agenda, like making it able to run scripts and
> doing fuzzy matching, but for now those are the main two attractions.
>

Is it possible to drop completly the bash syntax and use some python
library (I saw it on github) that wraps bash commands with python functions
or the other around making it possible to call python functions with a
bash-like syntax. The syntax you are talking about seems strange.

Regards,

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


Re: Help me abstract this (and stop me from using eval)

2012-10-03 Thread Kwpolska
On Wed, Oct 3, 2012 at 6:23 PM, Daniel Klein  wrote:
> tempmes.polish = row[1]
>
> Well, I do. Like this:
>
> eval("tempmes." + language + " = row[1]")
>
> But... eval is evil, no? There's got to be a better way?
> --
> http://mail.python.org/mailman/listinfo/python-list

Easy.

tempmes = myissue.name
language = 'polish'
setattr(tempmes, language, row[1])
tempmes.save()

-- 
Kwpolska 
stop html mail  | always bottom-post
www.asciiribbon.org | www.netmeister.org/news/learn2quote.html
GPG KEY: 5EAAEA16
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are ABCs an anti-pattern?

2012-10-03 Thread Demian Brecht
>
>
> ABCs were added (fairly recently) in 3.0 for the reasons given in
> http://python.org/dev/peps/**pep-3119/
> It was expected that it would take awhile for them to see good, pythonic
> uses. We obviously did okay without them up to 2.7.
>

I read the PEP before posting just to make sure that I wasn't missing
anything. The gut feeling that I got after reading PEP 3119 was that it was
written by an academic relatively recently out of school (or in school
even), or coming from a strictly typed language who saw this as a hole in
the language.

Don't get me wrong. In theory (and coming from a C/C++ background), I fully
appreciate the need for such language features. However, in practice, it
seems to somewhat be contrary to the Zen of Python.

One thing that irks me a bit about abc's is that those coming from other
(strictly typed) language backgrounds (or school for that matter) will
think "hey, my prof/books told me that I should use an abstract base class
to define the contract for [x]". Next step, Google abstract base classes
and Python, they're presented with abcs, rather than how to look and think
about the problem differently using Pythonic idioms. This kind of thing
(imho) is a catalyst for many over-engineered Python packages and
misunderstanding of the core language.

In short, it seems like somewhat of an academic crutch to me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help me abstract this (and stop me from using eval)

2012-10-03 Thread Steven D'Aprano
On Wed, 03 Oct 2012 09:23:03 -0700, Daniel Klein wrote:

> So ideally I would tell the script which language I'm currently
> importing and based on that it would write to the appropriate text
> fields. But I don't know how to abstract this:
> 
> tempmes.polish = row[1]
> 
> Well, I do. Like this:
> 
> eval("tempmes." + language + " = row[1]")

setattr(tempmes, language, row[1])



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


Re: Help me abstract this (and stop me from using eval)

2012-10-03 Thread Daniel Klein
Thank you Steven! That was PRECISELY what I was looking for.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help me abstract this (and stop me from using eval)

2012-10-03 Thread Daniel Klein
On Wednesday, October 3, 2012 5:40:12 PM UTC+1, Daniel Klein wrote:
> Thank you Steven! That was PRECISELY what I was looking for.

(And kwpolska!)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Experimental Python-based shell

2012-10-03 Thread Jonathan Hayward
I am open to suggestions and patches. I don't think the syntax strange,
though: it offers a clear and distinct way to differentiate Python and
shell commands, and shell commands can access Python variables when
specified. And it is a simple rule, without footnotes needed.

On Wed, Oct 3, 2012 at 11:25 AM, Amirouche Boubekki <
amirouche.boube...@gmail.com> wrote:

>
>
> 2012/10/3 Jonathan Hayward 
>
>> The chief benefit besides the searching, so far, is that you can use Py3k
>> mixed with shell commands as the scripting language--so script in Python
>> instead of bash.
>>
>> When using Python for scripting, Python lines are indented by an extra
>> tab (or four spaces) while shell-like commands are not indented. So:
>>
>> cjsh> for index in range(10):
>> > echo %(index)d
>> >
>> 0
>> 1
>> 2
>> 3
>> 4
>> 5
>> 6
>> 7
>> 8
>> 9
>>
>> Echo could (and maybe should) be a built-in, but it isn't. The output is
>> os.system()'ed to bash, which echoes based on a command that includes the
>> value of a Python variable. The implementation is a bit crude, but it is
>> reasonably powerful.
>>
>> I have other things on the agenda, like making it able to run scripts and
>> doing fuzzy matching, but for now those are the main two attractions.
>>
>
> Is it possible to drop completly the bash syntax and use some python
> library (I saw it on github) that wraps bash commands with python functions
> or the other around making it possible to call python functions with a
> bash-like syntax. The syntax you are talking about seems strange.
>
> Regards,
>
> Amirouche
>



-- 
[image: Christos Jonathan Hayward] 
Christos Jonathan Hayward, an Orthodox Christian author.

*Amazon * • Author
Bio
 • *Email * •
Facebook
 • Google Plus  •
*Kindle
* • LinkedIn  •
*Professional
* • Twitter  •
*Web
* • What's New? 
I invite you to visit my "theology, literature, and other creative works"
site. *See one page of my website! *
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can somebody give me an advice about what to learn?

2012-10-03 Thread Hans Mulder
On 1/10/12 00:14:29, Roy Smith wrote:
> In article ,
>  Chris Angelico  wrote:
> 
>> you can't, for instance, retain a "socket connection object" across 
>> that sort of reload.
> 
> Yeah, that's a problem.  There's nothing fundamental about a TCP 
> connection endpoint which precludes it being serialized and passed 
> around.  The amount of state involved is pretty small.  Unless I've 
> forgotten something, 2 IP addresses, 2 port numbers, a few bits worth of 
> TCP protocol state, and, for open connections, 2 sequence numbers.  
> Maybe a couple of timers, but I don't think they're strictly necessary.  
> The problem is, most of that state is private to the kernel.

You're looking at the wrong abstraction level.  A socket connection
object is a thin wrapper around a file descriptor.  Most posix platforms
allow you to pass file descriptors to other processes running on the
same box.  Thus, most posix platforms *do* allow you to pass socket
connection objects around, though you won't win prizes for portability.

> On the other hand, you could do what "screen" does, and spawn a process 
> per connection to hold the connection open :-)

That won't work for the sort of application we're discussing, because
it creates too many processes.  A pool of processes, each handling
many connections, might work though.

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


Need Data Architect/Technical Business Analyst For 6months at San Rafael, CA

2012-10-03 Thread ram dev
Good Day,

urgent Requirement : San Rafael, CA 6 months 

As a member of the Market Intelligence team, the Data Architect/Technical 
Business Analyst will be tasked
with assessing current state business process and corresponding data flows, 
understanding Marketing business
objectives, and identifying gaps in process, systems, and data that prevent 
execution against those objectives. This
will require understanding the broader internal data integration landscape to 
adequately determine synergies/
overlap and call out integration areas pertinent to Marketing that are 
insufficiently addressed by current systems
and in-flight projects.

Principal Duties and Responsibilities:
• Develop clear understanding of company’s integrated Marketing objectives/KPIs
• Leverage IT and Marketing resources to understand related process/data flows
• Develop and execute ETL procedures to integrate required sources (where 
currently feasible)
• Perform data/system/project gap analysis, documenting issues within the 
context of Marketing objectives
• Work closely with/inform business owners and project teams to ensure that 
documented gaps are addressed

Requirements:
• 5+ years SQL experience (SQL Server, Oracle) experience
• 5+ years ETL (SSIS, DTS, Informatica) experience
• High proficiency in data/systems analysis and integration
• Understanding of data models, data quality
• Proven ability to work within a highly-matrixed, global organization
• Excellent documentation and organizational skills
• Excellent communication skills, both written and verbal, and interpersonal 
skills

Desired Knowledge/Skills:
• Siebel CRM data model experience strongly preferred
• Business systems analysis./process engineering experience strongly preferred
• SFDC data model experience a plus
• Understanding of Clients Customer, Product, Contract, and Entitlement 
data/structures a plus





Thanks,

Ram Dev
Recruiter
Tech-Net Inc.
Tel: 916-458-4390 Ext 102
Email: r...@tech-netinc.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Emulating C++ namespaces with ChainMap and metaclass trickery

2012-10-03 Thread Steven D'Aprano
C++ namespaces are useful for encapsulating related objects within a 
single file, subdividing the global namespace without using classes. 
Python has modules, but they come in separate files.

Using Python 3.3's ChainMap type, and some metaclass trickery, I abuse 
the class keyword to (almost) emulate C++ namespaces:

http://code.activestate.com/recipes/578279/




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


Re: Can somebody give me an advice about what to learn?

2012-10-03 Thread Wolfgang Keller
> I'm really new to Usenet/Newsgroups, but... I'd like to learn some
> new programming language, because I learnt a bit of Perl though its
> OOP is ugly. So, after searching a bit, I found Python and Ruby, and
> both of they are cute. So, assuming you'll say me "learn python", why
> should I learn it over Ruby?

The point why Ruby was started (perceived deficit of object-orientation)
has been remedied since Python 2.2.

However, Ruby has reproduced quite a few of those well-known problems of
other languages that Python deliberately avoids (such as e.g. deficit of
orthogonality) and that make reading and understanding code difficult,
besides introducing sources for potential bugs.

Sincerely,

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


Re: Combinations of lists

2012-10-03 Thread Joshua Landau
On 3 October 2012 15:26, Steen Lysgaard  wrote:

> Hi,
>
> I am looking for a clever way to compute all combinations of two lists.
> Look at this example:
>
> h = ['A','A','B','B']
> m = ['a','b']
>
> the resulting combinations should be of the same length as h and each
> element in m can be used twice. The sought after result using h and m from
> above is:
>
> [['aA', 'aA', 'bB', 'bB'],
>  ['aA', 'aB', 'bA', 'bB'],
>  ['aB', 'aB', 'bA', 'bA']]
>
> (the order of the results does not matter i.e. ['aA', 'aA', 'bB', 'bB']
> and ['aA', 'bB', 'aA', 'bB'] are considered the same)
>
> This is achieved by the code below, this however needs to go through all
> possible combinations (faculty of len(h)) and rule out duplicates as they
> occur and this is too much if for example len(h) is 16.
>
> Can anyone guide me to a better solution?


What lengths can the two lists be?

Is len(h) === 2*len(m), or it it just this time?

Depending on your answer this could be easy or hard ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Combinations of lists

2012-10-03 Thread Oscar Benjamin
On 3 October 2012 15:26, Steen Lysgaard  wrote:
> Hi,
>
> I am looking for a clever way to compute all combinations of two lists. Look
> at this example:
>
> h = ['A','A','B','B']
> m = ['a','b']
>
> the resulting combinations should be of the same length as h and each
> element in m can be used twice. The sought after result using h and m from
> above is:
>
> [['aA', 'aA', 'bB', 'bB'],
>  ['aA', 'aB', 'bA', 'bB'],
>  ['aB', 'aB', 'bA', 'bA']]
>
> (the order of the results does not matter i.e. ['aA', 'aA', 'bB', 'bB'] and
> ['aA', 'bB', 'aA', 'bB'] are considered the same)
>
> This is achieved by the code below, this however needs to go through all
> possible combinations (faculty of len(h)) and rule out duplicates as they
> occur and this is too much if for example len(h) is 16.

I'm assuming that len(m) is always 2. Then if len(m) is 16 each
element of h can be used 8 times. If this is not as you intended you
will need to clarify how this problem generalises to other cases.

The elements that go with the 'b's are implicitly determined once you
have chosen the elements that go with the 'a's. The problem then is
solved if you choose the elements that go with the 'a's. If we need to
choose say k elements to go with the 'a's the basic problem becomes:
"enumerate over all multisets of size k that are subsets of the
multiset h."

'''
def submultisets(multiset, subsetsize, stack=None):
# Enter recursion
if stack is None:
multiset = dict((c, multiset.count(c)) for c in set(multiset))
stack = []

c = next(iter(multiset))

# End recursion
if len(multiset) == 1:
missing = subsetsize - len(stack)
if multiset[c] >= missing:
yield stack + missing  * [c]
return

# Continue recursion
count = multiset.pop(c)
for n in range(count + 1):
stack.extend(n * c)
for result in submultisets(multiset, subsetsize, stack):
yield result
del stack[-n:]
multiset[c] = count

def uniquecombinations(h, m):
for ha in submultisets(h, len(h)//2):
hb = list(h)
for c in ha:
hb.remove(c)
yield [m[0] + a for a in ha] + [m[1] + b for b in hb]

h = ['A', 'A', 'B', 'B']
m = ['a', 'b']

for x in uniquecombinations(h, m):
print(x)
'''

Output:
['aB', 'aB', 'bA', 'bA']
['aA', 'aB', 'bA', 'bB']
['aA', 'aA', 'bB', 'bB']


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


Re: Combinations of lists

2012-10-03 Thread Joshua Landau
On 3 October 2012 20:20, Oscar Benjamin  wrote:

> On 3 October 2012 15:26, Steen Lysgaard  wrote:
> > Hi,
> >
> > I am looking for a clever way to compute all combinations of two lists.
> Look
> > at this example:
> >
> > h = ['A','A','B','B']
> > m = ['a','b']
> >
> > the resulting combinations should be of the same length as h and each
> > element in m can be used twice. The sought after result using h and m
> from
> > above is:
> >
> > [['aA', 'aA', 'bB', 'bB'],
> >  ['aA', 'aB', 'bA', 'bB'],
> >  ['aB', 'aB', 'bA', 'bA']]
> >
> > (the order of the results does not matter i.e. ['aA', 'aA', 'bB', 'bB']
> and
> > ['aA', 'bB', 'aA', 'bB'] are considered the same)
> >
> > This is achieved by the code below, this however needs to go through all
> > possible combinations (faculty of len(h)) and rule out duplicates as they
> > occur and this is too much if for example len(h) is 16.
>
> I'm assuming that len(m) is always 2. Then if len(m) is 16 each
> element of h can be used 8 times. If this is not as you intended you
> will need to clarify how this problem generalises to other cases.
>

His code only works when len(m) is half of len(h), so this may not be the
right assumption.


> The elements that go with the 'b's are implicitly determined once you
> have chosen the elements that go with the 'a's. The problem then is
> solved if you choose the elements that go with the 'a's. If we need to
> choose say k elements to go with the 'a's the basic problem becomes:
> "enumerate over all multisets of size k that are subsets of the
> multiset h."
>
> '''
> def submultisets(multiset, subsetsize, stack=None):
> # Enter recursion
> if stack is None:
> multiset = dict((c, multiset.count(c)) for c in set(multiset))
> stack = []
>
> c = next(iter(multiset))
>
> # End recursion
> if len(multiset) == 1:
> missing = subsetsize - len(stack)
> if multiset[c] >= missing:
> yield stack + missing  * [c]
> return
>
> # Continue recursion
> count = multiset.pop(c)
> for n in range(count + 1):
> stack.extend(n * c)
> for result in submultisets(multiset, subsetsize, stack):
> yield result
> del stack[-n:]
> multiset[c] = count
>
> def uniquecombinations(h, m):
> for ha in submultisets(h, len(h)//2):
> hb = list(h)
> for c in ha:
> hb.remove(c)
> yield [m[0] + a for a in ha] + [m[1] + b for b in hb]
>
> h = ['A', 'A', 'B', 'B']
> m = ['a', 'b']
>
> for x in uniquecombinations(h, m):
> print(x)
> '''
>
> Output:
> ['aB', 'aB', 'bA', 'bA']
> ['aA', 'aB', 'bA', 'bB']
> ['aA', 'aA', 'bB', 'bB']
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Combinations of lists

2012-10-03 Thread Steen Lysgaard
Hi,

thanks for your interest. Sorry for not being completely clear, yes
the length of m will always be half of the length of h.

/Steen

2012/10/3 Joshua Landau :
> On 3 October 2012 20:20, Oscar Benjamin  wrote:
>>
>> On 3 October 2012 15:26, Steen Lysgaard  wrote:
>> > Hi,
>> >
>> > I am looking for a clever way to compute all combinations of two lists.
>> > Look
>> > at this example:
>> >
>> > h = ['A','A','B','B']
>> > m = ['a','b']
>> >
>> > the resulting combinations should be of the same length as h and each
>> > element in m can be used twice. The sought after result using h and m
>> > from
>> > above is:
>> >
>> > [['aA', 'aA', 'bB', 'bB'],
>> >  ['aA', 'aB', 'bA', 'bB'],
>> >  ['aB', 'aB', 'bA', 'bA']]
>> >
>> > (the order of the results does not matter i.e. ['aA', 'aA', 'bB', 'bB']
>> > and
>> > ['aA', 'bB', 'aA', 'bB'] are considered the same)
>> >
>> > This is achieved by the code below, this however needs to go through all
>> > possible combinations (faculty of len(h)) and rule out duplicates as
>> > they
>> > occur and this is too much if for example len(h) is 16.
>>
>> I'm assuming that len(m) is always 2. Then if len(m) is 16 each
>> element of h can be used 8 times. If this is not as you intended you
>> will need to clarify how this problem generalises to other cases.
>
>
> His code only works when len(m) is half of len(h), so this may not be the
> right assumption.
>
>>
>> The elements that go with the 'b's are implicitly determined once you
>> have chosen the elements that go with the 'a's. The problem then is
>> solved if you choose the elements that go with the 'a's. If we need to
>> choose say k elements to go with the 'a's the basic problem becomes:
>> "enumerate over all multisets of size k that are subsets of the
>> multiset h."
>>
>> '''
>> def submultisets(multiset, subsetsize, stack=None):
>> # Enter recursion
>> if stack is None:
>> multiset = dict((c, multiset.count(c)) for c in set(multiset))
>> stack = []
>>
>> c = next(iter(multiset))
>>
>> # End recursion
>> if len(multiset) == 1:
>> missing = subsetsize - len(stack)
>> if multiset[c] >= missing:
>> yield stack + missing  * [c]
>> return
>>
>> # Continue recursion
>> count = multiset.pop(c)
>> for n in range(count + 1):
>> stack.extend(n * c)
>> for result in submultisets(multiset, subsetsize, stack):
>> yield result
>> del stack[-n:]
>> multiset[c] = count
>>
>> def uniquecombinations(h, m):
>> for ha in submultisets(h, len(h)//2):
>> hb = list(h)
>> for c in ha:
>> hb.remove(c)
>> yield [m[0] + a for a in ha] + [m[1] + b for b in hb]
>>
>> h = ['A', 'A', 'B', 'B']
>> m = ['a', 'b']
>>
>> for x in uniquecombinations(h, m):
>> print(x)
>> '''
>>
>> Output:
>> ['aB', 'aB', 'bA', 'bA']
>> ['aA', 'aB', 'bA', 'bB']
>> ['aA', 'aA', 'bB', 'bB']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Combinations of lists

2012-10-03 Thread Oscar Benjamin
Oscar wrote:
>>> def uniquecombinations(h, m):
>>> for ha in submultisets(h, len(h)//2):
>>> hb = list(h)
>>> for c in ha:
>>> hb.remove(c)
>>> yield [m[0] + a for a in ha] + [m[1] + b for b in hb]
>>>
>>> h = ['A', 'A', 'B', 'B']
>>> m = ['a', 'b']
>>>
>>> for x in uniquecombinations(h, m):
>>> print(x)
>>> '''
>>>
>>> Output:
>>> ['aB', 'aB', 'bA', 'bA']
>>> ['aA', 'aB', 'bA', 'bB']
>>> ['aA', 'aA', 'bB', 'bB']

On 3 October 2012 21:15, Steen Lysgaard  wrote:
> Hi,
>
> thanks for your interest. Sorry for not being completely clear, yes
> the length of m will always be half of the length of h.
>
> /Steen

Then you can make the uniquecombinations function recursive. First
find the elements that go with 'a' then from the remaining elements
find those that go with 'b', then 'c' and so on.

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


Re: Combinations of lists

2012-10-03 Thread 88888 Dihedral
Oscar Benjamin於 2012年10月4日星期四UTC+8上午4時29分51秒寫道:
> Oscar wrote:
> 
> >>> def uniquecombinations(h, m):
> 
> >>> for ha in submultisets(h, len(h)//2):
> 
> >>> hb = list(h)
> 
> >>> for c in ha:
> 
> >>> hb.remove(c)
> 
> >>> yield [m[0] + a for a in ha] + [m[1] + b for b in hb]
> 
> >>>
> 
> >>> h = ['A', 'A', 'B', 'B']
> 
> >>> m = ['a', 'b']
> 
> >>>
> 
> >>> for x in uniquecombinations(h, m):
> 
> >>> print(x)
> 
> >>> '''
> 
> >>>
> 
> >>> Output:
> 
> >>> ['aB', 'aB', 'bA', 'bA']
> 
> >>> ['aA', 'aB', 'bA', 'bB']
> 
> >>> ['aA', 'aA', 'bB', 'bB']
> 
> 
> 
> On 3 October 2012 21:15, Steen Lysgaard  wrote:
> 
> > Hi,
> 
> >
> 
> > thanks for your interest. Sorry for not being completely clear, yes
> 
> > the length of m will always be half of the length of h.
> 
> >
> 
> > /Steen
> 
> 
> 
> Then you can make the uniquecombinations function recursive. First
> 
> find the elements that go with 'a' then from the remaining elements
> 
> find those that go with 'b', then 'c' and so on.
> 
> 
> 
> Oscar

Lets simplify the problem as follows:

A set of m symbols [0, 1,2,3...m-1] and each symbol can occur
a pecified number of times [(0, k(0)), (1, k(1)), (m-1, k(m-1)].rom a list 
to form a list of (i, k(i)) where  k(i) are  all positive integers.

For example [ (0,3), (1,2), (2, 1), (3, 2)], this is easy to generate 
valid numbers in base m numbers of sum(k(i)) digits.



in the final string.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Emulating C++ namespaces with ChainMap and metaclass trickery

2012-10-03 Thread Mark Adam
On Wed, Oct 3, 2012 at 1:26 PM, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> C++ namespaces are useful for encapsulating related objects within a
> single file, subdividing the global namespace without using classes.
> Python has modules, but they come in separate files.
>
> Using Python 3.3's ChainMap type, and some metaclass trickery, I abuse
> the class keyword to (almost) emulate C++ namespaces:
>

Very interesting.  I like the idea of continuing the namespace meme.

My idea of using the builtins (in the prior list thread of "namespaces and
modules"), is that if we overhaul the builtins, a unified data model could
emerge to incorporate whatever ideas one may have for namespaces (i.e.
"enclosures with a name").

My idea was to introduce the compound data type (using a ":" colon to
separate two sides), whereby one associates a (*hashable*) "name"  with an
object ("meals":{"breakfast","lunch","dinner"}) .  This has the extra
advantage of killing two warts in Python with one stone:  {} now is the
empty set literal like people are taught, and a set of compounds makes a
dictionary (dict now has set operations available), something which, in
theory, should simply CPython implementation AND the python environment/API.

"expose name" put the dictionary (or whatever type is decided for the rhs)
into the builtin/global namespace.

I have further thoughts, but that's all I have at the moment

markj
gothenburg, nebraska
-- 
http://mail.python.org/mailman/listinfo/python-list


Why is pylaucher in Python 3.3 being installed in Windows folder?

2012-10-03 Thread Piotr Dobrogost
Why is pylauncher in Python 3.3 being installed in Windows folder and
not in Program Files folder? Installing into Windows folder was maybe
acceptable 10 years ago but not now...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: design question:game skill system

2012-10-03 Thread Littlefield, Tyler
I just wanted to say thanks to all the people that provided input, both 
aonand off list. It gave me a good direction to head in. Thanks again.

On 10/2/2012 2:34 PM, Ian Kelly wrote:

On Tue, Oct 2, 2012 at 2:00 PM, Littlefield, Tyler  wrote:

Hello all:
I'm looking at a skill/perk system, where the player builds up his char by
using perk points to add abilities.
Each perk is under a category, and generally costs go up as you increase the
perk.
So I'm trying to figure something out; first, I'd really like the cost
calculation and all of that to be dynamic, so that I don't have to write a
calculateCost per object. I'd also like to be able to specify dependencies
and say a level, as well as other factors before a player can obtain a perk
and have them self documenting. The idea is that a player could do something
like:
data perk extended health
and it would tell them they require health at 50 before they can purchase
extended health, as well as the cost, the increase per level and the total
overall cost.

What are the cost calculations based on?  If there are specific
formulas then you would need to store them somehow, possibly just as a
function to be called or string to be evaled, but if the security of
the perk database is of concern then you could engineer a more
sandboxed representation.  For dependencies, you can keep them in a
container.  An extended health perk might look something like:

cost_formula = "5 * level ** 2"
dependencies = {HEALTH: 50, PLAYER_LEVEL: 15}
benefits = {HEALTH: "7 * level"}

where HEALTH and PLAYER_LEVEL are just some arbitrary known constants.
  Your core perks library would then be responsible for looking this
information up, running the formulas, and performing whatever
calculations on it are needed.


Finally, I'm curious how to store and calculate these. I thought about using
a uid per perk, then storing something like: {uid:level} on the player, but
means that I have to lookup the name somehow still in the main perk
database, then use that uid to check if the player has it. Are there better
ways of storing skills?

When you say uids, you mean UUIDs, right?  I'm not sure what advantage
there is in using abstracted unique identifiers for these.  Assuming
you have full control over what perks are added, you can ensure there
will be no name clashes, so why not just use the name or a name-based
tag to uniquely identify each perk?  Regardless of how you identify
them, though, your code is at some point going to have to go to the
database to look them up, so I would suggest you just go ahead and
write that code, and then you can add some caching later if it turns
out to be needed.


I'm also thinking about calculation; currently the
CalculateMaxHp method would have to add up all the possible perks for
health, then add stats and all that. That could get really rough on
performance if it's called often; would something like a cache work, where
you have something like: {attribute:dirty}? So if I call CalculateHealth, it
checks for the dirty flag, and if it doesn't exist just returns the previous
max HP, but if the dirty flag is set, it recalculates? Then anything
modifying health (level gains, perks, stat increases/etc) would just set the
dirty flag and call calculate?

Sounds reasonable.  I wouldn't use a separate flag attribute, though.
When max HP becomes dirty, clear the cached value, and use the absence
of a cached value to inform your code that it needs to recalculate.



--
Take care,
Ty
http://tds-solutions.net
The aspen project: a barebones light-weight mud engine:
http://code.google.com/p/aspenmud
He that will not reason is a bigot; he that cannot reason is a fool; he that 
dares not reason is a slave.

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


fastest data structure for retrieving objects identified by (x,y) tuple?

2012-10-03 Thread Benjamin Jessup
I have a group of objects identified by unique (x,y) pairs and I want to 
find out an object's "neighbors" in a matrix of size 2400 x 2400.

   #
   #obj#   #   #
   #
   #   #   #obj#  3 x 3 Example
   #
   #   #   #   #
   #
There is either a neighbor, or a null value. I always know the (x,y) 
pair to check the neighbors of, so is doing,

>> obj = grid[x][y] #lists, doesn't scale with num of objects
or,
>> obj = grid.get((x,y),None) #dictionary, scales with num of objects
the fastest? I can't seem to find a conclusion by testing each alone, 
then in the full environment. Is it that, depending on the number of 
objects, each has an advantage?


I know the fastest way to retrieve them would be to have them store 
pointers to their neighbors, then use those for retrieval. When large 
numbers of objects are changing their (x,y) pairs, rebuilding the 
pointers is too slow.

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


Re: Combinations of lists

2012-10-03 Thread Joshua Landau
On 3 October 2012 21:15, Steen Lysgaard  wrote:

> Hi,
>
> thanks for your interest. Sorry for not being completely clear, yes
> the length of m will always be half of the length of h.
>

(Please don't top post )

I have a solution to this, then.
It's not short *or* fast, but it's a lot faster than yours.

But first let me explain the most obvious optimization to your version of
the code:

combs = set()
>
> for a in permutations(range(len(h)),len(h)):
> comb = []
> for i in range(len(h)):
> comb.append(c[i][a[i]])
> comb.sort()
>
> frzn = tuple(comb)
> if frzn not in combs:
> combs.add(frzn)


 What I have done here is make your "combs" a set. This helps because you
are searching inside it and that is an O(N) operation... for lists.
A set can do the same in O(1). Simplez.

first  = list("AABBCCDDEE")
second = list("abcde")
import itertools
#
# Generator, so ignoring case convention
class force_unique_combinations:
 def __init__(self, lst, n):
self.cache = set()
self.internal_iter = itertools.combinations(lst, n)
 def __iter__(self):
return self
def __next__(self):
 while True:
nxt = next(self.internal_iter)
if not nxt in self.cache:
 self.cache.add(nxt)
return nxt
def combine(first, second):
sletter = second[0]
 first_combinations = force_unique_combinations(first, 2)
if len(second) == 1:
for combination in first_combinations:
 yield [sletter+combination[0], sletter+combination[1]]
else:
for combination in first_combinations:
 first_ = first[:]
first_.remove(combination[0])
first_.remove(combination[1])
 prefix = [sletter+combination[0], sletter+combination[1]]
for inner in combine(first_, second[1:]):
 yield prefix + inner


This is quite naive, because I don't know how to properly implement
force_unique_combinations, but it runs. I hope this is right. If you need
significantly more speed your best chance is probably Cython or C, although
I don't doubt 10x more speed may well be possible from within Python.


*Also, 8 Dihedral is a bot, or at least pretending like crazy to be one.
*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fastest data structure for retrieving objects identified by (x, y) tuple?

2012-10-03 Thread Joshua Landau
On 3 October 2012 23:30, Benjamin Jessup  wrote:

> I have a group of objects identified by unique (x,y) pairs and I want to
> find out an object's "neighbors" in a matrix of size 2400 x 2400.
>#
>#obj#   #   #
>#
>#   #   #obj#  3 x 3 Example
>#
>#   #   #   #
>#
> There is either a neighbor, or a null value. I always know the (x,y) pair
> to check the neighbors of, so is doing,
> >> obj = grid[x][y] #lists, doesn't scale with num of objects
> or,
> >> obj = grid.get((x,y),None) #dictionary, scales with num of objects
> the fastest? I can't seem to find a conclusion by testing each alone, then
> in the full environment. Is it that, depending on the number of objects,
> each has an advantage?
>
> I know the fastest way to retrieve them would be to have them store
> pointers to their neighbors, then use those for retrieval. When large
> numbers of objects are changing their (x,y) pairs, rebuilding the pointers
> is too slow


You really are asking the wrong question.

If most of the data is None, then a sparse matrix is best. Otherwise, lists
make the most sense.
*However, *what you really want is... a matrix. Look for a sparse matrix
type (
http://stackoverflow.com/questions/1053928/python-numpy-very-large-matrices)
if you need sparse, and otherwise Numpy's matrix should do fine.

The thing is this:
"I can't seem to find a conclusion by testing each alone, then in the full
environment. Is it that, depending on the number of objects, each has an
advantage?"

If you can't tell, don't bother. Dictionaries will have a memory advantage
with sparse matrices, lists in the other cases. That's the important part,
as look-up is fast for both*. If you need faster than these builtins, use
Numpy or SciPy.

If you really need optimization help, profile and ask the *right* question
to this list.

* To actually answer the question:
They both have O(1) look-up time, although dictionaries have a theoretical *
worst* case of O(N). Being simpler, it's faster to index a list. However,
you're doing that twice, so it's probably around even.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fastest data structure for retrieving objects identified by (x,y) tuple?

2012-10-03 Thread Steven D'Aprano
On Wed, 03 Oct 2012 18:30:24 -0400, Benjamin Jessup wrote:

> I have a group of objects identified by unique (x,y) pairs and I want to
> find out an object's "neighbors" in a matrix of size 2400 x 2400.
[...]
> There is either a neighbor, or a null value. I always know the (x,y)
> pair to check the neighbors of, so is doing,
>  >> obj = grid[x][y] #lists, doesn't scale with num of objects
> or,
>  >> obj = grid.get((x,y),None) #dictionary, scales with num of objects
> the fastest? I can't seem to find a conclusion by testing each alone,
> then in the full environment. Is it that, depending on the number of
> objects, each has an advantage?

Almost certainly not. Since you don't show how you test each, I have no 
idea why you can't find a conclusion.

Let's start off with the question you don't ask: which uses less memory? 
The answer is, the dict solution by far. Here is a test:

# populate a random matrix using both dict and list
adict = {}
alist = [[None]*2400 for i in range(2400)]
from random import randrange
for i in range(1000):
x = randrange(2400)
y = randrange(2400)
adict[(x, y)] = "something"
alist[x][y] = "something"

import sys
print(sys.getsizeof(adict))
print(sys.getsizeof(alist) + sum(sys.getsizeof(L) for L in alist))


The actual sizes printed will depend on how sparse the matrices are, but 
for the same above (approximately half full), using Python 2.7, the 
figures I get are:

adict: 24712
alist: 23127324


Now let's test the speed:

# randomly select matrix coordinates to look-up
test_coords = []
for i in range(1000):
x = randrange(2400)
y = randrange(2400)
test_coords.append((x, y))

# build some test code
from timeit import Timer
setup = "from __main__ import adict, alist, test_coords"
t1 = Timer("for p in test_coords: obj = adict.get(p)", setup)
t2 = Timer("for p in test_coords: obj = alist[p[0]][p[1]]", setup)

# run the test code
print(min(t1.repeat(number=1, repeat=7)))
print(min(t2.repeat(number=1, repeat=7)))


Again, on my system using Python 2.7, I get:
3.13823986053
2.97539305687

which shows that the two are very close, but the list solution is about 
6% faster. So in this situation, a list of lists uses about 100 times 
more memory than a dict, but look-ups are about 6% faster.

I would be very surprised if the timing results depended on the number of 
objects in the matrices.

In case you are not familiar with timeit, let me explain what I have done:

* I pre-select 1000 random coordinates.
* I write some test code inside a Timer object that look up each of 
  those coordinates, plus some setup code.
* timeit runs the setup code once.
* Then it runs my test code 1 times as a single trial, timing
  it as accurately as possible.
* It does seven trials, and I report the best of the seven.

The time printed is measured in seconds. In this case, I get 3 seconds 
per trial, or 3e-7 seconds = 0.3 microseconds per lookup.


> I know the fastest way to retrieve them would be to have them store
> pointers to their neighbors, then use those for retrieval.

How do you know that?

No offence, but if you can't even work out whether lookups in a dict or a 
list are faster, I can't imagine why you think you can intuit what the 
fastest way to retrieve the nearest neighbours would be.



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


Re: Why is pylaucher in Python 3.3 being installed in Windows folder?

2012-10-03 Thread Steven D'Aprano
On Wed, 03 Oct 2012 14:13:10 -0700, Piotr Dobrogost wrote:

> Why is pylauncher in Python 3.3 being installed in Windows folder and
> not in Program Files folder? Installing into Windows folder was maybe
> acceptable 10 years ago but not now...

Read the PEP:

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



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


Re: fastest data structure for retrieving objects identified by (x,y) tuple?

2012-10-03 Thread Steven D'Aprano
On Thu, 04 Oct 2012 01:58:16 +, Steven D'Aprano wrote:

> adict: 24712
> alist: 23127324
[...]
> So in this situation, a list of lists uses about 100 times
> more memory than a dict, but look-ups are about 6% faster.

Correction: about 1000 times more memory. Sorry for the typo.



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


+ in regular expression

2012-10-03 Thread contro opinion
>>> str="  gg"
>>> x1=re.match("\s+",str)
>>> x1
<_sre.SRE_Match object at 0xb7354db0>
>>> x2=re.match("\s{6}",str)
>>> x2
<_sre.SRE_Match object at 0xb7337f38>
>>> x3=re.match("\s{6}+",str)
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.6/re.py", line 137, in match
return _compile(pattern, flags).match(string)
  File "/usr/lib/python2.6/re.py", line 245, in _compile
raise error, v # invalid expression
sre_constants.error: multiple repeat
>>>

why the  "\s{6}+"  is not a regular pattern?
-- 
http://mail.python.org/mailman/listinfo/python-list


final question: logging to stdout and updating files

2012-10-03 Thread Littlefield, Tyler

pHello all:
I've seen frameworks like django reload files when it detects that 
they've been changed; how hard would it be to make my engine reload 
files that it detects were changed? I'm also curious how hard it would 
be to build in some error recovery. For example right now when an 
exception occurs, the player is sometimes just left hanging. It's a lot 
harder with Python for me, because I don't get the compile-time errors 
that I would with c++ for example to know that I did something wrong; 
while that's not always useful/and by far it doesn't catch everything, 
it does help. I'm familiar with things like pychecker, but it seems to 
be reporting a lot of issues that aren't issues. For example, I have a 
world module which is the core of the engine; it handles players, as 
well as keeps tracks of all rooms that are loaded in the game and that. 
Because player and world would have circular imports, I just pass the 
world object into player functions like logon/create. Pychecker tells me 
that the world parameter (which is a local var at that point) shadows 
the world variable in world; world is a singleton, so when you import 
world it just has a world = World() at the bottom of the module.


also: I have the following code:
logging.basicConfig(filename=path.join("logs", "mud.log"), 
level=logging.DEBUG)

logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
I like it displaying to stderr since usually when I'm doing this I'm in 
screen bouncing back and forth between the output and the tt++ session, 
but right now I can't get a couple of things; I'm not sure how to set it 
to log and all other messages to stderr as I did for the file, and I'd 
like to use a rotating log handler so that it'll rotate when the files 
are say above 16 KB or something. Is it possible to do something like 
this; perhaps make it compress the file before it writes to disk, or 
call a command to do so, so that it wouldn't hang the entire mud while 
it compresses?

Thanks, and sorry again for all the questions.

--
Take care,
Ty
http://tds-solutions.net
The aspen project: a barebones light-weight mud engine:
http://code.google.com/p/aspenmud
He that will not reason is a bigot; he that cannot reason is a fool; he that 
dares not reason is a slave.

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


Re: + in regular expression

2012-10-03 Thread Ian Kelly
On Wed, Oct 3, 2012 at 9:01 PM, contro opinion  wrote:
> why the  "\s{6}+"  is not a regular pattern?


Use a group: "(?:\s{6})+"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is pylaucher in Python 3.3 being installed in Windows folder?

2012-10-03 Thread Ian Kelly
On Wed, Oct 3, 2012 at 8:04 PM, Steven D'Aprano
 wrote:
> On Wed, 03 Oct 2012 14:13:10 -0700, Piotr Dobrogost wrote:
>
>> Why is pylauncher in Python 3.3 being installed in Windows folder and
>> not in Program Files folder? Installing into Windows folder was maybe
>> acceptable 10 years ago but not now...
>
> Read the PEP:
>
> http://www.python.org/dev/peps/pep-0397/

The PEP explains why it's in the Windows folder as opposed to the
System32 folder, but not why either of those locations should be
preferable to Program Files.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is pylaucher in Python 3.3 being installed in Windows folder?

2012-10-03 Thread Chris Rebert
On Wed, Oct 3, 2012 at 8:21 PM, Ian Kelly  wrote:
> On Wed, Oct 3, 2012 at 8:04 PM, Steven D'Aprano
>  wrote:
>> On Wed, 03 Oct 2012 14:13:10 -0700, Piotr Dobrogost wrote:
>>
>>> Why is pylauncher in Python 3.3 being installed in Windows folder and
>>> not in Program Files folder? Installing into Windows folder was maybe
>>> acceptable 10 years ago but not now...
>>
>> Read the PEP:
>>
>> http://www.python.org/dev/peps/pep-0397/
>
> The PEP explains why it's in the Windows folder as opposed to the
> System32 folder, but not why either of those locations should be
> preferable to Program Files.

Presumably because Program Files isn't part of the $PATH.
http://superuser.com/questions/124239/what-is-the-default-path-environment-variable-setting-on-fresh-install-of-window
Contrast (from the PEP): "However, the Windows directory is always on the path."

Now, as for why the launcher must be on the $PATH…*shrugs*

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can somebody give me an advice about what to learn?

2012-10-03 Thread Chris Rebert
On Wed, Oct 3, 2012 at 11:31 AM, Wolfgang Keller  wrote:
>> I'm really new to Usenet/Newsgroups, but... I'd like to learn some
>> new programming language, because I learnt a bit of Perl though its
>> OOP is ugly. So, after searching a bit, I found Python and Ruby, and
>> both of they are cute. So, assuming you'll say me "learn python", why
>> should I learn it over Ruby?
>
> The point why Ruby was started (perceived deficit of object-orientation)
> has been remedied since Python 2.2.

Not completely. At the least, there's arguably still the issue of
len() and friends (vs. `.length` etc.), and also of `self` being
explicit.

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


How to execute commands on a windows machine from a Linux machine

2012-10-03 Thread Shambhu Rajak
Here i have two questions,

1.   I want  to write a framework for Linux machine that can execute
commands on windows machine:

How to create a persistent shell between Linux and Windows machine.

2.   I require to extract windows disk management features, for eg:
Number of drives on that windows machine ,

volume size of the machine, to create a partition, all these storage stuffs.
I want to achieve all these features of windows machine, from linux.

-Shambhu

 

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


Re: How to execute commands on a windows machine from a Linux machine

2012-10-03 Thread Andrew Berg
On 2012.10.04 00:13, Shambhu Rajak wrote:
> Here i have two questions,
> 
> 1.   I want  to write a framework for Linux machine that can execute
> commands on windows machine:
> 
> How to create a persistent shell between Linux and Windows machine.
> 
> 2.   I require to extract windows disk management features, for eg:
> Number of drives on that windows machine ,
> 
> volume size of the machine, to create a partition, all these storage
> stuffs. I want to achieve all these features of windows machine, from linux.
If you must use Python, there are execnet and RPyC, which will allow you
to execute Python code remotely. Otherwise, there is Copssh, which has
an SSH server that runs on Windows.

http://codespeak.net/execnet/
http://rpyc.sourceforge.net/
https://www.itefix.no/i2/copssh
-- 
CPython 3.3.0 | Windows NT 6.1.7601.17835
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can somebody give me an advice about what to learn?

2012-10-03 Thread Steven D'Aprano
On Wed, 03 Oct 2012 21:47:33 -0700, Chris Rebert wrote:

> On Wed, Oct 3, 2012 at 11:31 AM, Wolfgang Keller 
> wrote:
>>> I'm really new to Usenet/Newsgroups, but... I'd like to learn some new
>>> programming language, because I learnt a bit of Perl though its OOP is
>>> ugly. So, after searching a bit, I found Python and Ruby, and both of
>>> they are cute. So, assuming you'll say me "learn python", why should I
>>> learn it over Ruby?
>>
>> The point why Ruby was started (perceived deficit of
>> object-orientation) has been remedied since Python 2.2.
> 
> Not completely. At the least, there's arguably still the issue of len()
> and friends (vs. `.length` etc.), and also of `self` being explicit.

I'm not entirely sure which "perceived deficit of object-orientation" is 
being talked about, or why anyone but OOP purists would consider that a 
problem.

Python is *more* object-oriented than Java, and I don't hear anyone 
complaining that Java isn't object-oriented. Everything[1] in Python is 
an object. *Everything*. Ints are objects. Strings are objects. Arrays 
are objects. There's no distinction between "boxed" and "unboxed" ints, 
like in Java or Haskell -- Python just has ints, and they're always 
objects.

As for len() and friends, that's a red-herring. Just because the syntax 
is written len(x) instead of x.len() doesn't make Python less object-
oriented. It's just syntax: "a + b" is no less OO than "a.plus(b)".

Somebody might not *like* the syntax "a + b", or "len(x)", but they 
should just say so, and not pretend that it isn't OO.

Likewise self. Explicit or implicit, how does that make a language less 
or more object-oriented? That's as foolish as saying that Python isn't 
object-oriented because you don't have to declare the type of variables:

x = (float)1.234

Again, there are arguments for and against explicit self, but "explicit 
self is not OO" is not a valid argument.

Being object-oriented has both costs and benefits. Java compromises on 
the idea of OOP for performance: native, non-object ints are faster than 
object ints. All these people complaining that Python isn't OO enough 
because you have to write "self" in method declarations, why aren't they 
complaining that Java isn't OO enough because ints are unboxed primitive 
types?



[1] Emphasis on the *thing* part. Control structures aren't things in 
that sense, they aren't values at all, they are actions that takes place 
during execution.


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