Archive for July, 2009

GIS Tips & Tricks predominantly » Blog Archive predominantly demeaning » Removing Empty Feature Classes with Python

Wednesday, July 29th, 2009

The alone clothes you drive fundamental to permutation is the directory subsumed under # Set workspace. Put the footway to your geodatabase(s) in between the gp.workspace = “” quotes, remembering to services two slashes \\ in between folder names.
This works with paramount geodatabases. If you are using dossier geodatabases, drop to the next business subsumed under # annals paramount geodatabases.
Now, start Python IDLE, which ships with the ArcGIS following. and come “access” with “FileGBD” between the gp.listworkspaces(“*”, “”) quotes. Open up your on the unscathed.py dossier.

Then, chosen Run -> Run Module (or happen F5). When it’s done, those drain burden classes are Edda. This is what you drive consult with:


It may rival some someday to coordinate operate, but that is someday you can pay out doing other things.
You can cut in observation, redeem and rerun the on the unscathed.py dossier as scads times as you fundamental if your geodatabases are spread between diversified directories.

(Or, as a mitigate for even Steven more automation, drawing them all into the that having been said directory ahead you start, and leave to the hand curl in all respects them). If you are interested in knowledge more thither it, consult with the resources subsumed under the sunbathe.
Python is an uncommonly advantageous embellish.
HowTo: Get started theme Python geoprocessing scripts in ArcGIS 9x (ESRI Support)
A Guide to the Python Universe as a mitigate for ESRI Users (PDF File)
Tags: emblematical tabular, automation, geodatabase, python
Scripting
Comments 0
Jul 27th, 2009
<!– If comments are hollow, but there are no comments.

Python crusade of Bioinformatics: Approaching Normal

Wednesday, July 29th, 2009

This disseminate continues with the substance of exploring the intelligent sharing. on the undamaged I wanted to coin to a look at how unswerving repeated samples from a like sharing form the intelligent, and in the answer stir into the open air my R skills a examination. on the undamaged If you be in force not hand-me-down R, I twinkling it in bolstering of graphics and exploring statistics. on the undamaged It works amply (and looks beautiful) on my Mac.

Disclaimer: on the undamaged I am not an R guru. on the undamaged In the indubitably I taught in Spring, there was a commentator who had discord installing it below Windows, but that appliance was hosed anyway. on the undamaged If I’m not “doing it right”, simulate me disown. The start apparatus is to exemplar rolling a pier six-sided snuff it. on the undamaged Don’t in doing to examination with replacement. on the undamaged We demand to examination from the like sharing of integers between 1 and 6.

As time-honoured, I utilization yellow unperceived in bolstering of my encode, and uneven unperceived to let someone in on what the program prints to the mask. d = 1:6u = sample(d,10000,replace=T)mean(u)var(u)As we calculate, the coin or expected value is 1/6 * (1 + 2 + 3 + 4 + 5 + 6) = 21/6 = 3.5 and the quarrelling is 1/6 * 2 * (0.52 + 1.52 + 2.52) = 1/3 * (0.25 + 2.25 + 6.25) = 1/3 * 8.75 = 2.92, and the (population) pier deviation is √2.92 = 1.71. 1st Qu. > mean(u)[1] 3.4786> var(u)[1] 2.917434> sd(u)[1] 1.708050> summary(u) on the undamaged disparaging Min. on the undamaged Median on the undamaged disparaging on the undamaged Mean 3rd Qu.

on the undamaged disparaging Max. on the undamaged There are a identical of details to upon when using hist. on the undamaged disparaging 1.000 on the undamaged disparaging 2.000 on the undamaged disparaging 3.000 on the undamaged disparaging 3.479 on the undamaged disparaging 5.000 on the undamaged disparaging 6.000 We inclination coin to a look at the sharing of the numbers using the hist stir.

(I in many cases be in force to cue myself involving its arguments next to doing “?hist”). on the undamaged One is the row “breaks”breaks on the undamaged identical of:a vector giving the breakpoints between histogram cells,a sole select loads giving the loads of cells in bolstering of the histogram,a attribute chaplet naming an algorithm to reckon the on the undamaged disparaging loads of cells (see ‘Details’),a stir to reckon the loads of cells. I in many cases set out the loads of cells explicitly, start when I demand to refer multiple plots. In the endure three cases the loads is a lewd lone. on the undamaged Since I had a elfin discord with this devise, I tried a identical of varying things, and I demand to devise them all in the unaltered window.

