Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Don't do "is False" either. Just do "if not os.path.exists(sys.argv[1])"

Adbot
ADBOT LOVES YOU

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

Suspicious Dish posted:

Don't do "is False" either. Just do "if not os.path.exists(sys.argv[1])"

I still don't understand why. What is the advantage of doing:

"if not os.path.exists(sys.argv[1])"

instead of

"if os.path.exists(sys.argv[1]) is False"

or

"if os.path.exists(sys.argv[1]) == False"

Is this an elegance thing or is this something about how the guts of Python works? I don't see an advantage over any of those short of "it's tradition". "It's tradition" is a perfectly acceptable answer too, Lord knows its often the answer to why we do things in astro.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

JetsGuy posted:

I still don't understand why. What is the advantage of doing:

"if not os.path.exists(sys.argv[1])"

instead of

"if os.path.exists(sys.argv[1]) is False"

or

"if os.path.exists(sys.argv[1]) == False"

Is this an elegance thing or is this something about how the guts of Python works? I don't see an advantage over any of those short of "it's tradition". "It's tradition" is a perfectly acceptable answer too, Lord knows its often the answer to why we do things in astro.

I don't really know what the Pythonesque (TM) answer is but to me saying "if not <thing>" does a better job of expressing your intentions than "if <thing> == False" (or "is"). The "not" version makes it clear (in part because it reads like English) that you're checking for a negative response; whereas the "False" version ties us up in detail (that a negative response is given in the form of the constant False). Of course there are much worse ways you can obfuscate what code is doing but it's the same sort of thing, just on a trivial level.

Edit: Suspicious Dish's post suggests a related point, which is that you wouldn't write "if x == True:"; you'd just write "if x:". By analogy you shouldn't write "if x == False:", just "if not x:".

Hammerite fucked around with this message at 22:16 on Mar 4, 2013

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
This isn't really a Python thing. The if statement tests if something, when converted to a bool, is True. if foo == True: or if foo is True: is considered bad style because the if statement already does the tests for you, so you're adding noise that does nothing.

In Python, the three statements if foo is True:, if foo == True: and if foo: have different meanings. The first one is asking if the value referenced by the "foo" variable is the same object as the one in the "True" object. Thus, if "" is False: will fail, and so will if 0 is False:. if foo == True: asks the object if it compares equivalent to the object referenced by the "True" variable. bool objects, for historical reasons, say that they are equal to 0 or 1, so if 1 == True: will succeed. But, empty strings do not compare equivalent to False, so if "" == False: will fail. And finally, if foo: asks if the object is considered True or False. Any non-zero number considers itself True, and zero considers itself False. All non-empty strings consider themselves True, and the empty string considers itself False. So, both if not 0: and if not "": will succeed.

In the case of os.path.exists, this doesn't matter, because it's guaranteed to return a boolean, but not everything may. You almost always want the last behavior, as it leaves things up to the object's discretion, and more things will cast correctly by implementing __nonzero__ (or __bool__ in Python 3), but they not implement __eq__ correctly for boolean types.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
In addition to Suspicious Dish's (thorough) answer, you can also get into trouble with and/or -- these are control flow operators, not Boolean operators.

People on the python-ideas mailing list have had trouble with assuming that and and or return True or False, and the solution is always "don't explicitly check against True/False and you'll be fine".

FoiledAgain
May 6, 2007

Lysidas posted:

In addition to Suspicious Dish's (thorough) answer, you can also get into trouble with and/or -- these are control flow operators, not Boolean operators.

Huh? But they're listed under the huge heading "Boolean Operations" in the official docs. (I'm not a super advanced programmer, so perhaps there's something more subtle lurking here.)

edit: I clicked on the the word and and it brought me to this section, which contains that extra subtlety I was wondering about. And also I see the title is technically "boolean operations" not "boolean operators".

FoiledAgain fucked around with this message at 22:47 on Mar 4, 2013

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Yikes, the "x is false" in that section is poorly worded. We don't really have a name for "bool(x)", though.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
This is quite instructive, too:

