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
Master_Odin
Apr 15, 2010

My spear never misses its mark...

ladies

dantheman650 posted:

Thanks for this! I like the Udacity layout better than Coursera and I enjoy the ability to study at my own pace. The first lesson is making a poker program, which, coincidentally, is one of the last exercises in Think Python, so that seems like a good sign this will be appropriate for my level. I'll give it a go.


This is what I was trying to do but I couldn't think of any great ideas. I tend to learn better when there's a directed goal someone else creates for me, but after I finish this course it seems like working on my own projects will be the best way to get better. Thanks!
Something like CheckIO might be up your alley

Adbot
ADBOT LOVES YOU

caberham
Mar 18, 2009

by Smythe
Grimey Drawer
Hey guys, just a short question thanks

Any has anyone here worked with Django and made Open ERP or Odoo modules? The Django thread seems super technical so I rather post here. How hard is it working with 3rd party API's for "basic" functionality? Signed up for coursera "An Introduction to Interactive Programming in Python (Part 1)" course. Hopefully I can stick to the end and get something out of it.

dantheman650 posted:

I was actually just coming to this thread to say thank you to the posters several months ago who recommended this book. I slowly worked my way through it in my free time and finished it today. The exercises were supremely helpful and well-designed and I feel like I understand Python basics extremely well.

As a self-taught Python learner, where do I go next? I find that the readily available resources are either targeted toward beginners or experts. There isn't much I can find targeted toward intermediate learners. My goal is to become proficient enough at coding to make it a marketable skill.

I am enrolled an and currently taking one of the only Coursera Python courses, which is aimed at complete beginners and quite boring. The others I could find are either significantly above my level or also for complete beginners.

Hey coursera buddy. I'm still super beginner and have a basic grasp of objects and javascript. If you ever want someone slightly behind your level or work something let's do it. Maybe we can do django together and work on github.

BigRedDot
Mar 6, 2008

Hey time for more Bokeh!

Here's a little video of a new example, there's more on the blog announcement.

https://www.youtube.com/watch?v=F0jXmtvmpHY

Big news is R language bindings, for anyone that might also use R.

Cingulate
Oct 23, 2012

by Fluffdaddy
I did conda update --all on my iMac and it's been doing this

quote:

Fetching package metadata: ..
Solving package specifications: ..
Error: Unsatisfiable package specifications.
Generating hint:
WARNING: This could take a while. Type Ctrl-C to exit.
[47796/341376 ] |############ | 14%
for a few days now.

Could take a while indeed.

Gothmog1065
May 14, 2009
Hey guys, I'm relearning python, and doing it via code academy. I'm trying to be dumb and do things a step above, and I suppose make it.. different? Dunno, trying things, but I can't remember if I can do a for loop like this:

code:
def get_average(student):
    l = ["homework", "quizzes", "tests"]
    count = 0
    weight = [.1, .3, .6]
    for item in l: 
        item = student[item]
        item_average = average(item)
        item_weighted = item_average * weight[count]
        
    return homework_weighted + quizzes_weighted + tests_weighted
I seem to recall a way to set the variable names within the for loop, so instead of item_weighted = foo, it actually comes out as homework_weighted = foo. Am I dumb and this can't be done?

also, is there a way to call which step you are in on a for loop?

Space Kablooey
May 6, 2009


Gothmog1065 posted:

Hey guys, I'm relearning python, and doing it via code academy. I'm trying to be dumb and do things a step above, and I suppose make it.. different? Dunno, trying things, but I can't remember if I can do a for loop like this:

I seem to recall a way to set the variable names within the for loop, so instead of item_weighted = foo, it actually comes out as homework_weighted = foo. Am I dumb and this can't be done?

Do you mean this?

Python code:
things = ["homework", "quizzes", "tests"]
weights = [.1, .3, .6]
for thing, weight in zip(things, weights):
    print thing, weight
it prints

code:
homework 0.1
quizzes 0.3
tests 0.6
EDIT: As SurgicalOntologist said below, it's better to use a dictionary. I completely forgot. :eng99:

Space Kablooey fucked around with this message at 17:10 on Feb 18, 2015

SurgicalOntologist
Jun 17, 2004

Gothmog1065 posted:

Hey guys, I'm relearning python, and doing it via code academy. I'm trying to be dumb and do things a step above, and I suppose make it.. different? Dunno, trying things, but I can't remember if I can do a for loop like this:

code:
def get_average(student):
    l = ["homework", "quizzes", "tests"]
    count = 0
    weight = [.1, .3, .6]
    for item in l: 
        item = student[item]
        item_average = average(item)
        item_weighted = item_average * weight[count]
        
    return homework_weighted + quizzes_weighted + tests_weighted
I seem to recall a way to set the variable names within the for loop, so instead of item_weighted = foo, it actually comes out as homework_weighted = foo. Am I dumb and this can't be done?

also, is there a way to call which step you are in on a for loop?

You never want to set your variable names programmatically. If you're tempted to do so, a dictionary might be what you're looking for. So it would be weighted_score[item] = foo which would "come out as" weighted_score['homework'] = foo.

Gothmog1065
May 14, 2009

HardDisk posted:

Do you mean this?

Python code:
things = ["homework", "quizzes", "tests"]
weights = [.1, .3, .6]
for thing, weight in zip(things, weights):
    print thing, weight
it prints

code:
homework 0.1
quizzes 0.3
tests 0.6

Thanks! I ended up with:

code:
def get_average(student):
    grades = ["homework", "quizzes", "tests"]
    total = 0
    weights = [.1, .3, .6]
    for grade, weight in zip(grades,weights): 
        item = student[grade]
        item_average = average(item)
        item_weighted = item_average * weight
        total = total + item_weighted
                
    return total
Though, I suppose I could have done weights as a dictionary (weights = {"homework" : .1, "quizzes" : .3, "tests" : .6}) and looped over that (for weight in weights:), which is probably way more than they were asking for regardless.


SurgicalOntologist posted:

You never want to set your variable names programmatically. If you're tempted to do so, a dictionary might be what you're looking for. So it would be weighted_score[item] = foo which would "come out as" weighted_score['homework'] = foo.

Duly noted.

Dominoes
Sep 20, 2007

Putting it all together:
Python code:
weights = {"homework" :  .1, "quizzes" : .3, "tests" : .6}

def get_average(student):
    return sum(student[item] * weight for item, weight in weights.items())

Hughmoris
Apr 21, 2007
Let's go to the abyss!
Can anyone recommend some reading/reference material for learning Flask?

Space Kablooey
May 6, 2009


I started with the mega-tutorial.

I'm also working with it for almost two years now, if you hit a snag I can probably help you.

PongAtari
May 9, 2003
Hurry, hurry, hurry, try my rice and curry.
I'm guessing this is more of a Python question than a SQL question, so here goes:

For an assignment (on Udacity - create a Swiss-style tournament database), I need to create a function that will return a list of tuples, each of which contains (id, name, wins, matches) from a PostgreSQL database. No problem there, but I'm getting tuples like:

(420, 'Dick Butt', None, None)

I'm only supposed to insert the player's name (ID is generated by SQL) when I create a new player - inserting "0"s for their wins and matches is cheating. The function that tests my function wants "0"s in the wins and matches:

code:
    [(id1, name1, wins1, matches1), (id2, name2, wins2, matches2)] = standings
    if matches1 != 0 or matches2 != 0 or wins1 != 0 or wins2 != 0:
        raise ValueError(
            "Newly registered players should have no matches or wins.")
Since I'm getting None (null) values from my database instead of 0s, I get the error message. I guess I could write some code that would take the tuples from the SQL query, create new tuples with "0"s instead of "None"s, and reinsert them into the standings list... but is there a more graceful way to do this?


caberham posted:

Signed up for coursera "An Introduction to Interactive Programming in Python (Part 1)" course.

I'm in this course too :sissies:. Check out my CEE-LO dice game in the Hall of Fame discussion board!

supercrooky
Sep 12, 2006

PongAtari posted:

I'm guessing this is more of a Python question than a SQL question, so here goes:

For an assignment (on Udacity - create a Swiss-style tournament database), I need to create a function that will return a list of tuples, each of which contains (id, name, wins, matches) from a PostgreSQL database. No problem there, but I'm getting tuples like:

(420, 'Dick Butt', None, None)