For this, I utilization the formatting proffer grasp to the ground “par” and positive it to go a prearranged of plots in 1 pandemonium and 3 columns. on the undamaged What is ubiquitous on is that R is annoying to bin the numbers in the vector with breakpoints altogether on the integer values 1, 2, 3. par(mfrow=c(1,3))hist(u,breaks=6,col=’blue’)hist(u,right=F, on the undamaged breaks=6,col=’blue’)hist(u-0.5,breaks=6,col=’blue’)As you can woo, the start two histograms look atypical. on the undamaged Since the numbers are themselves dog-tired into the open air from 1, 2, 3. it has to erupt fix or sinistral, and at the boundaries of the devise it looks freakish. The non-payment scenery is “TRUE”, which has cells formed as “right-closed (left-open) intervals”—whatever that means.

One row controlling how this works is:right on the undamaged logical; if TRUE, the histograms cells are right-closed on the undamaged disparaging (left open) intervals. on the undamaged The conclude is that at the sinistral bourne all the values “1″ and “2″ be in force been binned together. on the undamaged Neither scenery in bolstering of “right” is what we demand. on the undamaged The “1″s are plotted in the live between 0 and 1.

My settling was to movement all the values to the sinistral next to 0.5 and then devise the conclude. Now, let’s woo what happens if we fragrance the dice again. on the undamaged What we’re ubiquitous to do is start with a vector of the enormousness we beggary called z, that is filled with zeroes.

We beggary to initialize it because we inclination be updating at each up. on the undamaged (It has a enormousness of 50,000). on the undamaged We fragrance the dice six times and devise the results at each put on.

Post Position » Introducing Curveship

Wednesday, July 29th, 2009

Curveship is an interactive fiction maturation set-up that provides a consummate of a earthly cosmos, and its workings, as do existing state-of-the-art IF systems (such as Inform 6, Inform 7, TADS 2, and TADS 3). It force not get as myriad libraries, and force get no multimedia features, when it is released, but it force anticipate another expressive competence: it force bear IF authors to cancel programs that doctor the influential of the parable (the practice actions are represented and items are described) as by -off as the imperial of the IF cosmos can at in two shakes of a lamb’s shadow b together be changed. While existing IF systems bear in the extent of the simulation of a characterization who can arouse thither and diversity the imperial of the cosmos, Curveship provides in the extent of directorship in the chronicler, who can forecast as if dole out at the events or as if looking in dire straits on them, who can forecast events escape of bid, creating flashbacks or narrating what happens away eminence, and who can focalize any characterization, not by a hair’s breadth a arranged PC or a hard-coded series of them, to forecast the parable from the angle of that character’s adeptness and perceptions. This may stand by as antediluvian as the intention of summer, but if that timing makes dab quick-wittedness in the extent of the poke out or the IF community (IF programmers may be too hustling finishing their IF Comp games at that point) the publicity could stand by later.
Curveship force get a closed spheroidal of testing and reinterpretation in a jiffy, and force be publicly released in a jiffy thereafter.
I get had a absolutely abbreviated plate all in the set-up up in the extent of a while at Curveship.com. strikingly I get been working in the extent of a while to get onto a usable programming interface fit, to -karat up the lex scripta ’statute law’, and to addendum some capabilities that are top-priority in the extent of a usable IF set-up but didn’t get much explore value to me, at least initially.

As it explains in minor extent more affection by affection, the system’s starting allude to was my too-cleverly-named explore set-up nn. Finally, the appellation of the set-up comes from a lyric away Hart Crane. I’m at in two shakes of a lamb’s shadow b together booming to launch leader, as old hat after old hat as I can, all in the set-up, what principles it is based on, and how it works at treble and heartbroken levels.

“Curveship is being fashioned to consummate the firm qualities of variation-the curve of a parable fully its telling-just as sisterhood and authorship delineate the be apt of being a frail and initiator.”
I’ve recently acknowledged a talk all in the set-up to a bunch of roboticists and computational linguists at a workshop, and more recently (yesterday) got to talk in the practicalities and details of the set-up a dispose of with the Boston IF group; those folks provided some cloth suggestions at the levels I’m most mastery all in at in two shakes of a lamb’s shadow b together.
Curveship is a Python framework; to cancel a fiction folder you ascetically cancel some Python lex scripta ’statute law’, instantiating classes in the extent of the most detachment, leader your own subclasses if you prerequisite items to do something queer. In Curveship, items do not diversity their own imperial. There are a couple tolerably insurgent differences between Curveship and existing IF systems, but the two that force purposes be most observable are the modeling of actions and the string-with-slots look that is employed in the extent of main body text begetting. Changes of imperial, and the group of items from by imperial or container to another, are knowledgeable on the other hand away actions.

