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
AmericanBarbarian
Nov 23, 2011

Suspicious Dish posted:

Do not read Dive into Python. It was built for a version of Python that's over 10 years old, and the creator has not updated it.

Thanks, that potentially saved me a lot of time.

Adbot
ADBOT LOVES YOU

Dren
Jan 5, 2001

Pillbug

Lysidas posted:

There's no special syntax.

Python code:
In [1]: d = {(2, 1): 'two, one', (0, 0): 'zeroes'}

In [2]: d[2, 1]
Out[2]: 'two, one'
NumPy arrays have different semantics when you call __getitem__ with a tuple argument, however -- this pulls certain elements out of a multidimensional array.

I did not know that d[2, 1] would be treated as a dictionary lookup on a tuple. I assumed you'd have to do d[(2, 1)].

Emacs Headroom
Aug 2, 2003

Lysidas posted:

There's no special syntax.

Python code:
In [1]: d = {(2, 1): 'two, one', (0, 0): 'zeroes'}

In [2]: d[2, 1]
Out[2]: 'two, one'
NumPy arrays have different semantics when you call __getitem__ with a tuple argument, however -- this pulls certain elements out of a multidimensional array.

Numpy can't just be doing something with tuple keys, because you can do slicing right?

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

Dren posted:

I did not know that d[2, 1] would be treated as a dictionary lookup on a tuple. I assumed you'd have to do d[(2, 1)].

It's the same reason why a, b = b, a works. :)

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

Emacs Headroom posted:

Numpy can't just be doing something with tuple keys, because you can do slicing right?

You can't use slices as dictionary keys because they're unhashable :)
Python code:
In [1]: d = {(2, 1): 'two, one', (0, 0): 'zeroes'}

In [2]: d[2, :] = 4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-eba3eb2c8757> in <module>()
----> 1 d[2, :] = 4

TypeError: unhashable type: 'slice'
There are some syntactical restrictions on using the slice operator, however:
Python code:
In [1]: d = {(4, :): 'four, slice'}
  File "<ipython-input-1-f99acc9f2a88>", line 1
    d = {(4, :): 'four, slice'}
             ^
SyntaxError: invalid syntax

Cat Plus Plus
Apr 8, 2011

:frogc00l:

KARMA! posted:

It's the same reason why a, b = b, a works. :)

To explain in little more detail, comma is what actually creates a tuple, not parentheses. That's also why you need a comma at the end of singleton tuple. Only exception is the empty tuple, which is literally ().

code:
>>> x = 1, 2, 3
>>> type(x)
<type 'tuple'>
>>> x = 1,
>>> type(x)
<type 'tuple'>
>>> x = 1
>>> type(x)
<type 'int'>
>>> x = (1)
>>> type(x)
<type 'int'>
>>> x = ()
>>> type(x)
<type 'tuple'>

OnceIWasAnOstrich
Jul 22, 2006

PiotrLegnica posted:

Only exception is the empty tuple, which is literally ()


This has always made me inexplicably angry. I know its unnecessarily complicated and doesn't make sense to have the empty tuple be (,) but damnit, the empty tuple should be a butt.

Coldharbour
Jan 2, 2004
LOL speakeasy LOL
Is there a way to ignore (not update) a file with pysvn on a svn update?

I've gotten it to checkout/update to a temp directory then using rsync to copy with ignore/exclude X files. Would like to get rid of that rsync and just do it on svn update via pysvn.

Modern Pragmatist
Aug 20, 2008
If I'm working on a module that is python2 and python3 compatible, I'd like to force the user to specify string values as unicode. This is easy enough in python3 since unicode strings are very commonplace but for people using python2, they haven't necessarily thought about unicode vs. bytestrings in their programs.

Here is my thought on how to handle them:

Python code:
if isinstance(value, bytes):
    warnings.warn('Assignment of bytestrings has been deprecated in the migration to py3. We will attempt to convert to unicode for you')
    try:
        value = value.decode(default_encoding)
    except UnicodeDecodeError:
        raise UnicodeDecodeError('Unable to decode your string using the %s encoding' % default_encoding)

self.value = value
Is this the best way to remind people to update their code while still attempting to preserve functionality?