I'm only supposed to insert the player's name (ID is generated by SQL) when I create a new player - inserting "0"s for their wins and matches is cheating. The function that tests my function wants "0"s in the wins and matches:

code:
    [(id1, name1, wins1, matches1), (id2, name2, wins2, matches2)] = standings
    if matches1 != 0 or matches2 != 0 or wins1 != 0 or wins2 != 0:
        raise ValueError(
            "Newly registered players should have no matches or wins.")
Since I'm getting None (null) values from my database instead of 0s, I get the error message. I guess I could write some code that would take the tuples from the SQL query, create new tuples with "0"s instead of "None"s, and reinsert them into the standings list... but is there a more graceful way to do this?


The most graceful way to do this is in the database layer, by setting default values of 0 for both your wins and matches columns. Then your queries could return zeros without technically breaking "insert only the players name" rule.

PongAtari
May 9, 2003
Hurry, hurry, hurry, try my rice and curry.

supercrooky posted:

The most graceful way to do this is in the database layer, by setting default values of 0 for both your wins and matches columns. Then your queries could return zeros without technically breaking "insert only the players name" rule.

Thanks, I'll give that a shot.

caberham
Mar 18, 2009

by Smythe
Grimey Drawer

PongAtari posted:

I'm guessing this is more of a Python question than a SQL question, so here goes:

For an assignment (on Udacity - create a Swiss-style tournament database), I need to create a function that will return a list of tuples, each of which contains (id, name, wins, matches) from a PostgreSQL database. No problem there, but I'm getting tuples like:

(420, 'Dick Butt', None, None)

I'm only supposed to insert the player's name (ID is generated by SQL) when I create a new player - inserting "0"s for their wins and matches is cheating. The function that tests my function wants "0"s in the wins and matches:

code:
    [(id1, name1, wins1, matches1), (id2, name2, wins2, matches2)] = standings
    if matches1 != 0 or matches2 != 0 or wins1 != 0 or wins2 != 0:
        raise ValueError(
            "Newly registered players should have no matches or wins.")
Since I'm getting None (null) values from my database instead of 0s, I get the error message. I guess I could write some code that would take the tuples from the SQL query, create new tuples with "0"s instead of "None"s, and reinsert them into the standings list... but is there a more graceful way to do this?


I'm in this course too :sissies:. Check out my CEE-LO dice game in the Hall of Fame discussion board!

Oh wow, that's you! That's awesome. I'm going to make something next weekend. Maybe we should have our goon newbies group or something and make projects of goatse

Master_Odin
Apr 15, 2010

My spear never misses its mark...

ladies

PongAtari posted:

I'm guessing this is more of a Python question than a SQL question, so here goes:

For an assignment (on Udacity - create a Swiss-style tournament database), I need to create a function that will return a list of tuples, each of which contains (id, name, wins, matches) from a PostgreSQL database. No problem there, but I'm getting tuples like:

(420, 'Dick Butt', None, None)

I'm only supposed to insert the player's name (ID is generated by SQL) when I create a new player - inserting "0"s for their wins and matches is cheating. The function that tests my function wants "0"s in the wins and matches:

code:
    [(id1, name1, wins1, matches1), (id2, name2, wins2, matches2)] = standings
    if matches1 != 0 or matches2 != 0 or wins1 != 0 or wins2 != 0:
        raise ValueError(
            "Newly registered players should have no matches or wins.")
Since I'm getting None (null) values from my database instead of 0s, I get the error message. I guess I could write some code that would take the tuples from the SQL query, create new tuples with "0"s instead of "None"s, and reinsert them into the standings list... but is there a more graceful way to do this?
The proper way would be as supercrooky pointed out would be to set a default on the field to 0 such that it auto defaults to 0 on insertion when only inserting player name.

Alternatively, if you're forced to work with a database design that is dumb, you could do something like this in your SQL query:
code:
SELECT player_id, player_name, case when player_wins is null then 0 else player_wins end, 
case when player_draws is null then 0 else player_draws end  FROM players
Assuming table is "players" and fields are (player_id,player_name, player_wins,player_draws). But this is a dumb query that should be avoided by less dumb DB setups.

sc0tty
Jan 8, 2005