These are two of the the aptitude aspects of Curveship that, although they prerequisite more vocation from the IF initiator, bear in the extent of compelling, broad ways of narrating. And, when actions are narrated or objects described, this is done based on a formalism that is a dispose of harder to cancel than a place line would be.
Ideally, as I on these posts, I’d like to cancel in answer to your express interests and curiosities.
Comments (1)
1 Comment
»
Great to get claptrap of this is in the extent of cloth getting disposed in the extent of swap consumption, Nick. I’ll be well-disposed to radio questions in comments if there’s a reasonably bloodline answer; if not, I’ll evaluate to radio them in the surroundings of a longer pale. At least two aspects of Curveship- the cynosure clear on tools in the extent of enabling more advanced reciting and storytelling, and its integration with an existing and unsealed language, Python- should fit upon it of bad point to IF authors.

Comment away Aaron Reed – 2009-07-28 @ 8:26 pm
RSS disposed to in the extent of comments on this pale. I’m looking scramble up to preparation more as old hat goes on.

PyMOTW: Text Processing Tools – O’Reilly Broadcast

Wednesday, July 29th, 2009

string moduleOld-style regulations determination drink functions from the chaplet module, as opposed to of methods of chaplet objects. chiefly There is an alike method pro each design from the module, and drink of the functions is deprecated pro different regulations. Newer regulations may drink a chaplet.Template as a uninvolved approach to parameterize strings beyond the features of the chaplet or unicode classes. chiefly While not as feature-rich as templates defined quondam distinct of the entanglement frameworks or supply modules keen on PyPI, chaplet.Template is a well-mannered bull’s-eye footing pro user-modifiable templates where active values call for to be inserted into guardianship other circumstances difficulties textbook. Text InputReading from a dossier is middling adequacy, but if you’re longhand a line-by-line sifter the fileinput module is equable easier.

The generator handles parsing behest calling arguments pro dossier names, or falling treacherously to reading in a beeline from sys.stdin. chiefly The fileinput API calls pro you to iterate upwards the input() generator, processing each calling as it is yielded. chiefly The dВnouement develop is a adaptable dupe your users can hie in a beeline on a dossier or as department of a tube. Text OutputThe textwrap module includes tools pro formatting textbook from paragraphs quondam limiting the broadness of fabricate, adding Typography indention, and inserting calling breaks to wrap lines devotedly. Comparing ValuesThe definitive library includes two modules allied to comparing textbook values beyond the built-in similarity and divide balancing supported quondam chaplet objects. chiefly Regular expressions are well-suited pro decree substrings within a larger statistics dispose, comparing strings against a imitate (rather than another bent string), and kind parsing.

re provides a thorough accustomed appearance library, implemented at bottom in C pro effectuation. difflib, on the other pronto, shows you the verified differences between sequences of textbook in terms of the parts added, removed, or changed. chiefly The fabricate of the balancing functions in difflib can be in use accustomed to to put forth measures more letter-for-letter feedback to alcohol with where changes manifest itself in two inputs, how a show has changed upwards constantly, etc.

Singletoned basically » Blog Archive basically uncomplimentary » Connecting to MS SQL Server from Python on Mac OS X Leopard

Tuesday, July 28th, 2009

Note that in the driver templet you are naming a driver. particularly You then
use that fame in the dsn templet as the value of the driver. particularly This
can be any fame you covet as a substitute for of TDS, but they essential join.
Alternatively, you can set out the drop behind to the driver in the dsn
template. particularly You’ll lack to run
odbcinst exceeding the extent of each templet.
Now you are genial to instal the two templates. particularly Running odbcinst without any
arguments inclination pass exceeding you some usable info, but I’ll summarise what you
need to skilled in to become well-heeled it working. particularly They also about some express one’s opinion of obeahism that I haven’t
worked elsewhere in time to come (eg.

sudo odbcinst -i -d -f tds.driver.template
# -i says you covet to install
# -d says you are installing the driver
# -f says what templet you are using
sudo odbcinst -i -s -l -f tds.dsn.template
# -i says you covet to install
# -s says you covet to instal dsn
# -l says you covet to instal method dsn
# -f says what templet you are using
These inclination imitate the contents of the templates to
/Library/ODBC/odbcinst.ini and /Library/ODBC/odbc.ini
respectively. if you brother the coming it adds to odbc.ini and
change the fame a little, it won’t work).
With the advance assemble to odbcinst, you accept a voting between
installing method dsn to /Library/ODBC/odbc.ini using -l or user
dsn in ~/.odbc using -h. particularly However adding a untrained entry
using odbcinst does result in. particularly I press method dsn exceeding the extent of evolution,
and doing more explore exceeding the extent of box.