Is it acceptable to recommend that python2.x users add from __future__ import unicode_literals to their scripts to improve compatibility?

Dren
Jan 5, 2001

Pillbug
TIL about the specifics of tuple syntax. It is a shame that (,) is invalid so you can't have butts as empty tuples if you want.

If you're going to try to write a compatible library put the compatibility in a separate layer. Make the library the user imports a bunch of stub functions that do nothing but convert string arguments if necessary then call the real functions.

Other solutions include:
  • Not writing a 2/3 compatible library if you can help it. I don't know of any 2/3 compatible libraries that are the same actual code for both language versions and I think there's a good reason for that.
  • Writing "use unicode strings" in your docs and then pointing at the docs when stuff breaks for python 2 users.

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

This thread should be renamed "Python: empty tuples aren't butts :("

SpudCat
Mar 12, 2012

Hi there, python newbie coming in again. I've been trying to practice coding by making a simple test-based game (I'm really new at this programming thing.) But, my game has a problem. The code is pretty long, but here's the gist:

I define the introduction to the game, then define what happens when the player inputs a direction they want to go. The directions are: north, south, east and west. Then I define a menu that should should ask the player for a direction, and based on that input execute the code for that particular direction. There is also some randomization within the directions (by that I mean I use randint and randomchoice).

However, when I go to execute the game, no matter what I enter at the menu, the game executes the north direction, and and always in the same way. Is there some obvious thing I'm doing wrong? Should I just post the code? I'm using Python 3 if that makes any difference.

Gothmog1065
May 14, 2009
Post the code.

At least post the function or the class that contains the parts with the movement commands.

Gothmog1065 fucked around with this message at 01:46 on Sep 7, 2012

SpudCat
Mar 12, 2012

All right, I guess the description was too vague.

code:

import random
import time

hp = 15 #health
bosschoice1 = random.choice(['Blue','Golden','Black','Amber','Crimson','Midnight','Twilight','Ephemeral','Purple','Teal'])

bosschoice2 = random.choice([' Dragon',' Bear',' Serpent',' Phoenix',' Troll',' Lich',' Wraith',' Stag'])

treasure = 0 #points
	

def intro():
	#intro here

def north(hp,treasure):
	print('You travel north, to the frozen disk known as the Sea of Ice.')
	print('Within that cold abyss lives the feared', bosschoice1+bosschoice2, '.')
	print('But your heart is burning with passion hot enough to melt all ice.')
	print('You approach the monster\'s lair...')
	print()
	bossbattle = random.randint(1, 6)
	time.sleep(5)
	if bossbattle == 1:
		print('The beast was asleep! It barely has time to open it\'s eyes \nbefore your sword cleaves it in two!')
		print('You are victorious, and escape without a scratch!')
		print()
		treasure = treasure + 1
	elif bossbattle == 2:
		print('The beast was just waking up! It is so groggy it can barely put up a fight!')
		print('You are victorious, and escape only slightly wounded.')
		print()
		hp = hp - 1
		treasure = treasure + 1
	elif bossbattle == 3:
		print('The beast was awake! You heroically slay it all the same.')
		print('You are victorious, with a couple new scars for your efforts.')
		print()
		hp = hp - 3
		treasure = treasure + 1
	elif bossbattle == 4:
		print('The beast was awake and waiting for you! You manage to escape and beat a heroic retreat!')
		print('You lick your wounds and resolve to seek vengeance another day.')
		print()
		hp = hp - 5
	elif bossbattle == 5:
		print('The beast was awake and waiting for you! You barely manage to get away!')
		print()
		hp = hp - 10
	elif bossbattle ==6:
		print('The beast springs its trap! It rips you to pieces!')
		print()
		hp = 0

#south, east, and west are the same except for the flavor text

def menu():
	print('The four monsters live in separate lairs; \none to the north, one to the south, \none to the east, and one to the west.')
	print('To check your progress, type show.')
	selection = input('Which direction would you like to go? ')
	print()
	if selection == 'n' or 'north':
		north(hp, treasure)
	elif selection == 'e' or 'east':
		east(hp, treasure)
	elif selection == 's' or 'south':
		south(hp, treasure)
	elif selection == 'w' or 'west':
		west(hp, treasure)
	elif selection == 'show':
		print('You have', treasure, 'treasures and', hp, 'health left.')