too kewell for school..
I am currently in the process of learning Python for data analysis. I am using wakari (https://www.wakari.io), and am currently working through a bunch of basic data transformation tasks to get my head around things.

My background is SAS and SQL so I am finding data transformation in Python to be EXTREMELY difficult and frustrating. I am sure that once I get the hang of things I will wiz through this stuff however for whatever reason my dumb brain cannot figure out basic concatenation to derive new columns.

If I had a dataframe with the following columns,

model, productID, productname, sales
2010, 1101, widget, 43
2010, 1102, gidget, 12

How do I create a new column in the dataframe that

a. Combines model and productID into a new column
b. Combines productname and sales into a new column

(I realise these are dumb examples but they capture the casting, new columns, and concatenation problems they are having)

model, productID, productname, sales, newcolA, newcolB
2010, 1101, widget, 43, 20101101, widget43
2010, 1102, gidget, 12, 20101102, gidget12

I am using Panda for other data transformation tasks but as a COMPLETE python newbie I am stumped. I've worked through different examples which use series or variables, that involve casting int to string using different methods but I can't seem to bring it all together and make it happen inside a dataframe.

I keep just wanting to rush back to SAS but I know that if I stick with it I won't look back. Help!

JawnV6
Jul 4, 2004

So hot ...
I'm trying to decide how to get a complex blob from one python script to another.

I have a few different scripts. One's a polling loop waiting for instructions from a remote computer, one's a graphics driver that can take some time to update the screen. The loop calls the driver with subprocess.open() to avoid blocking. The driver currently takes args as one complete command, e.g. "./driver.py Text 15 50 'Hello!' " puts the string Hello! at x=15,y=50.

I want to send more than one update to the driver at a time and I'm not sure how to package them up. I'd love to just have a list of lists, keep the current internal structure and loop over it multiple times. But I'm not sure how to send a list of lists in the command line arguments. I'm considering a flat file that keeps each current command on its own line. It's stupid and slow, but I can afford slow and I'm not going to get any smarter.

Is there some easier way or is the file system the easiest way to smuggle this data around?

e: smuggling throuhg filesystem worked, back to the terrible implementation at hand

JawnV6 fucked around with this message at 01:23 on Feb 20, 2015

SurgicalOntologist
Jun 17, 2004

sc0tty posted:

I am currently in the process of learning Python for data analysis. I am using wakari (https://www.wakari.io), and am currently working through a bunch of basic data transformation tasks to get my head around things.

My background is SAS and SQL so I am finding data transformation in Python to be EXTREMELY difficult and frustrating. I am sure that once I get the hang of things I will wiz through this stuff however for whatever reason my dumb brain cannot figure out basic concatenation to derive new columns.

If I had a dataframe with the following columns,

model, productID, productname, sales
2010, 1101, widget, 43
2010, 1102, gidget, 12

How do I create a new column in the dataframe that

a. Combines model and productID into a new column
b. Combines productname and sales into a new column

(I realise these are dumb examples but they capture the casting, new columns, and concatenation problems they are having)

model, productID, productname, sales, newcolA, newcolB
2010, 1101, widget, 43, 20101101, widget43
2010, 1102, gidget, 12, 20101102, gidget12

I am using Panda for other data transformation tasks but as a COMPLETE python newbie I am stumped. I've worked through different examples which use series or variables, that involve casting int to string using different methods but I can't seem to bring it all together and make it happen inside a dataframe.

I keep just wanting to rush back to SAS but I know that if I stick with it I won't look back. Help!

If those columns are strings, you can just add them. If not, you need to make them strings, then add them (in Python addition for strings is concatenation; in pandas it will automatically apply the addition operation to the whole column).

Python code:
df['newcolA'] = df['model'].map(str) + df['productID'].map(str)
df['newcolB'] = df['productname'] + df['sales'].map(str)
The map method is "apply the given function to every element" so df['model'].map(str) returns a new column (temporary; it's not inserted unless you do so explicitly) of strings rather than ints.

SurgicalOntologist fucked around with this message at 21:42 on Feb 19, 2015

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

JawnV6 posted:

I'm trying to decide how to get a complex blob from one python script to another.

I have a few different scripts. One's a polling loop waiting for instructions from a remote computer, one's a graphics driver that can take some time to update the screen. The loop calls the driver with subprocess.open() to avoid blocking. The driver currently takes args as one complete command, e.g. "./driver.py Text 15 50 'Hello!' " puts the string Hello! at x=15,y=50.

I want to send more than one update to the driver at a time and I'm not sure how to package them up. I'd love to just have a list of lists, keep the current internal structure and loop over it multiple times. But I'm not sure how to send a list of lists in the command line arguments. I'm considering a flat file that keeps each current command on its own line. It's stupid and slow, but I can afford slow and I'm not going to get any smarter.

Is there some easier way or is the file system the easiest way to smuggle this data around?

e: smuggling throuhg filesystem worked, back to the terrible implementation at hand

I'm not quite picturing what you're doing, but could you just send JSON as a command line argument in your subprocess call?

supercrooky
Sep 12, 2006

Master_Odin posted:

The proper way would be as supercrooky pointed out would be to set a default on the field to 0 such that it auto defaults to 0 on insertion when only inserting player name.

Alternatively, if you're forced to work with a database design that is dumb, you could do something like this in your SQL query:
code:
SELECT player_id, player_name, case when player_wins is null then 0 else player_wins end, 
case when player_draws is null then 0 else player_draws end  FROM players
Assuming table is "players" and fields are (player_id,player_name, player_wins,player_draws). But this is a dumb query that should be avoided by less dumb DB setups.

This can also be
code:
SELECT player_id, player_name, COALESCE(player_wins, 0), COALESCE(player_draws, 0)

Liam Emsa
Aug 21, 2014

Oh, god. I think I'm falling.
nm

Liam Emsa fucked around with this message at 06:16 on Feb 20, 2015

KICK BAMA KICK
Mar 2, 2009

Ah, see you caught it but just a few tips of style: don't explicitly compare booleans to True or False -- while leaver == True: should just be while leaver:; you can simplify those numerical comparisons like f >= 0.25 and f < 0.50: to 0.25 <= f < 0.5; and that chain of those exclusive conditions should be of the form if... elif... else rather than if... if... if....

Literally Elvis
Oct 21, 2013

I have an assignment for a job I'm trying to get that requires I parse 20 books' titles, authors, weight, etc. from some saved files, pack boxes based on the weight, and spit out the box arrangements in JSON format. The README specifically says "submissions with only a single class are not worthy", so I've got classes for Books, Boxes, and the Shipment. I'm having trouble figuring out a good way to get each object's __repr__ working properly so I can print the Shipment at the end. Is there any sage wisdom on accomplishing this? The code is currently roughly like this:

Python code:
class Book:
    def __init__(self, title, author, price, isbn, weight, ship_weight):
        self.title = title
        self.author = author
        self.price = price
        self.isbn = isbn
        self.weight = weight
        self.shipping_weight = ship_weight

    def __repr__(self):
        return json.dumps(self.__dict__, indent=4)


class Box:
    def __init__(self, id, books):
        self.id = id
        self.contents = [book for book in books]
        self.total_weight = sum(book.weight for book in books)

    def __repr__(self):
        return json.dumps(self.__dict__, indent=4)


class Shipment:
    def __init__(self):
        self.boxes = []
        self.box_id = 0

    # boxes are created in an inner function and then added to the shipment here

    def __repr__(self):
        return json.dumps(self.__dict__, indent=4)

Haystack
Jan 23, 2005





Try looking into what jsonpickle does.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What do I do with my requirements.txt and setup.py if I want to support both Python 2 and 3, with different dependencies depending on what version you're using. i.e. I need unicodecsv for Python 2, but not for Python 3.

edit: Nevermind I think I found a good example of how to do this: https://github.com/aws/aws-cli

Hughmoris
Apr 21, 2007
Let's go to the abyss!
Is there a reliable way in python to search for a string directly in a pdf? I have script that loses a lot of time because it is having to convert a 60 page pdf to text file, then search for its information.

accipter
Sep 12, 2003

Hughmoris posted:

Is there a reliable way in python to search for a string directly in a pdf? I have script that loses a lot of time because it is having to convert a 60 page pdf to text file, then search for its information.

Are these PDF files that have already been OCR'ed or have text information?

Hughmoris
Apr 21, 2007
Let's go to the abyss!

accipter posted:

Are these PDF files that have already been OCR'ed or have text information?

To be honest, I'm not sure I know the answer. How could I check? Using pdf2txt, it converts everything I need to a text file just fine. I don't know if that means I can assume the PDF files have text information. I tried using pdfminer before to search directly in pdf but I got all turned around, had a whole bunch of objects I didn't know how to manipulate.

JawnV6
Jul 4, 2004

So hot ...

Thermopyle posted:

I'm not quite picturing what you're doing, but could you just send JSON as a command line argument in your subprocess call?

That would've worked, yes. I was sweating a demo that happened a couple hours ago, turns out they hadn't seen it do the wireless bits yet so I really shouldn't have been worried at all.

I might move to JSON, depending on how much more this has to grow. There's enough issues with the relevant display technology that I might not have time to drill down into it.

Hughmoris posted:

Is there a reliable way in python to search for a string directly in a pdf? I have script that loses a lot of time because it is having to convert a 60 page pdf to text file, then search for its information.
Figure out what you can cache. If this is the same as the general thread and you're chewing through the 60 pages to figure out record/page number translations, do the pdf2txt once and either store that out in a text format or keep it in memory. Check the file handle against your cached version's timestamp to see if you need to re-read it for new information.

Hughmoris
Apr 21, 2007
Let's go to the abyss!

JawnV6 posted:

That would've worked, yes. I was sweating a demo that happened a couple hours ago, turns out they hadn't seen it do the wireless bits yet so I really shouldn't have been worried at all.

I might move to JSON, depending on how much more this has to grow. There's enough issues with the relevant display technology that I might not have time to drill down into it.

Figure out what you can cache. If this is the same as the general thread and you're chewing through the 60 pages to figure out record/page number translations, do the pdf2txt once and either store that out in a text format or keep it in memory. Check the file handle against your cached version's timestamp to see if you need to re-read it for new information.

I think I'll figure out how to post my code on github, maybe someone might see a glaring problem that is slowing things down.

JawnV6
Jul 4, 2004

So hot ...
If you're using pdf2txt from here, it mentions:

quote:

PDFMiner is about 20 times slower than other C/C++-based counterparts such as XPdf.
So I'd recommend breaking out your process and figuring out if there's a way to use one of those tools for that step.

If you're doing:
1. Take user input
2. Convert Global.pdf to Global.txt with pdf2txt
3. Search user input in Global.txt

You could replace step 2 with a faster tool with relative ease.

e: or just use Pastebin?

Hughmoris
Apr 21, 2007
Let's go to the abyss!

JawnV6 posted:

If you're using pdf2txt from here, it mentions:
So I'd recommend breaking out your process and figuring out if there's a way to use one of those tools for that step.

If you're doing:
1. Take user input
2. Convert Global.pdf to Global.txt with pdf2txt
3. Search user input in Global.txt

You could replace step 2 with a faster tool with relative ease.

e: or just use Pastebin?

Ok, I uploaded my code. The purpose of the script is to find and extract a single page of a PDF, from a folder full of multi-page PDF files. I had to rename/remove one or two things for privacy purposes, but I think its all simple enough to get the gist.

http://pastebin.com/ftXEfRGD

This code may make you run for the hills, its about a week's worth of google searching python functions and reverse engineering things to meet my needs. Forgive me for my sins.

Hughmoris fucked around with this message at 01:59 on Feb 21, 2015

KICK BAMA KICK
Mar 2, 2009

I haven't got into the meat of it but why are you using subprocess.call to run a Python script as opposed to just importing that module and calling a function?

Hughmoris
Apr 21, 2007
Let's go to the abyss!

KICK BAMA KICK posted:

I haven't got into the meat of it but why are you using subprocess.call to run a Python script as opposed to just importing that module and calling a function?

Learning as I go along and following examples I find online. I'll try to do that with pdf2txt, and I guess I'll have to use subprocess with Adobe Reader still?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Why is --no-site-packages not working? I can't figure out how six 1.8.0 is making it into my virtualenv, I didn't think I even had to specify --no-site-packages since it should be the default behavior, it doesn't seem to work either way though.

code:
[vagrant@vagrant ~]$ pip freeze
argparse==1.2.1
six==1.8.0
stevedore==1.0.0
virtualenv==1.11.6
virtualenv-clone==0.2.5
virtualenvwrapper==4.3.1
wsgiref==0.1.2

[vagrant@vagrant ~]$ mkvirtualenv test --no-site-packages
New python executable in test/bin/python
Installing setuptools, pip...done.

[vagrant@vagrant ~]$ workon test

(test)[vagrant@vagrant ~]$ which pip
~/.virtualenvs/test/bin/pip

(test)[vagrant@vagrant ~]$ pip freeze
argparse==1.2.1
six==1.8.0
stevedore==1.0.0
virtualenv==1.11.6
virtualenv-clone==0.2.5
virtualenvwrapper==4.3.1

cowofwar
Jul 30, 2002

by Athanatos
If I have a list of lists such as the following:

code:
items = [["tom",1,2,3],["bob",1,2,3]]
And I want to iterate through that list:

code:
for item in items:
    print(item.name)
And then get

code:
tom
bob
How would I set that up? I am new to objects and classes, I know how to define a variable that applies to all objects of a class but not how to do this.

Also I am loading the list of lists in from a tab separated file if that helps. Should I be setting this up by first making a list of objects instead?

cowofwar fucked around with this message at 04:45 on Feb 21, 2015

motorcyclesarejets
Apr 24, 2007

cowofwar posted:

If I have a list of lists such as the following:

code:
items = [["tom",1,2,3],["bob",1,2,3]]
And I want to iterate through that list:

code:
for item in items:
    print(item.name)
And then get

code:
tom
bob
How would I set that up? I am new to objects and classes, I know how to define a variable that applies to all objects of a class but not how to do this.

Also I am loading the list of lists in from a tab separated file if that helps. Should I be setting this up by first making a list of objects instead?

Check out collections.namedtuple in the standard library

cowofwar
Jul 30, 2002

by Athanatos

motorcyclesarejets posted:

Check out collections.namedtuple in the standard library
Thanks, this seems to work. Although I had to grep out a bunch of lines and cut excess columns because it doesn't tolerate variation.

Adbot
ADBOT LOVES YOU

Harriet Carker
Jun 2, 2009

I'm beating my head against the wall about a seemingly simple problem. This is a simple test block for code that will eventually delete a wild card from a poker hand, then create a list of all possible hands (each represented by a list of cards) by substituting each possible card in for the wild card and adding that hand to the list. This is the homework for the Udacity course recommended on the previous page. (I'm loving the course and also CheckIO - thanks for recommending them!)

code:
def replace(hand): #takes a list of cards as input
    if "a" in hand:
        hand.remove("a") #placeholder for wildcard - remove the wildcard from the hand
    res = []
    cards = [5,6,7,8,9] #placeholder for list of cards to substitute in for wildcard
    for card in cards:
        hand.append(card) #add a card from the list of cards to the hand
        res.append(hand) #add the hand to the list of hands
        hand.remove(card) #remove the card from the hand
    return res

print(replace([1,2,3,4,"a"]))
This should return [[1,2,3,4,5], [1,2,3,4,6], ....] but it's returning [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]].

If I add some print statements to debug, one after each of the statements in the for loop, I get this:

code:
Appended hand: [1, 2, 3, 4, 5]
Result:  [[1, 2, 3, 4, 5]]
Hand after removal:  [1, 2, 3, 4]

Appended hand: [1, 2, 3, 4, 6]
Result:  [[1, 2, 3, 4, 6], [1, 2, 3, 4, 6]]
Hand after removal:  [1, 2, 3, 4]

Appended hand: [1, 2, 3, 4, 7]
Result:  [[1, 2, 3, 4, 7], [1, 2, 3, 4, 7], [1, 2, 3, 4, 7]]
Hand after removal:  [1, 2, 3, 4]
...
The function is correctly appending and removing the cards from the hand, and even appends the hand correctly to res on the first pass through the loop, but on the second and further passes, it's somehow retroactively changing the elements before the current one being appended to all be equal to the current one being appended. What in the world is causing this behavior? Am I missing something incredibly silly?

  • Locked thread