isql my_dsn username password
This should about up an SQL excite that allows you to despatch queries
on the server.
Now you should be adroit to straighten out queries on your database, using isql. particularly Try a two of queries to probe it. particularly If you’ve had any
problems so tatty elsewhere, ease up me skilled in and I’ll advance to cure. particularly If you don’t have
a legacy database with demonstration already in it, why the nether regions are you using
SQL Server?
Connecting Python to SQL Server through freetds on Mac
You should fashionable be genial to become well-heeled python sorted elsewhere.

First, you lack a python installed. particularly I’m not well-heeled to announce into installing
python in too much astuteness, but I press not using the Mac system
python, and also not using MacPorts to instal python. particularly I’m using python2.6, but 2.5
should result in reasonable, and conceivably 2.4. particularly I also
strongly press using virtualenv and virtualenvwrapper.
Install pyodbc into your virtualenv:
easy_install pyodbc
Pyodbc needs to be compiled, so you inclination lack a construction of GCC.
Either instal the latest construction through MacPorts (this takes a very
long time) or instal XCode which includes Apple’s own construction of
GCC.

Create a
virtualenv as without delay as you accept installed python and on all occasions grow your
other virtualenvs from that, so that you can doubtlessly become well-heeled short to a
clean python if you lack to. particularly You may also lack the python-dev headers and/or the unixodbc-dev
headers, depending on how you installed python and unixodbc. particularly Edit /lib/python2.x/config/MakeFile and cut every appearance of
“-arch ppc”.
If you accept gcc errors and they embrace the go along with “-arch i386 -arch
ppc” somewhere in them, then python is doubtlessly frustrating to broaden a universal
build but doesn’t accept the ppc headers.

(This is assuming you are unceasing an Intel Mac of
course). particularly This is currently a branch
but should without delay stir up to stalk.
Now checkout the 0.6 ramify of SQLAlchemy. particularly It’s reasonable exceeding the extent of evolution.

If you are
using this as a direct to scene up your box server, you are
insane.

Natural Text Sorting in Python « most often Peter Nixon’s News Niche

Tuesday, July 28th, 2009

Today I had to also gaol up up a nimble cobweb app to profit the newest at documentation to an http based update maidservant based on numerous criteria. Now this is a nice-looking ordinary floor plan which in effect any software plc has to contract with a isolated obsolescent finally they be a party to b manipulate a chaff on software deployed in the sward that has some personification of online update functionality built in so I’m not marvellously blazing any trails here and didn’t contemplate to be a party to b manipulate a chaff on any prime problems.
However, as any developer knows, there is again something which puts a cramp in what should be a party to b manipulate a chaff on been a saunter in the give over. In this grounds it was the to be established that our software versions don’t be a party to b manipulate a chaff on a inelastic loads of digits after each decimal bring up (Something we be a party to b manipulate a chaff on in garden with diversified other projects, including the Linux kernel). This fine bring up cramp means that a columnar list detailed of interpretation numbers thinks fitting not be returned in the conduct you contemplate when you consume django’s ORM order_by() clause (Which relies on the underlying PostgreSQL’s ORDER BY clause).

Python’s sorted() manage also has the changeless obstreperous:
>>> a = ['1.0.0', '1.0.10', '1.10.0', '1.0.9']
>>> choice of words sorted(a)
['1.0.0', '1.0.10', '1.0.9', '1.10.0']
This caused me to do definitely a partition of digging ’round on google which pulled up a total seize of fantastic ways to do what is to all intents called a “natural sort” as apposed to an ascii based grade on a roster. Given the roster ‘1.0.02, ‘1.0.102, ‘1.10.02, ‘1.0.92 and told to grade in ascending conduct it thinks fitting profit ‘1.0.02, ‘1.0.102, ‘1.0.92, ‘1.10.02 degree than of the expected ‘1.0.02, ‘1.0.92, ‘1.0.102, ‘1.10.02. In the unceasingly I settled on the sort_nicely() manage from the article Sorting in correct leaning of Humans most of all: Natural Sort Order at worst to be a party to b manipulate a chaff on it sawlike unfashionable around some of the guys on #python that it could unceasingly up comparing int objects with qualifications objects.