intro()
gameIsDone = False

while gameIsDone == False:
	menu()
	if hp <= 0:
		print('You are dead. Better luck next time, adventurer!')
		print()
		gameIsDone = True
	elif treasure == 4:
		print('Congratulations! You have slain the monsters and gathered all the treasure!')
		
		gameIsDone = True
	else:
		print('Your journey continues...')
		print()
		menu()
		
print('Game End')
print()

playAgain = input('Would you like to play again? ')
print()
if playAgain == 'y' or 'yes':
	gameIsDone == false
	hp = 15
	treasure = 0
else:
	print()
Super simple and cheesy; it was only meant for practice. Thank you for looking at it!

Hammerite
Mar 9, 2007

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

if selection == 'n' or 'north':

because the "==" operator has higher precedence than the "or" operator, it is equivalent to this:

if (selection == 'n') or 'north':

So you are asking: is it the case that either selection == 'n' is true, or 'north' is true?

The string 'north' always counts as True, so the value returned by "or" will always be True here.

You could change the line to

if selection in ['n', 'north']:

SpudCat
Mar 12, 2012

Thank you! That'll teach me to not skip the basic boring stuff.

Of course, now new problems are popping up, but that's just the joy of programming~! :v:

Comrade Gritty
Sep 19, 2011

This Machine Kills Fascists

Dren posted:



Other solutions include:
  • Not writing a 2/3 compatible library if you can help it. I don't know of any 2/3 compatible libraries that are the same actual code for both language versions and I think there's a good reason for that.
  • Writing "use unicode strings" in your docs and then pointing at the docs when stuff breaks for python 2 users.

Emphasis mine. This is inaccurate, Writing code that is 2 and 3 compatible is the easier and more widespread method of handling the 2 -> 3 shift. It's really not very difficult, especially with something like six and supporting only python 2.6+. It also avoids a lot of the issue of differing code bases (namely that either you have 2 seperate projects with vastly similar code that you need to mirror the changes in, or you use 2to3 and deal with slow tests on 3.x, tracebacks that don't point to the right lines of code, etc. Using six and Python 2.6+ you can write mostly idiomatic Python 3 code, and include support for Python 2 still.

bc87
Dec 11, 2010
Coming from a c++ background, serialization is so much easier using the pickle module.

Sylink
Apr 17, 2004

I'm making a basic scrabble solver and want it to use the letter positions to see if a word fits from a word list.

I have a long way of doing this and its not that processor intensive but I was wondering if there is a better more pythonic way I'm missing.


First we have the 7 letters someone has in their rack lets say these:

code:

rack = 'adctsag'

But then I have the board squares represented in arrays (or a multi-dimensional array).

Lets say the middle squares of a row look like this:

code:
row1 = [' ', ' ' , ' ' , 'g', ' ' , ' ' ,'t']
Now the brute way is to go through my word list and check to see what words have a g and a t in them with two letters in between that also contain any combination of the letters in the rack variable.

But it would be nice if there was some kind of pattern recognition way of doing this but I can't think of anything beyond a series of for loops and other checks.

Anyone have a clever idea?

Modern Pragmatist
Aug 20, 2008

Steampunk Hitler posted:

Emphasis mine. This is inaccurate, Writing code that is 2 and 3 compatible is the easier and more widespread method of handling the 2 -> 3 shift. It's really not very difficult, especially with something like six and supporting only python 2.6+. It also avoids a lot of the issue of differing code bases (namely that either you have 2 seperate projects with vastly similar code that you need to mirror the changes in, or you use 2to3 and deal with slow tests on 3.x, tracebacks that don't point to the right lines of code, etc. Using six and Python 2.6+ you can write mostly idiomatic Python 3 code, and include support for Python 2 still.

The 2to3 approach was the one that we were going for. I hadn't really run into any issues with tracebacks being messed up yet. I think for better backwards compatibility we're going to stick to native strings (str) for both Python 3 and 2. The module only supports 2.6+ so I may look into using six.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



bc87 posted:

Coming from a c++ background, serialization is so much easier using the pickle module.