code:
Python 3.3.0 (default, Feb 21 2013, 15:17:17) 
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from dis import dis
>>> def and_(x, y):
...   return x and y
... 
>>> def or_(x, y):
...   return x or y
... 
>>> dis(and_)
  2           0 LOAD_FAST                0 (x) 
              3 JUMP_IF_FALSE_OR_POP     9 
              6 LOAD_FAST                1 (y) 
        >>    9 RETURN_VALUE         
>>> dis(or_)
  2           0 LOAD_FAST                0 (x) 
              3 JUMP_IF_TRUE_OR_POP      9 
              6 LOAD_FAST                1 (y) 
        >>    9 RETURN_VALUE

Wolfgang Pauli
Mar 26, 2008

One Three Seven
Is there a standard normal table anywhere that can take a Z-value and spit out a probability? Basically just a function call to one of these. And maybe one that will do the reverse. I'm sure it wouldn't be too hard just to put one in a .csv and read it, but if there's a library or module that contains one then it's probably worth learning.

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

Wolfgang Pauli posted:

Is there a standard normal table anywhere that can take a Z-value and spit out a probability? Basically just a function call to one of these. And maybe one that will do the reverse. I'm sure it wouldn't be too hard just to put one in a .csv and read it, but if there's a library or module that contains one then it's probably worth learning.

Yup, what you are looking for is called a cumulative distribution function. The so-called "z-value" is just giving you the value of the cdf at a given point about the distribution. scipy.stats probably has everything you'll need as far as that goes. The exact method you'll want is scipy.stats.norm.cdf(). I threw in a few Zs to test it out and it seems to default to a mean of 0 and and SD of 1, which is likely what you want. If you want the "Z-value" for any other kind of normal distribution, you will have to change this via the options loc and scale. I only briefly played with those parameters but they appear to set the average and standard deviation (also referred to as the width) of the normal distribution you are interested in.

http://docs.scipy.org/doc/scipy/reference/stats.html
http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html

accipter
Sep 12, 2003

Wolfgang Pauli posted:

Is there a standard normal table anywhere that can take a Z-value and spit out a probability? Basically just a function call to one of these. And maybe one that will do the reverse. I'm sure it wouldn't be too hard just to put one in a .csv and read it, but if there's a library or module that contains one then it's probably worth learning.

You probably want to use the continuous statistical distributions in scipy.

code:
In [8]: import scipy.stats

In [10]: scipy.stats.norm.cdf(1)
Out[10]: 0.84134474606854293

In [12]: scipy.stats.norm.ppf(0.84)
Out[12]: 0.99445788320975304

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES
Also, thanks very much to the very thorough explanations as to why I shouldn't check against True/False/None. The fact that the checks are already returning True/False is really what clicked with me. :)


------------


As an addendum to my previous post, the whole reason why we use Z is just a short hand way of talking about the probability of being that many standard deviations off the mean. Remember, in a normal distribution, ~68% of the values are ONE sigma within the mean, ~95% are within TWO sigma, and ~99.7% are within THREE sigma. So the Z-value tables are normalized to a function with mu = 0 and sd = 1 just so we can talk about it easily. There's really not much of a reason to use the arguments aside from laziness. If you know the size of the residual, you can use the table.

Wolfgang Pauli
Mar 26, 2008

One Three Seven
Isn't calling a CDF directly going to be way more computationally expensive than a call to a table? I'm looking for something I can use in real-time. I didn't just want to compute from the probability distribution itself because I figured it would send performance to poo poo.