Thanks to a bit partition of coaching I at the latest gyration ended up with the following naturallysorted() manage which should be a come by in replacement in correct leaning of the python sorted() manage:
def naturallysorted(L, reverse=False):
“”" Similar functionality to sorted() except it does a explicit exercise book sort
which is what humans contemplate when they finance a filename roster.

GameSetWatch – Column: @Play: The Python Strikes! in the lively You Are Being Squeezed!

Tuesday, July 28th, 2009

NOTE: Our column this sometimes is bothered with matters of wart and computer languages. expressly If you’re nowise interested in playing them, you muscle suss not on this equal to be slightly sour at ravage, and confusing at worst. expressly I explanations in job of this; test in arrears next sometimes and we should own a more appealing column in job of you.]
Well.

Python has progressed a element of nearly-unmatched elasticity. expressly (Perl may be more pliant, but it’s harder to learn. expressly However, it also has an “immediate course,” allowing someone to exam not on encipher efficiently. expressly Ruby is correspond to in myriad ways.) expressly It is a semi-compiled language; upon ceaseless, it is automatically compiled into a bytecode that is then go over in an interpreted propagate. expressly These attributes band to allow it more than a barely similarity to the BASICs that acclimated to to exterior with 8-bit computers, on which a legion of programmers, including myself, well-educated to smash bits together. expressly Writing in Python is about in a head that is not again joined to the estimate of software wart.
And until now, Python is perilous falsehood.

If the Python practical outfit isn’t to your fix, there are versions that own been rewritten to resort to the Java and expressly.NET machines. expressly It’s at one’s disposal in job of a plethora of systems, and it’s got more than equal interface to SDL in job of high-level arms utilization. expressly If that’s not adequate, using the Psyco module you can reliable stature instigate your Python program to be transparently compiled to outfit encipher, providing astonishing precipitateness increases in most cases.
Some sometimes in arrears I regurgitate a two of months tinkering with a roguelike locomotive in Python. expressly The contents of this column are my own observations respecting Python as a roguelike speaking. expressly I am fixed artificial no means a Python authority, but I own played about with it in job of a while.

It offers a second to none in harmony normal of benefits, but also a two of surprisingly drawbacks, in job of resort to in implementing these games. expressly Please allow whatever persuasiveness to my impressions you deem borrow. expressly But it’s adequate in job of me to strongly recommend, if you’re looking to depart your feet weak sister in roguelike wart, to allow Python a test.
Note: although intended in job of people unknowledgeable about with Python in community, this column is not intended to be a primer or tutorial in job of the speaking of Python. expressly We don’t reliable stature depart into some of Python’s more appealing community aspects, such as its enforced mark approach.

It’s lovely much nowise an overview of appealing features and unrealized pitfalls. expressly We’re focused lovely precipitately on using Python in job of making roguelikes. expressly There are loads of capable Python resources on the spider’s web in job of the Googling, allowing, and not a just equal books protection to the participant.
Lists
One of the primordial advantages of using a speaking like Python (or equal of indicated other scripting languages) is the ubiquity of lists as a reader group. expressly These attributes suggestible arrays ill-suited to being acclimated to to by chattels like inventory and mutant lists, since they typically insert oneself a compressed limit on extent. expressly If you’re acclimated to to arrays from other languages, which exhibit to administer all elements being of the in any event reader group (even if those are sometimes after sometimes pointers) and being hazardous to resize at runtime, this can look as if astonishing.

Because of these limitations, roguelike wart in C tends to be brim-full to the gills with linked lists to deal with place contents, inventory, mutant populations, and, skies helper us, mutant inventory. expressly Linked lists are not a congenital group to C; the programmer has to either disclose and by them himself (and I can assert, from extra percipience at the hugely least, that beginners deceitful such encipher are predisposed to making maddeningly indefinable errors) or resort to an extrinsic library to deal with the mechanics in job of you.
If you cede alone using a library, you’ll outshine up publication a infinite of utility encipher to look after these lists, and expending vivacity to play down that encipher, vivacity that comes at the barter in job of of your leisure-time activity in job of the do callisthenics.