Don't use it for data a malicious user could access, though http://nadiana.com/python-pickle-insecure

Dren
Jan 5, 2001

Pillbug

Sylink posted:

I'm making a basic scrabble solver and want it to use the letter positions to see if a word fits from a word list.

I have a long way of doing this and its not that processor intensive but I was wondering if there is a better more pythonic way I'm missing.


First we have the 7 letters someone has in their rack lets say these:

code:

rack = 'adctsag'

But then I have the board squares represented in arrays (or a multi-dimensional array).

Lets say the middle squares of a row look like this:

code:
row1 = [' ', ' ' , ' ' , 'g', ' ' , ' ' ,'t']
Now the brute way is to go through my word list and check to see what words have a g and a t in them with two letters in between that also contain any combination of the letters in the rack variable.

But it would be nice if there was some kind of pattern recognition way of doing this but I can't think of anything beyond a series of for loops and other checks.

Anyone have a clever idea?

You should attempt to create a better data structure for your dictionary.

The dictionary has the following characteristics:
1. It doesn't particularly matter how much space you devote to it unless it gets so big you start having to restructure your code so that the whole thing isn't in memory at once. Even then it's not that bad of a problem.
2. It never changes so you can do as much analysis/collection of additional information/organization of it as you want. This is all frontend work that doesn't happen at runtime so you can access the data faster at runtime.

You should create a data structure where looking up all of the words with a letter at position x is really fast. You could have something like this:
code:
wordlist = ['a', 'aardvark', ....]

# The keys of dict_by_pos are letters of the alphabet and the values are
# dictionaries.  The keys of these sub-dictionaries are character positions
# within words.  The values are lists of words with the character at that
# position.
dict_by_pos = {'a' : {}, 'b' : {}, ....}

for word in wordlist:
  for i in xrange(len(word)):
    char = word[i]
    try:
      dict_by_pos[char][i].append(word)
    except KeyError:
      dict_by_pos[char][i] = [word, ]
Then once you've made it, pickle it and load it into your program at runtime. Then you can quickly look up lists of words with letters at certain positions and use set operations to whittle down the possibilities.

Once you have your list of words that can fit with certain letters, such as 'g' and 't' with two spaces in between, perhaps you could re-run the algorithm on that word list to get something that's faster to use for fitting the pieces the player has.

There's probably a more elegant/faster way to solve the problem but this seems like a pretty easy and straightforward optimization that would get you down to an acceptable runtime.

I'd also figure out a data structure for storing the available locations to play along with their constraints and bonuses. When a word is played it would only need to update the parts that change. The point of such a data structure would not be just to avoid reanalyzing parts of the board that were already looked at. It would also be to have a nice, concise list of possible positions to go through while solving the board given the player's current tileset.

ufarn
May 30, 2009
Never mind.

ufarn fucked around with this message at 21:29 on Sep 8, 2012

Comrade Gritty
Sep 19, 2011

This Machine Kills Fascists

Modern Pragmatist posted:

The 2to3 approach was the one that we were going for. I hadn't really run into any issues with tracebacks being messed up yet. I think for better backwards compatibility we're going to stick to native strings (str) for both Python 3 and 2. The module only supports 2.6+ so I may look into using six.

Tracebacks being messed up tends to be line numbers changing or module imports changing so you'll get a traceback that says line XXX and you can't just jump to that line, you have to run 2to3, find the problem, reverse that to find where the problem exists in your existing codebase fix it, run 2to3, make sure it's fixed now, etc.

huhu
Feb 24, 2006
If I assign values to each of the letters such that a=1, b=2, c=3, etc, etc, how could I go about converting a string to a numerical value such as cat = 3 + 1 + 20? I would prefer a push in the right direction instead of a solution if possible.

My thoughts so far is to set
a=1
b=2
...
z=26

Then take a name such as "cat" and break it up and treat c a t as variables and sum these values. I'm just not sure how to identify each of the strings as variables.

huhu fucked around with this message at 18:03 on Sep 8, 2012

Cat Plus Plus
Apr 8, 2011

:frogc00l:

huhu posted:

Then take a name such as "cat" and break it up and treat c a t as variables and sum these values. I'm just not sure how to identify each of the strings as variables.