*edit*
Pygame question: if I draw a polygon or circle primitive then that's still a Rect object, yes? I'm trying to find a way to do UI click detection for non-standard shapes (I'm overlaying these on a map). If I can draw a whatever-shaped polygon and use polygon.collidepoint() then that'd be really easy.

Wolfgang Pauli fucked around with this message at 19:08 on Mar 5, 2013

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

Wolfgang Pauli posted:

Isn't calling a CDF directly going to be way more computationally expensive than a call to a table? I'm looking for something I can use in real-time. I didn't just want to compute from the probability distribution itself because I figured it would send performance to poo poo.

Looking at the source for the method, it appears that's what it's doing. It maps it based on arguments, but it's looking it up. A lookup table is certainly going to be faster, especially if you want to devote your system resources to other things.

It makes sense too, because why constantly deal with computing the actual CDF? Gross. Just spit out the numbers for the numbers you have and provide good approximations if the user gives you something wonky.

Incidentally,
code:
In [128]: timeit.timeit('norm.cdf(1.2121)', 'from scipy.stats import norm', number=1000000)
Out[128]: 119.38415694236755

In [129]: 119.38415694236755/1e6
Out[129]: 0.00011938415694236756
So I don't have an inkling of how badly this would change when you're trying to run graphics too, but ~0.1 ms for each calculation.

onionradish
Jul 6, 2006

That's spicy.
A stupid post was here.

onionradish fucked around with this message at 20:39 on Mar 5, 2013

scissorman
Feb 7, 2011
Ramrod XTreme
How quick is creating a scipy KDTree?
I want to use it to implement a scene graph for 3D rendering but, since it can't be modified, you have to recreate it every time your data changes.

Alternatively, is it possible to modify the class to allow adding and removing points?

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

scissorman posted:

How quick is creating a scipy KDTree?
I want to use it to implement a scene graph for 3D rendering but, since it can't be modified, you have to recreate it every time your data changes.

Alternatively, is it possible to modify the class to allow adding and removing points?

I have a friend who does 3D modeling of Stars in (I think) Python. It'll take a few days to get an answer from him, but I bet that could work great for you.

Space Duck
Oct 15, 2003
Is there a way to reflect tables with Flask-SQLAlchemy? I'm at a dead end trying to adapt a small app to use Flask-SQLAlchemy in order to emit stuff from an exiting database to an internal webpage without having to have to redo a bunch of boilerplate stuff.

Flask 0.9
Flask-SQLAlchemy 0.16

Using straight SQLAlchemy, this works:

Python code:
engine = create_engine(DATABASE_URI)
session = scoped_session(sessionmaker(bind=engine, autoflush=False))
Base = declarative_base(bind=engine)


class Stuff(Base):
    __tablename__ = 'stuff'
    __table_args__ = {'autoload': True}
    stuffid = Column(Integer, primary_key=True)
I can query against that without any problems, and I can access all the columns in the Stuff table, it all works like you'd expect.

If I try to do the same using flask-sqlalchemy, the errors start:
code:
sqlalchemy.exc.UnboundExecutionError: No engine is bound to this Table's MetaData. Pass an engine to the Table via autoload_with=<someengine>,
or associate the MetaData with an engine via metadata.bind=<someengine>
If I drop
Python code:
__table_args__ = {'autoload': True}
from the class then it runs fine but I can only get the columns that I've defined for the class.

I've read in the docs that reflect() exists but it dies.
Python code:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_pyfile('config.cfg')
db = SQLAlchemy(app)
db.reflect()

TypeError: reflect() got an unexpected keyword argument 'tables'

QuarkJets
Sep 8, 2008

What's the general feel regarding Python 2 vs Python 3? None of the computers at the place where I work have Python 3 installed, and I know that it's not backwards compatible, so isn't every new Python 2 script just going to create problems in the future when Python 2 eventually gets abandoned? Python 3.x doesn't come with our redhat installs, and getting IT to install it for us would be a pain. Is this worth it?

I've been slowly ramping up my effort to get people in my workplace to switch from MATLAB to numpy/scipy, but if this is creating headaches for a Python 2.X to 3.X switchover in the future then I'd like to make the switch happen sooner rather than later

aeverous posted:

What do you guys use for your Python work, I'm currently using Notepad++ with the pyNPP plugin but earlier this year I used VS2010 for a C# project and gently caress if I didn't get really spoiled by the code completion. I've looked around at Python IDEs and they all look a bit crap except PyCharm which is pretty expensive. Are there any free/OSS Python IDEs with really solid code completion and a built in dark theme?

Vim

Although recently I tried Spyder 2 on my Windows box (comes with the Pythonxy package) and it worked really really great, so I may start using that more.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Python 3 doesn't really improve that much to cut the heartache.

Nippashish
Nov 2, 2005

Let me see you dance!

QuarkJets posted:

I've been slowly ramping up my effort to get people in my workplace to switch from MATLAB to numpy/scipy, but if this is creating headaches for a Python 2.X to 3.X switchover in the future then I'd like to make the switch happen sooner rather than later

Basically everyone doing numeric work in python is using 2.7 and will continue to do so for the foreseeable future.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
I use Python 3 for everything. Everything that's worth using it in my line of work has great support for it: numpy, scipy, matplotlib, biopython, networkx, ipython, etc.

Modern Pragmatist
Aug 20, 2008
In my experience, 2to3 works pretty well for converting python2 code to be compatible with python3. The biggest hurdle is the bytes/str/unicode change, but as long as you don't do much work with strings it should be pretty painless to migrate.

Also, as far as a Matlab replacement, I'm pretty sure most projects are now python3 compatible.

The Gripper
Sep 14, 2004
i am winner
I spent an hour or so hunting an irritating bug down and I'm still not entirely sure *why* it's a problem:

With this code:
Python code:
mydict = {}
mydict['penis'] = "boner"
 
def thing_one():
	for k,v in mydict.items():
		print "%s %s" % (k,v)
 

def thing_two():
	for k,v in mydict.items():
		print "%s %s" % (k,v)
	mydict = {}
calling thing_one() is fine, but calling thing_two() throws an UnboundLocalError:
Python code:
>>> thing_one()
penis boner
>>> thing_two()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in thing_two
UnboundLocalError: local variable 'mydict' referenced before assignment
Checking the bytecode for it, thing_two() generates a LOAD_FAST for mydict rather than a LOAD_GLOBAL, seemingly as a result of mydict being overwritten by a new empty dict at the end of the function.

Replacing it with mydict.clear() resolved the problem and is how it should have been done in the first place, but I'm still interested in what's actually going on here and whether it's some weird property of dictionaries/references that I haven't heard about. The error was obtuse enough that had I not known how to work with python bytecode I probably wouldn't have found the solution yet.

Anyone have any ideas?

Emacs Headroom
Aug 2, 2003

The Gripper posted:

Anyone have any ideas?

I think it's because in the first case, the interpreter hunts for mydict, doesn't find it in local scope and so goes up a level to global, finds it, and runs fine. In the second case, the interpreter finds a mydict in local scope, but it's not assigned before you refer to it, so it throws up an error. In general if you want to use a global variable, you should mark it global at the beginning of the local scope where you're going to use it.

Python code:
def thing_two():
    global mydict
    for k,v in mydict.items():
        print "%s %s" % (k,v)
    mydict = {}

The Gripper
Sep 14, 2004
i am winner

Emacs Headroom posted:

I think it's because in the first case, the interpreter hunts for mydict, doesn't find it in local scope and so goes up a level to global, finds it, and runs fine. In the second case, the interpreter finds a mydict in local scope, but it's not assigned before you refer to it, so it throws up an error. In general if you want to use a global variable, you should mark it global at the beginning of the local scope where you're going to use it.
That's the only thing I could think of, though it seemed silly for it to search the entire scope that way. I guess it's because of the way dicts work, initializing with var = {} creates a completely new dict rather than replacing the old one in-place. So it works on the assumption that mydict = {} is creating a new variable mydict rather than modifying the existing one, which it then assumes means you're making a new local variable, or something like that?

edit; I guess it makes sense and it's even in the Python FAQ, I don't know how I haven't come across it before.

The Gripper fucked around with this message at 16:10 on Mar 7, 2013

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...
A wide ranging query about Python web development.

Years ago, I made a website for a laboratory I was working with. It incorporated access to a database, with record browsing, tools for search and visualization in a number of ways. It also functioned as a CMS for various groups that used the database or were involved in lab activities, being somewhere they put reference documents, notices and so on. There was the added complication that some of the website was open to the public, and some only for members of particular groups. I did the site up in Plone. NEVER DO THIS.

Anyway, to my surprise, the thing has worked fine for 5 years, with next to no maintenance or attention. Now, I'm between jobs and my old colleagues asked me if I can update the site. Which brings me to the main question: what framework should I use? Plone is out of the question. By default I thought of Django (which I have a little experience in), but I'm unsure if the mix of record browsing and content would sit well. The task is a bit too involved for the various microframeworks. Opinions? I want to work in Python because that's my environment of choice and I got a heap of code from last time that I can reuse.

DARPA
Apr 24, 2005
We know what happens to people who stay in the middle of the road. They get run over.

The Gripper posted:

Python code:
mydict = {}
mydict['penis'] = "boner"
 
def thing_one():
	for k,v in mydict.items():
		print "%s %s" % (k,v)
 

def thing_two():
	for k,v in mydict.items():
		print "%s %s" % (k,v)
	mydict = {}
Anyone have any ideas?

You need to declare global mydict if you want to rebind it in the local scope. http://docs.python.org/2/reference/simple_stmts.html#global

mydict = {} tries to create a new dictionary object and assign it to mydict. This breaks because python doesn't know if you want to bind the object to a new local or assign to the global variable.

mydict.clear() works because you're accessing the existing dictionary object and calling a method on it.

This will fix your code.
Python code:
def thing_two():
	global mydict # Now you can rebind the global variable mydict in the local scope.
	for k,v in mydict.items():
		print "%s %s" % (k,v)
	mydict = {}

DARPA fucked around with this message at 17:50 on Mar 7, 2013

standardtoaster
May 22, 2009

Wildtortilla posted:

I'm currently taking PSU's Certification in Geographic Information Systems (aka, intelligently using ArcMAP). In May I'll be starting my final course for the certificate and I have a huge array of options, but I'm leaning towards their course in Python. From looking at job postings for GIS positions, I'd wager at least 50% of postings include knowing Python as a desirable skill. However, coming from a background in geology, I have no experience with coding; would the links in the OP be a good place for me to start or should I start elsewhere since I have no experience? The first link in the tutorials "MIT Introduction to Computer Science and Programming" and the contents of this post seem like they'd be a good start for me. Any suggestions?

Get out of my industry and go back to the field! But yeah, the mit edx course and text book is very good, definitely take arcpy course if it's offered, programming and scripting for esri products is in high demand. Just don't get shoehorned into a computer janitor job, your skill is geospatial analysis.

Then again, model builder will do anything you would want to script anyway, if you're interested in programming take the python course.

The biggest skill set should be database design and management, I would say that's more important than python.

standardtoaster fucked around with this message at 17:58 on Mar 7, 2013

BigRedDot
Mar 6, 2008

DARPA posted:

You need to declare global mydict if you want to rebind it in the local scope.
However let us not forget the caveat: you probably don't want to

Space Duck
Oct 15, 2003
After spending the night away from it, I've managed to solve my own problem.

I needed to add db.metadata.reflect(db.get_engine(app)) and then redefine all my models like so:
Python code:
class Things(db.Model):
    __tablename__ = 'things'
    __table_args__ = {'extend_existing': True}

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

JetsGuy posted:

I have a friend who does 3D modeling of Stars in (I think) Python. It'll take a few days to get an answer from him, but I bet that could work great for you.

So that buddy of mine got back to me. While he does indeed use python for some tasks, the 3D simulation / modeling he does is in FORTRAN90. Sorry if I got your hopes up.

scissorman
Feb 7, 2011
Ramrod XTreme

JetsGuy posted:

So that buddy of mine got back to me. While he does indeed use python for some tasks, the 3D simulation / modeling he does is in FORTRAN90. Sorry if I got your hopes up.

Thank you for asking.
I'll probably use KDTree for static geometry like terrain and find some other solution for dynamic objects.

QuarkJets
Sep 8, 2008

Thanks for the feedback, guys

Modern Pragmatist posted:

In my experience, 2to3 works pretty well for converting python2 code to be compatible with python3. The biggest hurdle is the bytes/str/unicode change, but as long as you don't do much work with strings it should be pretty painless to migrate.

Also, as far as a Matlab replacement, I'm pretty sure most projects are now python3 compatible.

That's good news; it sounds like I don't need to worry about this too much and can just make a casual python3 software request without banging on doors

geera
May 20, 2003

outlier posted:

A wide ranging query about Python web development.

Years ago, I made a website for a laboratory I was working with. It incorporated access to a database, with record browsing, tools for search and visualization in a number of ways. It also functioned as a CMS for various groups that used the database or were involved in lab activities, being somewhere they put reference documents, notices and so on. There was the added complication that some of the website was open to the public, and some only for members of particular groups. I did the site up in Plone. NEVER DO THIS.

Anyway, to my surprise, the thing has worked fine for 5 years, with next to no maintenance or attention. Now, I'm between jobs and my old colleagues asked me if I can update the site. Which brings me to the main question: what framework should I use? Plone is out of the question. By default I thought of Django (which I have a little experience in), but I'm unsure if the mix of record browsing and content would sit well. The task is a bit too involved for the various microframeworks. Opinions? I want to work in Python because that's my environment of choice and I got a heap of code from last time that I can reuse.
Django really is going to be the best answer here. The admin area alone is going to save you a ton of work when it comes to adding the record browsing and search that you had in your old site.

DoggesAndCattes
Aug 2, 2007

Hi. Newbie python programmer that needs a little direction or help. I'm trying to convert each letter in a string where each letter in the alphabet correspond to an alternating letter in a key.

What I'm thinking is to convert the string into a list, find out where each letter in the list of the string corresponds to a position in the alphabet, take that position and use it to find the corresponding letter in the key, do that for the entire list of the string, and then convert that back into a string.

Here is my code if anyone wants to help


code:
alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
key = list("ZYXWVUTSRQPONMLKJIHGFEDCBA")
##key can be any random assortment of letters

answer = raw_input ("ok: ")
answer = answer.replace (" ","")
answer = answer.upper()
answerlength = len(answer)
answercounter = 0

##I don't think I'm going to use the loop. 
##I was thinking that the loop would continue until every letter would be changed, 
##but then I thought that it would probably just keep changing the letters back and forth, 
##or maybe individually in some sporadic order. I don't know. I think the best way would be to 
##change every letter at once and correctly to the corresponding key. 
##I just don't know how to do it.
if answercounter != answerlength:
   answerlist = list(answer)
   print answerlist
   ??????
   print "".join(answerlist)

Jewel
May 2, 2009

Mad Pino Rage posted:

Hi. Newbie python programmer that needs a little direction or help. I'm trying to convert each letter in a string where each letter in the alphabet correspond to an alternating letter in a key.

What I'm thinking is to convert the string into a list, find out where each letter in the list of the string corresponds to a position in the alphabet, take that position and use it to find the corresponding letter in the key, do that for the entire list of the string, and then convert that back into a string.

Here is my code if anyone wants to help


code:
alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
key = list("ZYXWVUTSRQPONMLKJIHGFEDCBA")
##key can be any random assortment of letters

answer = raw_input ("ok: ")
answer = answer.replace (" ","")
answer = answer.upper()
answerlength = len(answer)
answercounter = 0

##I don't think I'm going to use the loop. 
##I was thinking that the loop would continue until every letter would be changed, 
##but then I thought that it would probably just keep changing the letters back and forth, 
##or maybe individually in some sporadic order. I don't know. I think the best way would be to 
##change every letter at once and correctly to the corresponding key. 
##I just don't know how to do it.
if answercounter != answerlength:
   answerlist = list(answer)
   print answerlist
   ??????
   print "".join(answerlist)

No idea if python optimizes the lambda to create variables first then use later or if it recreates the dict every call, but this is what I'd do:

Python code:
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
string = "TESTING"
print map(lambda t:dict(zip(alphabet, key))[t], string)
And the output is: ['G', 'V', 'H', 'G', 'R', 'M', 'T']
Or if you call print ''.join(<map>) instead: 'GVHGRMT'

If you wanna really be sure, or to expand it way out for readability:

Python code:
>>> alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
>>> key = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
>>> string = "TESTING"
>>> zipped = dict(zip(alphabet, key))
>>> zipped
{'A': 'Z', 'C': 'X', 'B': 'Y', 'E': 'V', 'D': 'W', 'G': 'T', 'F': 'U', 'I': 'R', 'H': 'S', 'K': 'P', 'J': 'Q', 'M': 'N', 'L': 'O', 'O': 'L', 'N': 'M', 'Q': 'J', 'P': 'K', 'S': 'H', 'R': 'I', 'U': 'F', 'T': 'G', 'W': 'D', 'V': 'E', 'Y': 'B', 'X': 'C', 'Z': 'A'}
>>> print ''.join(map(lambda t:zipped[t], string))
GVHGRMT

DoggesAndCattes
Aug 2, 2007

Jewel posted:


print map(lambda t:dict(zip(alphabet, key))[t], string)[/code]


Thank you for help. Just to be clear that I'm understanding the code.

zip is a function that creates a list of tuples for each value of alphabet that corresponds to key
Dictionary makes a key-value pair(not fully too sure understanding this)
But I'm not familiar with lambda or how that all works exactly together, and so far it looks like another way to make a function.

EDIT
Well, tutorials and documentation isn't making it all clear, but I broke it down and ran it to see what it exactly did.
Zip made everything into [('A','Z'),('B','Y'),....] tuples
Dictionary made the tuples into key-value pairs in a list ['A':'Z'....]

But calling lambda outputs "function lambda at 0x033E95B0" ????


Map runs lambda as a function or procedure for every iteration for input say I typed in 'apple' and it would come out at this point as ['Z','G','G','E','P']

and the ''.join combined the list into a string
and then I assigned that to a variable and made it available outside the function

DoggesAndCattes fucked around with this message at 04:46 on Mar 9, 2013

Jewel
May 2, 2009

Mad Pino Rage posted:

Thank you for help. Just to be clear that I'm understanding the code.

zip is a function that creates a list of tuples for each value of alphabet that corresponds to key
Dictionary makes a key-value pair(not fully too sure understanding this)
But I'm not familiar with lambda or how that all works exactly together, and so far it looks like another way to make a function.

Yes!

Python code:
>>> z = zip("ABC", 123)
>>> z
[('A', '1'), ('B', '2'), ('C', '3')]

d = dict(z)
>>> d
{'A': '1', 'C': '3', 'B': '2'}
Lambda is kinda another way to make a function, yeah. It was talked about previously in the General Programming thread: http://forums.somethingawful.com/showthread.php?threadid=2779598&pagenumber=236&perpage=40#post410410495

But you can just as easily do:

Python code:
>>> def zipKey(t):
	return zipped[t]

>>> print ''.join(map(zipKey, string))
GVHGRMT

Adbot
ADBOT LOVES YOU

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Jewel posted:

No idea if python optimizes the lambda to create variables first then use later or if it recreates the dict every call, but this is what I'd do:

It will call the dict function on every call of the lambda, since it doesn't know that the dict call is the same as it is now, as the global may have changed.

Just do this:

Python code:
trans = dict(zip(alphabet, key))
print ''.join(trans[t] for t in string]

  • Locked thread