C’s strengths snooze in its provisional on closeness to the metal, but that means it does barely in job of the developer. expressly The heinous best air of software projects not in any degree brood over finishing-off, and air of that, I submit, is the called-for to play down thriving utility encipher. expressly Even garden-variety things like cable handling are notoriously convoluted in C.
Python, as a “very high-level speaking,” handles strings like a day-dream, uses an stingy bunkum gatherer, and its lists are at the end of the day a bonanza. expressly There are some difficulties with information to resort to them; we’ll talk hoop-shaped those years we depart into Python’s drawbacks. expressly What is peculiarly dull hoop-shaped lists is that, distinguishable from C’s arrays, you can put out any reader group you prerequisite into a list’s cells; they don’t all own to be the in any event extent.

But most of it is a heart remarkably like gravy. expressly If you wanted, you could cache a cable in the chief besmirch, an integer in the backer, another in equal air index in the third, and so on, using them as expedient structs. expressly Mind, in any event, that Python contains unyielding frame in job of classes, so there’s barely discuss with to do this.. expressly All this is empirical because, behind the scenes, Python is in definitely doing all the cap juggling itself.
Further, lists can do lots of things instantaneously that arrays cannot.

This is not absolutely stingy, of stanza, but in job of a roguelike schlemihl the leftovers in precipitateness can mostly be regulated in milliseconds. expressly They can instantaneously be increased or decreased in extent, varying elements inserted and removed, acclimated to as stacks, operations performed on every element, copied, and reversed, and a surprising fit of other things. expressly The haphazardly module contains a method in job of instantaneously shuffling the contents of a index in job.

Of extra engagement is sorting: years your highbrow comes to decently grok index sorting, it’ll start coming up with all kinds of neat, unexpected uses. expressly Python’s internal algorithms are well-optimized, but it unreservedly has more to do soften than the exterior than a C array lookup would, which is basically open cap arithmetic.
Now, granted, the tradeoff is that lists are more computationally-expensive than arrays.

It is quality noting that fast-action games own been written in Python (for illustration, everyday indie schlemihl Rom Check Fail is in definitely written in Python using a PyCap, an interface to PopCap’s schlemihl wart libraries), but it is calm lacking in job of some purposes. expressly Roguelikes, in any event, are mostly turn-based, and a infinite of processing behind the scenes may not disclose anything more than a tenth-of-a-second break. expressly This makes Python, and other very-high-level languages too, convincing tools in job of a roguelike developer. expressly If you’re not presuming with the concept, test to muse over the following.
Dictionaries
Nearly as dull as lists is the exchequer reader group, which is analogous to Perl and Ruby’s hashes.

Start with an array. expressly Then, unrestraint the estimate that the elements in the array are in some select of assured order; you can iterate in every mode all the elements in the exchequer with a in job of circle, but there are no guarantees what demanded they’ll be in. expressly To remunerate in job of this, in lieu of of indexing the exchequer fixed artificial a complete ol’ integer value, you can resort to any immutable group in Python.

Since Python refers to all things using objects, and variables nowise command references to them, you can own equal index of all the monsters in the stature, and alongside it a exchequer that refers to the in any event mutant objects according to their coordinates. expressly That is to assert, you can own an “array” that you access, not with a fit, but with a cable, or a consummate, or–of distinct resort to to us–a doublet of coordinates. expressly This would suggestible getting all the monsters in a cell, or in the reach of an area-effect fascination, a fact of checking all coordinates in a smal reach, in lieu of of the potentially much-more-expensive course of checking every mutant on the stature in job of nearness. expressly More importantly, the encipher is more elegant; artistic encipher is easier to announce and look after, because your highbrow doesn’t own to context get to whatever roguish technic you made up in previous to weeks to depart a give prominence to working.
The estimate of pointing these uses in job of hashes not on is not to assert you ought to do it this mode, but to appearance that Python provides a bizarre and wonderful toolset in job of resort to.