Use a dictionary that maps letters to their values. Iterating over string will yield individual letters.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
Try the ord function.

Opinion Haver
Apr 9, 2007

As a general rule, you almost never want to go from the name of a variable to a variable itself; it's a sign that you should be using something like a dict.

huhu
Feb 24, 2006
Ended up with a surprisingly fast code which went through about 5000 names in less than a second. I will check out dictionaries and ord now though thanks.

code:
def score(this_name):
    sum=0
    for j in range(len(this_name)):
        if this_name[j]=='A': sum+=1
        if this_name[j]=='B': sum+=2
        if this_name[j]=='C': sum+=3
        if this_name[j]=='D': sum+=4
        if this_name[j]=='E': sum+=5
        if this_name[j]=='F': sum+=6
        if this_name[j]=='G': sum+=7
        if this_name[j]=='H': sum+=8
        if this_name[j]=='I': sum+=9
        if this_name[j]=='J': sum+=10
        if this_name[j]=='K': sum+=11
        if this_name[j]=='L': sum+=12
        if this_name[j]=='M': sum+=13
        if this_name[j]=='N': sum+=14
        if this_name[j]=='O': sum+=15
        if this_name[j]=='P': sum+=16
        if this_name[j]=='Q': sum+=17
        if this_name[j]=='R': sum+=18
        if this_name[j]=='S': sum+=19
        if this_name[j]=='T': sum+=20
        if this_name[j]=='U': sum+=21
        if this_name[j]=='V': sum+=22
        if this_name[j]=='W': sum+=23
        if this_name[j]=='X': sum+=24
        if this_name[j]=='Y': sum+=25
        if this_name[j]=='Z': sum+=26
    return(sum)
Edit: I've solved 14 of the first 22 problems on Project Euler. I'd like to start learning about other aspects of Python that aren't focused primarily on solving math problems similar to Project Euler. What would be the next best logical step from here?

huhu fucked around with this message at 18:47 on Sep 8, 2012

Hammerite
Mar 9, 2007

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

huhu posted:

Ended up with a surprisingly fast code which went through about 5000 names in less than a second. I will check out dictionaries and ord now though thanks.

code:
def score(this_name):
    sum=0
    for j in range(len(this_name)):
        if this_name[j]=='A': sum+=1
        ...
        if this_name[j]=='Z': sum+=26
    return(sum)
Edit: I've solved 14 of the first 22 problems on Project Euler. I'd like to start learning about other aspects of Python that aren't focused primarily on solving math problems similar to Project Euler. What would be the next best logical step from here?

I guess that works, but you're not really using the strengths of the language to cut down on the amount of code you have to write. See how it is possible to do the same thing in four lines of Python code, with less repetition:

Python code:
def score_character (c):
    ordc = ord(c.lower())
    return ordc - 96 if 97 <= ordc <= 122 else 0

def score (name): return sum(score_character(c) for c in name)
To answer your question, it seems like it would be worthwhile learning about Python's iterators, list generators and the like, as it could let you become more comfortable coming up with efficient solutions of your own.

geonetix
Mar 6, 2011


Just to add to that, there's a module with everything you need in it. This is the magic that makes Python useful.

Python code:
import string


def score (name):
    return sum(string.uppercase.index(c)+1 for c in name)

fart simpson
Jul 2, 2005

DEATH TO AMERICA
:xickos:

huhu posted:

Ended up with a surprisingly fast code which went through about 5000 names in less than a second. I will check out dictionaries and ord now though thanks.

code:
def score(this_name):
    sum=0
    for j in range(len(this_name)):
        if this_name[j]=='A': sum+=1
        if this_name[j]=='B': sum+=2
        if this_name[j]=='C': sum+=3
        if this_name[j]=='D': sum+=4
        if this_name[j]=='E': sum+=5
        if this_name[j]=='F': sum+=6
        if this_name[j]=='G': sum+=7
        if this_name[j]=='H': sum+=8
        if this_name[j]=='I': sum+=9
        if this_name[j]=='J': sum+=10
        if this_name[j]=='K': sum+=11
        if this_name[j]=='L': sum+=12
        if this_name[j]=='M': sum+=13
        if this_name[j]=='N': sum+=14
        if this_name[j]=='O': sum+=15
        if this_name[j]=='P': sum+=16
        if this_name[j]=='Q': sum+=17
        if this_name[j]=='R': sum+=18
        if this_name[j]=='S': sum+=19
        if this_name[j]=='T': sum+=20
        if this_name[j]=='U': sum+=21
        if this_name[j]=='V': sum+=22
        if this_name[j]=='W': sum+=23
        if this_name[j]=='X': sum+=24
        if this_name[j]=='Y': sum+=25
        if this_name[j]=='Z': sum+=26
    return(sum)
Edit: I've solved 14 of the first 22 problems on Project Euler. I'd like to start learning about other aspects of Python that aren't focused primarily on solving math problems similar to Project Euler. What would be the next best logical step from here?

If you're gonna do it this way, you might as well at least put elifs instead of ifs

Oakland Martini
Feb 14, 2008

D&D: HASBARA SQUAD
THE APARTHEID ACADEMIC


It's important that institutions never take a stance like "genocide is bad". Now get out there and crack some of my students' skulls.
I've got a strange Python/matplotlib issue going on. I've been using matplotlib in the past few days to re-do all the graphs for my job market paper since I love how nice they look relative to MATLAB/R/etc. However, I'm trying to make some simple scatter plots with least squares lines and something strange is happening -- matplotlib only draws the lines partially, if it draws them at all. Here's some code:

code:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

CSVPATH = '../../data/macro_regs/'

mpl.rc('font',family='serif')
mpl.rc('font',size=FONTSIZE)
mpl.rc('text', usetex=True)

f=open(CSVPATH+'for_python.csv')
data=np.genfromtxt(f, delimiter=",")
data=data[:,1:]
data=data[~np.isnan(data).any(1)]
x_cred=data[:,2]
x_info=data[:,1]
x_ec=data[:,3]
y=data[:,4]

m,b = np.polyfit(x_cred,y,1)
r=m*x_cred+b
fig=plt.figure(1,figsize=(8,5.82))
plt.scatter(x_cred,y,alpha=0.8,s=7,color='blue')
plt.plot(x_cred,m*x_cred+b,linestyle='-',color='black',linewidth=3.0)
plt.xlabel('Private credit/GDP')
plt.ylabel('log TFP')
plt.axis([0,300,1.5,4.0])
plt.savefig('paperfigs/scatter1.pdf',bbox_inches='tight')
plt.clf()

fig=plt.figure(2,figsize=(12,5))
plt.subplot(131)
plt.scatter(x_cred,y,alpha=0.8,s=7,color='blue')
plt.plot(x_cred,r,linestyle='-',color='black',linewidth=3.0)
plt.xlabel('Private credit/GDP')
plt.ylabel('log TFP')
plt.axis([0,300,1.5,4.0])

m,b = np.polyfit(x_info,y,1)
r=m*x_info+b
plt.subplot(132)
plt.scatter(x_info,y,alpha=0.8,s=7,color='blue')
plt.plot(x_info,r,linestyle='-',color='black',linewidth=3.0)
plt.xlabel('Depth of credit info')
plt.ylabel('log TFP')
plt.axis([-1,7,1.5,4.0])

m,b = np.polyfit(x_ec,y,1)
r=m*x_ec+b
plt.subplot(133)
plt.scatter(x_ec,y,alpha=0.8,s=7,color='blue')
plt.plot(x_ec,r,linestyle='-',color='black',linewidth=3.0)
plt.xlabel('Contract enforcement')
plt.ylabel('log TFP')
plt.axis([0,1,1.5,4.0])

plt.savefig('paperfigs/scatter2.pdf',bbox_inches='tight')
plt.clf()
and here are the two figures:




Note how the regression lines for the first figure (which is also the first one in the multi-figure plot) and the third subplot in the second figure get truncated. And the line for the second subplot in the second figure doesn't show up at all. Anybody have any idea how to fix this? Also, you can probably figure out who I am based on these figures, so I'd appreciate it if you would refrain from doing so (or at least posting my contact info).

Edit: And these pictures do a very poor job of capturing how good python figures look.

Dren
Jan 5, 2001

Pillbug