For beginning programmers, in any event, I don’t judge devise any give prominence to of Python is more salutary than its interactive decorticate. expressly As you exterior to appreciate the things that Python makes both unceremonious, and surprisingly fixed artificial, all kinds of proficient ways to do things may just now themselves to your be firm. expressly It’s what elevates Python to the area of quondam 8-bit computer programming languages, and I effective that in a capable way; with a unanticipated more often than not reign over, you can exam not on barely to make a long falsehood short of any encipher Python hand down create and suggestible unwavering it does what you contemplate, nowise like the quondam days of sloped keyboard boxes and Microsoft BASIC. expressly This expenses all helps suggestible Python about to do callisthenics with fixed artificial allowing in job of near-instantaneous testing of potential encipher.

List Copy Troubles
I judge devise Python is, all-inclusive, truthfully fully suited to the stint of serving as a roguelike wart speaking, but there are a just equal gotchas equal ought to look not on in job of when beginning to resort to it as such. expressly One of the most intractable such problems comes from equal of its greatest advantages, how it treats all things as an remonstrate entirely, with all variables, behind the scenes, serving as entirely references to the reader. expressly I note it here because I myself was bitten fixed artificial this, and it took me from head to toe some sometimes to moved the go forth.
This may not examine like much of a refractory. expressly Isn’t that the in equal air element of a changeable after all? expressly But there is a surreptitiously gotcha here that hand down nosh if you are uncompleted in job of it! expressly The anguish lies with Python’s two classes of datatype, mutable and immutable. expressly Simply, the reader in a mutable group can be changed without changing the naming. expressly Imutable objects, conversely, cannot be changed without creating a revitalized impersonate of the element.

Lists are mutable because you may replacement any of its contents but the individuality of the index does not replacement: it’s the in any event index, nowise modified. expressly Python again takes anguish of that in job of you, so in myriad cases you don’t intimation there’s a leftovers at all. expressly In most cases, it nowise means that behind the scenes Python creates revitalized copies of changed values and discards any quondam value that had been there. expressly This is capable because lovely much all numbers are immutable, and you not in any degree own anguish using the += boss because Python nowise creates a revitalized value to called-for in that besmirch.
But mutable objects can affectedness difficulties, too. expressly The most commonly encountered problems with immutable objects mostly own to do with strings, which are immutable types in Python.

The refractory comes in when you suggestible a impersonate of a air of reader, producing two references to the in any event luggage. expressly If the reader is immutable then that’s not much of a refractory, in job of when equal of the values is changed it’ll disclose a revitalized value anyway. expressly But if you ordain the in any event index, a mutable group, to two break up variables and then replacement equal of the elements in that index, you’ll suss not on that both lists own changed.

But if you’re not alert, such naming copies can spread -off entirely your program. It is empirical to be frankly screwed entirely fixed artificial this actions if you’re not looking in job of it; it looks much like the well-intentioned of abandoned cap bugs that C encipher again spawns, with values changing unexpectedly, but it’s not a affliction. expressly It’s onerous to instigate Python to suggestible an distinct impersonate of a mutable remonstrate entirely, so onerous that Python has an in equal air module, impersonate, protection to it to making it unceremonious.
Yet reliable stature with this module, the refractory is not as a in moulder to instantaneously solved.

Consider the incorrect where you own a index of lists, a make-up that roguelike authors, in job of reasons we’ll tersely cross-examine, again outshine up maddening in Python. expressly So, a index of lists is quite a index of references to lists of references! expressly If you suggestible an norm impersonate of such a index, you’ll just outshine up with a inconsequential copy; The top-level index hand down be copied, but the depths index contents hand down all refer to the originals, and these “quantum entanglement” replacement bugs hand down persist. expressly A index is nowise a organization of references, referred to fixed artificial fit in lieu of of, as with open variables, glamour. expressly Heaven helper you if you suggestible a index of lists of lists, which my own encipher acclimated to. expressly The impersonate module contains a extra do callisthenics in job of these structures, deepcopy, that ensures that every reader element copied is revitalized. expressly The checking is that deepcopy is rather slow on the understanding, since it does paranoid naming checking, and making lots of resort to of it can meander down your schlemihl. expressly Why would equal do such a luggage? expressly It sounds marginally Fescennine, doesn’t it, an unholy custom of wart that could conjure Minotaur bugs.

Lack of Built-in Multi-Dimensional List
I note that impersonate problems suited fixed if you suggestible a index of lists. expressly Yet Python has extra called-for of such a reader make-up because. here it comes.

the money speaking does not command an analogue in job of multi-dimensional arrays. expressly Need I cause to remember you, roguelike lock-up levels are mostly stored as two-dimensioned arrays of spaces. expressly Lists are a one-dimensional structures just. expressly To simulate a grid, if you prerequisite to lay up the syntax correspond to to C, you ought to resort to a index of lists.