huhu posted:

If I assign values to each of the letters such that a=1, b=2, c=3, etc, etc, how could I go about converting a string to a numerical value such as cat = 3 + 1 + 20? I would prefer a push in the right direction instead of a solution if possible.

My thoughts so far is to set
a=1
b=2
...
z=26

Then take a name such as "cat" and break it up and treat c a t as variables and sum these values. I'm just not sure how to identify each of the strings as variables.

Treating the letters of the alphabet as sequential numbers is a special case of the generic problem of mapping a key to a value since the ord() function easily supplies the mapping for you.

The generic tool to use for solving this problem is the dictionary.
code:
charmap = {
  'A' : 1,
  'B' : 2,
  'C' : 3,

  'Z' : 26,
}
The ord() function can be used to easily populate this dictionary rather than typing all of the values out by hand.

You can then use functional operators to translate your strings into lists of integers that can be summed.

code:
as_int_list = map(lambda x : charmap[string.upper(x)], input_string)
Once you have the int list you can sum the values. I don't mean to give you a solution but the problem is so basic it's hard not to. I believe you could benefit greatly from taking a functional approach to the project euler problems. The idioms of functional style are way more math-like than procedural code. I find it easier to work the problems when I use a functional style.

For starters, look at map(). http://docs.python.org/library/functions.html#map

Note the functional style of Hammerite's solution. He has a function to do the mapping/translation, score_character() (analogous to the dictionary I created). Then, in score(), he translates the original values to the desired values using his mapping function and sums the resulting list.

Functional style in Python can be given to some inefficiency. Sometimes computations that could be combined into one loop are instead spread over two loops. However, what it sometimes lacks in efficiency it makes up for in readability.

Pythagoras a trois
Feb 19, 2004

I have a lot of points to make and I will make them later.
Howdy! Just found this subforum and have been working my way through Udacity classes hard and fast. I'm currently looking at making a quick program that produces a ding whenever a web page updates, and I for the life of me can't find a concise way to produce sound in Python on a contemporary installation of Ubuntu.

The closest answer I've found is old as dirt, making calls to the depreciated /dev/dsp to initiate sound through an oss module. The other options I can follow are installing pretty sizable modules like pygame, but I really just want a 1 second sound clip to play every thirty minutes or so, no UI necessary.

Should I bite the bullet and install Snack, or is there some os-specific import that I'm missing to make simple .wav playback easy?

OnceIWasAnOstrich
Jul 22, 2006

Cheekio posted:

Howdy! Just found this subforum and have been working my way through Udacity classes hard and fast. I'm currently looking at making a quick program that produces a ding whenever a web page updates, and I for the life of me can't find a concise way to produce sound in Python on a contemporary installation of Ubuntu.

The closest answer I've found is old as dirt, making calls to the depreciated /dev/dsp to initiate sound through an oss module. The other options I can follow are installing pretty sizable modules like pygame, but I really just want a 1 second sound clip to play every thirty minutes or so, no UI necessary.

Should I bite the bullet and install Snack, or is there some os-specific import that I'm missing to make simple .wav playback easy?

Pick your favorite command-line audio player (VLC using cvlc, mpg123, sox with play) and use the subprocess module.

Python code:
import subprocess

subprocess.call("cvlc mysound.wav", shell=True)
edit: I think aplay is buillt in and will play wav files.

OnceIWasAnOstrich fucked around with this message at 18:14 on Sep 10, 2012

Pythagoras a trois
Feb 19, 2004

I have a lot of points to make and I will make them later.

OnceIWasAnOstrich posted:

Pick your favorite command-line audio player (VLC using cvlc, mpg123, sox with play) and use the subprocess module.

Python code:
import subprocess

subprocess.call("cvlc mysound.wav", shell=True)
edit: I think aplay is buillt in and will play wav files.

"subprocess + aplay" works great, exactly what I was hoping for! Finally I can (sort of) put my attention back to constructive uses.

Pythagoras a trois fucked around with this message at 19:10 on Sep 10, 2012

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
I just found out that Python chokes if you do this:

code:
f(*L,)
Specifically it does not like a trailing comma after the argument-unpacking operator.

Why does it do this? I thought trailing commas in argument lists, etc. were fine.

Red Mike
Jul 11, 2011
Python code:
>>> def func(a, b, c, d, e, f):
...   print a, b, c, d, e, f
...
>>> x = (1, 2, 3)
>>> func(4, 5, 6, *x)
4 5 6 1 2 3
>>> func(4, 5, *x, 6)
  File "<stdin>", line 1
SyntaxError: only named arguments may follow *expression
Guessing it has something to do with this and how tuple unpacking actually works in an argument list.

Adbot
ADBOT LOVES YOU

Sylink
Apr 17, 2004

Alright, so I kept working on my scrabble program and ran into a problem.

Consider that a row in scrabble contains 15 tiles which could have any reasonable combination of letters on them based on how the game is going.

I represent a row like this, roughly:

code:

pattern = ['','','d','e','n','','','c','','t','','','','e','d']

Now what I want to do is check this row and see what potential words could kill the various possible positions, which would involve dividing this 15 character pattern into chunks that allow for words.

For example, at the 'den' section a simple search would turn up denied as an option, but in this case doesn't fit because you would have a 'c' in the way.


Can anyone think of a straightforward way to check? right now I have a complicated way that still doesn't come up with every possibility (though it does come up with MOST of them).

here is the full code example with sample output:

code:

import re 

##load library into memory
wordlib = open('brit.txt','r')

wordlibrary = wordlib.read().split('\n')

pattern = ['','','d','e','n','','','c','','t','','','','e','d']







def convert_regex(pattern):
	regex = ''
	for i in pattern:
		if i == '':
			regex += '.'
		else:
			regex += i
	regex +='$'
	return regex
#potential function reduces master list based on regex pattern
# def potential_words(self):
	# self.potential = []
	# for word in self.words:
		# if re.search(self.regex, word):
			# self.potential.append(word)
				
def potential_words(pattern,words):
	potential = []
	temp = []
	temp.extend(pattern)
	while temp!= []:
		print convert_regex(temp)
		if temp == []:
			break
		for word in words:
			if re.search(convert_regex(temp),word):
				if len(word) <= len(temp):
					potential.append(word)
		if temp == []:
			break
		if temp[0] != '':
			try:
				while temp[0] != '':
					temp.pop(0)
			except IndexError:
				break
		if temp[0] == '':
			temp.pop(0)	
	##working backwards from right to left
	temp = []
	temp.extend(pattern)
	while temp!= []:
		print convert_regex(temp)
		if temp == []:
			break
		for word in words:
			if re.search(convert_regex(temp),word):
				if len(word) <= len(temp):
					potential.append(word)
		if temp == []:
			break
		if temp[-1] != '':
			try:
				while temp[-1] != '':
					temp.pop(-1)
			except IndexError:
				break
		if temp[-1] == '':
			temp.pop(-1)		

	##both directions??
	temp = []
	temp.extend(pattern)
	while temp!= []:
		print convert_regex(temp)
		if temp == []:
			break
		for word in words:
			if re.search(convert_regex(temp),word):
				if len(word) <= len(temp):
					potential.append(word)
		if temp == []:
			break
		if temp[-1] != '':
			try:
				while temp[-1] != '':
					temp.pop(-1)
			except IndexError:
				break
		if temp[-1] == '':
			temp.pop(-1)
		if temp[0] != '':
			try:
				while temp[0] != '':
					temp.pop(0)
			except IndexError:
				break
		if temp[0] == '':
			temp.pop(0)	
	
	return potential

Output
code:
>>> x = potential_words(pattern,wordlibrary)
..den..c.t...ed$
.den..c.t...ed$
den..c.t...ed$
.c.t...ed$
c.t...ed$
t...ed$
..ed$
.ed$
ed$
..den..c.t...ed$
..den..c.t..$
..den..c.t.$
..den..c.t$
..den..c$
..den.$
..den$
.$
..den..c.t...ed$
.den..c.t..$
den..c.t.$
.c.t$
c$

WORDS
So from the output, in this example you can see I get most of the possible combos but ones like 'c.t' don't show up so the word 'cat' does not appear in the potential words list.

EDIT: oh and I have a class based version of this to do other things, but I separated this out to test it.

  • Locked thread