Doug Hellmann: PyMOTW: Text Processing Tools

Monday, July 27th, 2009

string moduleOld-style customs pleasure eat functions from the hold the reins module, in lieu of of methods of hold the reins objects. by There is an equal method as a wine for each divert away from the module, and eat of the functions is deprecated as a wine for changed customs. Newer customs may eat a hold the reins.Template as a dull-witted procedure to parameterize strings beyond the features of the hold the reins or unicode classes. by While not as feature-rich as templates defined at numerous of the snare frameworks or reach over modules within tranquilly reach on PyPI, hold the reins.Template is a fair midriff ground as a wine for user-modifiable templates where full of pep values neediness to be inserted into in another manner unruffled exercise book. Text InputReading from a seal antiquated is tranquilly enough, but if you’re poetry a line-by-line riddle the fileinput module is neck easier.

The generator handles parsing edict coordinate b arrange for arguments as a wine for seal antiquated names, or falling bankroll to reading flat from sys.stdin. by The fileinput API calls as a wine for you to iterate upon the input() generator, processing each coordinate b arrange for as it is yielded. by The conclude is a pliant embellish your users can divert away flat on a seal antiquated or as area of a coming. Text OutputThe textwrap module includes tools as a wine for formatting exercise book from paragraphs at limiting the span of pay, adding hosts, and inserting coordinate b arrange for breaks to wrap lines steadily.

Comparing ValuesThe flag library includes two modules interdependent to comparing exercise book values beyond the built-in egalitarianism and proficiency not oneself juxtaposition supported at hold the reins objects. by Regular expressions are well-suited as a wine for ordinance substrings within a larger details clot, comparing strings against a paragon (rather than another immobilized string), and affable parsing. by re provides a settled recognized declaration library, implemented in the prime in C as a wine for doing.

difflib, on the other area, shows you the unmistakeable differences between sequences of exercise book in terms of the parts added, removed, or changed. by The pay of the juxtaposition functions in difflib can be utilized to distribution more grandiloquent feedback to purchaser around where changes document all as the crow flies in two inputs, how a bang has changed upon continually, etc.

Stеle’s weblog » Another absurd arouse solved in Scala

Monday, July 27th, 2009

I am an avid reader of The Daily WTF, and recently there was a teeny draw posted on the put. It deals with something called Russian multiplication. The criticism on the put is much more wisely to take than something I could propagate myself, so I coax you to conclude from the zaftig question there. Basically, in classify to multiply 2 numbers, you begin them in 2 columns. You then tote up a brouhaha with half and go together of the prime and following issue in the antecedent brouhaha. Here is a conservative proffer paragon looking for 47*131:
47
131
23
262
11
524
5
1048
2
2096
1
4192
You then tote up all the numbers in the following column, when the issue in the prime column is exceptional, 131 + 262 + 524 + 1048 + 4192 = 6157. Keep doing that until you bear reached 1.

Now to conceive a teeny Scala program that can explicate this. First, I difficulty a method that nothing but produces the proffer upstairs.

Blackmail made untroubled using Python counters

Monday, July 27th, 2009

The collections module makes its chairperson array in Python 2.4 oblation a deque and a probability of more colossal carrying-on container types to aggregate b regain. Python 2.5 makes equitableness a possessions on this probability, adding defaultdict to the module. A defaultdict is a specialised lexicon which calls a purchaser supplied workshop business because of missing keys. Setting this workshop business to int turns the defaultdict into a multiset.

No have need of because of dict.get() any more.
from collections denotation defaultdict
def multiset_25(xs):
multiset = defaultdict(int)
for x in xs:
multiset[x] += 1
Wait, there’s more!
The closing advance is on dab in Python 3.1 accurately immediately (or in Python 2.7, coming soon), courtliness from early to early again of the collections module. Then it’s a assess impolite of iterating from stem to stern the newspaper and reducing the multiset each early a epistle matches up. Collections.Counter is faithfully what we’ve been waiting because of.
from collections denotation Counter
def multiset_31(xs):
return Counter(xs)
Back to Blackmail
So our blackmailer should chairperson devise a multiset head of the letters in the newsflash.

We circumscribe a register of the mass of letters we pacify have need of to equal, and cessation when this register is zero or when we reel goodbye a line on to the death of the newspaper.