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
bitprophet
Jul 22, 2004
Taco Defender

trashmatic posted:

If you mean that you can't call 'continue' inside a function and expect it to abort the loop it was called from... well, yes. You can't do that.

I think this is coming in Python 3 though, could swear I read that somewhere :) Not that it helps the poster any, of course. I'd second everything you said, at any rate.

EDIT: reading comprehension :downs: Can't do what you said, but Python3000 is adding multi-level continue statements, I think - i.e. if you're 3 nested for loops deep, you'd be able to have a single continue that says to break out of all 3.

Regarding the original assertion, yea, it's not possible for a function to have any real idea about the state of things when it's being called - it is solely concerned with taking input and giving output, and that's it.

bitprophet fucked around with this message at 16:59 on Feb 25, 2008

Adbot
ADBOT LOVES YOU

Kresher
Sep 11, 2001
Permanent Patient
Ok, thanks for the advice trashmatic.

This is what I've got after working on the program some more (before reading the reply)

code:
import random
def read_list_from_file():
    fileRef = open("ty_words.txt","r") # opening file to be read
    localList=[]
    for line in fileRef:
        word = line[0:len(line)-1]  # eliminates trailing '\n'
                                    # of each line (or last character
                                    # if it is the last line of the file)
                                    
        localList.append(word.lower())  # adds word to list in lower case
        
    fileRef.close()
    return localList

def greetings():
    str_response = raw_input("\nDo you want to play? Y- yes, N - no: ")
    if str_response == "y" or str_response == "Y":
        bool_response = True
    else:
        bool_response = False
    return bool_response   

def ask_user_guess():
    print "".join([((ch in letters) and ch or "-") for ch in word])
    guess = raw_input("Please guess a letter/word (%d/%d): " % (guesses, max_try))
    return guess

def good_bye():
    print " Good bye! "

def check_user_guess():
    if len(guess)>1:
        print "\nYou've guessed the whole word: %s" % (guess)
        if guess.strip() == word: #compares the word guess against the word
            print "\nYour lucky guess is correct!"
        else:
            print "\nToo bad, you were wrong."

def fill_in_blanks():
    for ch in guess:
        letters.append(ch)

def user_win_loss():
    if set(letters) == set(word):
        print "\nCongratulations, you win!"
    else:
        print "You've guessed wrong too many times"
    

wants_to_play = greetings()

while wants_to_play:

    guesses = 0
    max_try = 6
    word = random.choice(read_list_from_file()) #a word from ty_words.txt is
    letters = []                                #picked
    user_won = False
    
    while (guesses<max_try) and (user_won == False):     #playing until won == True or
        guess = ask_user_guess() #the players makes 6 wrong guesses
        if guess not in word:
            print "You've made a wrong guess."
            guesses+=1 
            continue #only occur syntactically nested in a for or while loop
                     #couldn't use this in a function and make the program work
        check_user_guess()
        fill_in_blanks()
        
    user_won = user_win_loss()

    wants_to_play = greetings()

good_bye()
I didn't really touch it much, other than cutting out bits of the code to fit the top level programming model. (Also added the variable user_won to control)

I think I should be able to draw a flow chart now and think it through, but I better study for the midterm on wednesday first.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm very curious about Python. I've never used it, but can't help but see everybody praising it, while everybody puts down PHP. I figured I might as well give it a whirl, but I was wondering if anybody had a good comparison of how something is written in PHP vs what the equivalent would look like in Python, specifically geared towards web development.

trashmatic
Jan 27, 2006

Kresher posted:

This is what I've got after working on the program some more (before reading the reply)

I didn't really touch it much, other than cutting out bits of the code to fit the top level programming model. (Also added the variable user_won to control)
Try to clarify with your teacher what the "top level programming model" (I found nothing on Google) means with respect to your code. I think it's leading you further away from a solution. Functions are generally to take input data, perform a specific task, and return data -- not act as cutely named containers for fragments of your program's control structures.

duck monster
Dec 15, 2004

fletcher posted:

I'm very curious about Python. I've never used it, but can't help but see everybody praising it, while everybody puts down PHP. I figured I might as well give it a whirl, but I was wondering if anybody had a good comparison of how something is written in PHP vs what the equivalent would look like in Python, specifically geared towards web development.

PHP isn't really as bad as its made out, at least not v5 onwards. The latest Object model is actually pretty close , but not quite (in a few key ways) to python.

PHP is however a pretty focused little web language, but not really that good for much else, in comparison with other languages.

I think the more interesting comparison is Perl v Python. I had it described like this. Perl is a chainsaw, Python is the surgeons scalpel. A Chainsaw will amputate a leg much faster than a scalpel, but the scalpel will do a cleaner job of it. Now contrast and compare with cutting down a tree.

Python is elegant, and conservative. Its simple minded as well, and thats a good thing. You'll quickly come to apreciate how python achieves so much, in so small an amount a code with such a small but highly powerful number of primatives.

But its a bit more of a bitch if you want to write 'line noise' regex heavy stuff.

Kresher
Sep 11, 2001
Permanent Patient

trashmatic posted:

Try to clarify with your teacher what the "top level programming model" (I found nothing on Google) means with respect to your code. I think it's leading you further away from a solution. Functions are generally to take input data, perform a specific task, and return data -- not act as cutely named containers for fragments of your program's control structures.

The following is what my prof showed us as an example of "top level" programming.

code:
##  One player guessing game :
##
##  The program picks a number and the user (player) guesses
##
##  Version 2: (added to version 1)
##        MANY GAMES DEPENDING ON USER: nested while loops
##        additions wrt version 1: marked with v2
##        
##  Version 1:
##        only one game
##        no limitation of number of times the user guesses
##        hence the user cannot lose and
##        the program finishes when the user (player) wins
## 
##  1st look at USAGE OF FUNCTIONS AND SUBROUTINES (THAT WE CREATE):
##  FUNCTIONS WITH NO PASSAGE OF PARAMETERS
##  (notice the parenthesis with no variables inside)


## SUBROUTINES AND FUNCTIONS

def welcome():
    print "Welcome to the guessing game - Version 2!\n"

## only new function needed for v3
def invite_user_to_play():
    str_response = raw_input("\nDo you want to play? Y- yes, N - no: ")
    if str_response == "y" or str_response == "Y":
        bool_response = True
    else:
        bool_response = False
    return bool_response        ## both variables,
                                ## str_response and bool_response
                                ## are LOCAL to the function
                                ## invite_user_to_play()

def program_picks():
    num = random.randint(1,10)  ## num is a variable LOCAL to
                                ## the function program_picks
    return num

def ask_user_for_number():
    num = int(raw_input("Please enter a number between " + str(1) \
                        + " and " + str(10) + ": "))
    return num

def check_if_user_guessed():
    return  (user_number == the_number)

def inform_user_won():
    print " Dear player, you have won! "

def say_good_bye():
    print " Good Bye!"

    

## TOP LEVEL
    
## general initializations at top level
import random


welcome()

wants_to_play = invite_user_to_play()  # v2

while   wants_to_play:                 # v2

    the_number = program_picks()
    won = False

    while (not won):   # same as:  while (won == False):

        user_number = ask_user_for_number()

        won = check_if_user_guessed()   ## this will eventually change
                                        ## the variable won to
                                        ## the boolean value True
        

    # here the inner while is over, therefore the user won
    inform_user_won()
    
    
    wants_to_play = invite_user_to_play()   # v2
    

# here the outer while loop is over, since
# the user does not want to play any more, we say good_bye
say_good_bye()   # v2
    
### END OF PROGRAM
Am I doing it right? The big chunks of codes are subroutines, no?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

duck monster posted:

PHP is however a pretty focused little web language, but not really that good for much else, in comparison with other languages.

What makes it not as good as python for a command line application? I've only done very basic things on the command line with php, but Python looks like it would be a lot more useful since it has GTK support.

such a nice boy
Mar 22, 2002

A few things I noticed about your code:

First, you used "continue". It's occasionally acceptable to use "continue", but most of the time, you shouldn't. Instead, use an else clause.

Pass parameters to your functions! You're using "global variables" now; everyone gets access to your variables. This quickly leads to maintainability problems. Instead of:

code:
def user_win_loss():
use:

code:
def user_win_loss(guessed_letters, word):
This makes your functions reusable, as they don't depend on any outside state.

There's another problem with your "user_win_loss" function: it doesn't return anything, even though it's supposed to. You call it thusly:

code:
user_won = user_win_loss()
but it doesn't return a value of "True" or "False"; it just prints a string.

Heresiarch
Oct 6, 2005

Literature is not exhaustible, for the sufficient and simple reason that no single book is. A book is not an isolated being: it is a relationship, an axis of innumerable relationships.
I'm trying to put together a simple file-section app using wxpython, and I'm running into the same problem whether I run the test app on a Linux machine or under Windows.

Basically, the wx.GenericDirCtrl control that I'm using isn't receiving the keyboard focus on app startup, which makes it impossible to control using anything but mouse clicks. This is annoying for the intended purpose, which is to let people select a movie file a directory using a remote control's arrow keys.

The really annoying thing is that after adding "style=wx.DIRCTRL_SELECT_FIRST | wx.WANTS_CHARS" to the control, I can then use window.FindFocus() to see where the keyboard focus is supposed to end up, and it says that it's on the only GenericDirCtrl control in the app. But even so, it won't accept keyboard input unless I click on a filename in the control first. Scrolling the control doesn't do the trick; a filename remains selected but it's greyed out and no keyboard input is accepted.

If I click on a filename first, everything works as intended, including the keyboard focus going back after it returns from the subprocess.check_call() that spawns the media player. It's just the initial keyboard focus on application startup that seems broken.

I have used SetFocus() and all that, and it doesn't help. All it lets me do is pull the "focus" back to the window level. Am I missing something obvious here?

I apologize for the terrible quality of this code. A lot of this was ripped from wxpython tutorials and example code while I tried to test out what I was doing.

code:
import wx
import string
import subprocess

mplayer = 'C:\\Documents and Settings\\Christian Wagner\\Desktop\\mplayer\\mplayer.exe'
startpath = 'E:\\movies\\'

class TestPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)

        self.dir1 = wx.GenericDirCtrl(self, -1, size=(550,350), style=wx.DIRCTRL_SELECT_FIRST | wx.WANTS_CHARS)
	self.dir1.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnSelect)
	self.dir1.SetPath(startpath)

    def OnSelect(self,event):
	videofile = self.dir1.GetPath()
	print videofile
	subprocess.check_call([mplayer, videofile])

class MainWindow(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(600,400))
        self.control = TestPanel(self)

app = wx.PySimpleApp()
frame = MainWindow(None, wx.ID_ANY, 'Select File')
frame.Show()
print frame.FindFocus()
app.MainLoop()
[edit] On the Linux system, the output from FindFocus() is "None", instead of the GenericDirCtrl control, which is odd.

Heresiarch fucked around with this message at 14:24 on Feb 26, 2008

duck monster
Dec 15, 2004

fletcher posted:

What makes it not as good as python for a command line application? I've only done very basic things on the command line with php, but Python looks like it would be a lot more useful since it has GTK support.

Its just better focused on the task. Pythons got a very clean model, and its designed all sharp like for that sort of thing. Truth is, its a generally better language.

Not to say PHP can't do it. But there stuff php simply can't do as well, like threading , or pythons funky itterators and generators, and so on.

But PHP is a fine web language as far as I'm concerned.

trashmatic
Jan 27, 2006

Kresher posted:

The following is what my prof showed us as an example of "top level" programming.

code:
def check_if_user_guessed():
    return  (user_number == the_number)
...
the_number = program_picks()
...
user_number = ask_user_for_number()
...
won = check_if_user_guessed()
There is no excuse for a professor to be showing code like this in an intro class. The rest of the program is pretty bad, too, but drat.

To elaborate, this code is completely abusing global variables in order to make a so-called subroutine out of a function which should logically be taking two arguments (i.e. check_if_user_guessed(user_number, the_number)). The way it is now, if for whatever reason those variables are not in the global scope, it will fail. Terrible programming practice.

Further, it's stupidly named because of course the user guessed, we want to know whether they guessed correctly! So we should write something more like check_if_guess_correct(users_guess, correct_answer). But wait, we can generalize here and just call it check_if_equal(a, b). Brilliant! OH WAIT THAT IS BUILT INTO THE LANGUAGE IT IS CALLED THE == OPERATOR.


Your prof is doing a piss-poor job of teaching functional abstraction.


He/she seems to have created the perception that Python functions work like assembly language subroutines or C preprocessor macros, where the code in the function is simply copy-pasted into your "top level" code at runtime. This is completely wrong.

Try think of a function as a its own box, if you will, that is connected to its caller only by a thin straw. Nothing inside one box can directly alter anything happening inside the other box, it can only send things down the straw as either function arguments or return values and hope the other box does something intelligent with it. That's why you can't use a 'continue' statement inside a function and expect it to bust out of your main program's 'while' loop -- because your function is operating in its own little universe. Data in, data out.

Of course, using global variables completely fucks with this picture because now you have these things that are visible and alterable by both boxes, so you can "cheat" that way. But the picture is still very different from the copy-n-paste idea.

I dunno, hope this helps a little.

trashmatic fucked around with this message at 19:58 on Feb 26, 2008

Wedge of Lime
Sep 4, 2003

I lack indie hair superpowers.

trashmatic posted:

There is no excuse for a professor to be showing code like this in an intro class. The rest of the program is pretty bad, too, but drat.....

To be fair it does say in the code comments at the top

## 1st look at USAGE OF FUNCTIONS AND SUBROUTINES (THAT WE CREATE):
## FUNCTIONS WITH NO PASSAGE OF PARAMETERS
## (notice the parenthesis with no variables inside)

I can still remember attending required basic programming classes in python when I'd already taught myself C. In all seriousness some students *really* struggled with functions after writing simple python programs without them.

It wasn't until they'd grasped functions and parameter passing that the whole "don't use global variables" stuff was introduced.

Kresher
Sep 11, 2001
Permanent Patient
Yes, my class will be learning about local&global variables on friday after tomorrow's midterm.

Also, my prof told us that she usually codes/teaches in Java, and this is her first time teaching the introductory CS course.

Heresiarch
Oct 6, 2005

Literature is not exhaustible, for the sufficient and simple reason that no single book is. A book is not an isolated being: it is a relationship, an axis of innumerable relationships.
The completely elegant solution to my earlier problem (as provided by a guy on #wxpython):
code:
self.dir1.GetTreeCtrl().SetFocus()
I forgot that GenericDirCtl had a TreeCtrl in it that could also receive focus.

Heresiarch fucked around with this message at 00:37 on Feb 28, 2008

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

bitprophet posted:

EDIT: reading comprehension :downs: Can't do what you said, but Python3000 is adding multi-level continue statements, I think - i.e. if you're 3 nested for loops deep, you'd be able to have a single continue that says to break out of all 3.

I just looked into that because I thought it sounded interesting. Apparently it is not being included; the PEP for it was rejected.
http://www.python.org/dev/peps/pep-3136/

bitprophet
Jul 22, 2004
Taco Defender
Thanks for the correction, goes to show that I don't exactly follow the mailing list very carefully :haw:

duck monster
Dec 15, 2004

I just made this

code:
testarr = {     'name':'duckmonster',
                'job':'codemonkey',
                'animals': {
                                '1':'dog',
                                '2':'cat',
                                '3':'mouse'
                           },
                'fat':'your mother'
        }


def returnxml(struct,base,depth=0):
        ostr = (' ' * (depth * 3)) +'<'+str(base)+'>'
        if (hasattr(struct,'items')):
                for item in struct:
                        ostr += '\n'+returnxml(struct[item],item,depth+1) +(' ' * (depth * 3))
        else:
                ostr+=str(struct)
        ostr+='</'+str(base)+'>\n'
        return ostr

print returnxml(testarr,'test')

code:
root@webdev02:~# python test.py
<test>
   <job>codemonkey</job>

   <animals>
      <1>dog</1>

      <3>mouse</3>

      <2>cat</2>
   </animals>

   <name>duckmonster</name>

   <fat>your mother</fat>
</test>
Have fun.

Also the order it puts elements is MAGICAL just like harry potter or a unicorn.

Share Bear
Apr 27, 2004

duck monster posted:

I just made this

xml-from-dictionary function()

Have fun.

Also the order it puts elements is MAGICAL just like harry potter or a unicorn.

That's neat, is this a question? I've read the last two pages and I'm not sure. Dictionaries/hashes don't store ordering information and need sorting for keys or definitions.

oRenj9
Aug 3, 2004

Who loves oRenj soda?!?
College Slice

duck monster posted:

Also the order it puts elements is MAGICAL just like harry potter or a unicorn.

The ordering is quite consistent for being magical. Dictionaries are order by the generated index from the hash key, not the order in which the items were placed in the hash. 'job' apparently generates a lower index than any of the other values you've provided.

If you need to retrieve values from the dict in a specific order, you're probably going to have to use a pre-sorted list of keys.

Edit: I'm surprised this behavior is not discussed in the documentation.
Edit2: I'm surprised the reason behind this behavior is not discussed in the documentation.

oRenj9 fucked around with this message at 17:55 on Feb 28, 2008

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

oRenj9 posted:

The ordering is quite consistent for being magical. Dictionaries are order by the generated index from the hash key, not the order in which the items were placed in the hash. 'job' apparently generates a lower index than any of the other values you've provided.

If you need to retrieve values from the dict in a specific order, you're probably going to have to use a pre-sorted list of keys.

Edit: I'm surprised this behavior is not discussed in the documentation.

Oooor you could wrap a sorted around it. for item in sorted(struct): ...

e: Also, string formatting is your friend.
code:
ostr+='</'+str(base)+'>\n' becomes
ostr += '</%s>\n' % base

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
or you can browse django's source and grab SortedDict.

edit:

Habnabit posted:

Oooor you could wrap a sorted around it. for item in sorted(struct): ...

that should be for key in sorted(dict):


because sorted() on a dict only returns the keys

also:

oRenj9 posted:

The ordering is quite consistent for being magical.

...

Edit: I'm surprised this behavior is not discussed in the documentation.

It's consistent, but it differs accross implementations, which is exactly what the docs says.

Python Library Docs posted:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): "pairs = zip(a.values(), a.keys())". The same relationship holds for the iterkeys() and itervalues() methods: "pairs = zip(a.itervalues(), a.iterkeys())" provides the same value for pairs. Another way to create the same list is "pairs = [(v, k) for (k, v) in a.iteritems()]".

deimos fucked around with this message at 15:26 on Feb 28, 2008

Wedge of Lime
Sep 4, 2003

I lack indie hair superpowers.

deimos posted:

or you can browse django's source and grab SortedDict.

Though they're still having issues, I believe the ordering of dicts is what causes the following lovely bug (I believe):

http://code.djangoproject.com/ticket/4193

http://code.djangoproject.com/ticket/6374

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Wedge of Lime posted:

Though they're still having issues, I believe the ordering of dicts is what causes the following lovely bug (I believe):

http://code.djangoproject.com/ticket/4193

http://code.djangoproject.com/ticket/6374

Isn't that because they use regular dicts instead of the sorted alternative? I know that's why they're having some tests fail on PyPy. The tests expect CPython ordering.

VirtuaSpy
Jul 26, 2002

OMG WTF FIREEEE!!
Newbie Python question:

Say I have a CSV file like so:
code:
0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00
6.00E-01,0.00E+00,0.00E+00,0.00E+00,1.09E-16,0.00E+00
1.20E+00,0.00E+00,0.00E+00,0.00E+00,1.09E-16,0.00E+00
and so on.

I know there are different ways to read in the CSV file, and I would like to manipulate the resulting input so that it will work with pyChart. pyChart has its own way to read in CSV data using art_data.read_csv('file', '%d,%s:%d'): http://home.gna.org/pychart/doc/module-chart-data.html But it wants a specific format that my CSV file does not have.

So, I ask, what is a good way to read in the CSV input and manipulate it to be as pyChart wants, either as a comma separated list [5, 10, 15] or as a tuple (5, 10, 15). I would like to come up with a method rather than just fixing the CSV data manually because that is exactly how it comes out of the simulation program that I use.

So far, when I read it in using:

adata = []
for line in csv.reader(open("hrrnum.csv").readlines()[1:]):
adata.append(line)

I get:
code:
[' 6.0000002E-001', ' 0.0000000E+000', ' 0.0000000E+000', ' 0.0000000E+000', ' 1.0913936E-016', ' 0.0000000E+000']
[' 1.2000000E+000', ' 0.0000000E+000', ' 0.0000000E+000', ' 0.0000000E+000', ' 1.0913936E-016', ' 0.0000000E+000']
[' 1.8000000E+000', ' 0.0000000E+000', ' 0.0000000E+000', ' 0.0000000E+000', ' 1.0913936E-016', ' 0.0000000E+000']
[' 2.4100001E+000', ' 0.0000000E+000', ' 0.0000000E+000', ' 0.0000000E+000', ' 1.0913936E-016', ' 0.0000000E+000']
[' 3.0100000E+000', ' 0.0000000E+000', ' 0.0000000E+000', ' 0.0000000E+000', ' 1.0913936E-016', ' 0.0000000E+000']
And, of course, if I try to read it in with the pyChart function, it doesn't like the exponential notation. I tried using a loop and float/long but I am too much of a newbie to know what to try next.

Thank you for any help in kicking me in the right direction.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

VirtuaSpy posted:

Newbie Python question:
I know there are different ways to read in the CSV file, and I would like to manipulate the resulting input so that it will work with pyChart. pyChart has its own way to read in CSV data using art_data.read_csv('file', '%d,%s:%d'): http://home.gna.org/pychart/doc/module-chart-data.html But it wants a specific format that my CSV file does not have.

...

Thank you for any help in kicking me in the right direction.

Instead of copy/pasting, read the docs, try:
chart_data.read_csv('file','%f,')

heck I think
chart_data.read_csv('file',',')

should work.

VirtuaSpy
Jul 26, 2002

OMG WTF FIREEEE!!
I knew that I was being an idiot somehow. Thank you.

duck monster
Dec 15, 2004

Oh I'm aware that the expectation of ordering is not a good one, but its annoying, since a handy little guide to ordering is provided by the structure provided.

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

deimos posted:

that should be for key in sorted(dict):
because sorted() on a dict only returns the keys

I was trying to use the same variable names:

duck monster posted:

code:
def returnxml(struct,base,depth=0):
        ostr = (' ' * (depth * 3)) +'<'+str(base)+'>'
        if (hasattr(struct,'items')):
                for item in struct:
                        ostr += '\n'+returnxml(struct[item],item,depth+1) +(' ' * (depth * 3))
        else:
                ostr+=str(struct)
        ostr+='</'+str(base)+'>\n'
        return ostr

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Habnabit posted:

I was trying to use the same variable names:

My bad. But still, it was worth clarifying.

PnP Bios
Oct 24, 2005
optional; no images are allowed, only text
I'm using python with pySerial and wxWidgets to do some pretty sweet stuff with GPS devices. I just have to say that wx for python is amazingly simple to use. I love it to pieces.

Marzzle
Dec 1, 2004

Bursting with flavor

How do I install a .egg on python in os x? I have installed "easy_install" or at least I think I did

code:
>>> easy_install /Users/name/Downloads/mpl.egg

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    easy_install /Users/name/Downloads/mpl.egg
NameError: name 'easy_install' is not defined
It's taken me like 3 hours trying to get this thing on here.

The module is matplotlib and I just renamed the thing since it was driving me crazy.

schzim
May 24, 2006
tl;dr
Help me not be retarded with regular expressions

>>print re.search('\bword\b','something donkey1431 ; ,word , ; ,cat]')
None

I want to use a regular expression to check for the existence of a word in a sentence but I want to make sure it is not part of another word '\bword\b' has not been working for this purpose.

hey mom its 420
May 12, 2007

Use r'\bword\b' or '\\bword\\b'

mantaworks
May 6, 2005

by Fragmaster

Marzzle posted:

How do I install a .egg on python in os x? I have installed "easy_install" or at least I think I did

code:
>>> easy_install /Users/name/Downloads/mpl.egg

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    easy_install /Users/name/Downloads/mpl.egg
NameError: name 'easy_install' is not defined
It's taken me like 3 hours trying to get this thing on here.

The module is matplotlib and I just renamed the thing since it was driving me crazy.

Don't execute it in python's interactive prompt, execute it into a command line (ie Terminal).

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

Marzzle posted:

:words:

As said before, easy_install is a command. It should be /System/Library/Python.framework/Versions/Current/bin/ unless you manually upgraded your python.

So,
$ easy_install [...].egg

schzim posted:

I want to use a regular expression to check for the existence of a word in a sentence but I want to make sure it is not part of another word '\bword\b' has not been working for this purpose.

Raw strings were designed for things like this. Don't escape the backslashes, just do r'\bword\b'. Raw strings don't parse escape characters like \b or \n, but they will still parse \\' or \" like expected.

duck monster
Dec 15, 2004

PnP Bios posted:

I'm using python with pySerial and wxWidgets to do some pretty sweet stuff with GPS devices. I just have to say that wx for python is amazingly simple to use. I love it to pieces.

track down boa constructor. its a bit rusty, which is a shame because it would be loving fantastic otherwise. However its a really competent gui designer and generates nice and clean code. But due to its buggyness I'd recomend once designing the gui, using something else to finish it off. Crashing and losing code sucks.

If the guy working on it wasnt so drat insular and let it open up a bit, it could be a 'killer app' in the python world as a full delphi-like system.

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...
Here's something basic, but it might represent a gap in my Python-fu.

I have a bunch of floating point numbers of indeterminate size. Say, 3.02340, 0.8, 0.0051234. Now with the string formatting, it's fairly easy to specify the number of digits before the decimal points and the number of digits after:

'%2f' % x => ['3.023400', '0.800000', '0.005123']

'%0.2f' % x => ['3.02', '0.80', '0.01']

What I'd like to do is something a bit different, show 3 digits precision overall. So it would look like:

['3.02', '0.800', '0.00512']

Any ideas on the most robust way to do this?

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

outlier posted:

Here's something basic, but it might represent a gap in my Python-fu.

I have a bunch of floating point numbers of indeterminate size. Say, 3.02340, 0.8, 0.0051234. Now with the string formatting, it's fairly easy to specify the number of digits before the decimal points and the number of digits after:

'%2f' % x => ['3.023400', '0.800000', '0.005123']

'%0.2f' % x => ['3.02', '0.80', '0.01']

What I'd like to do is something a bit different, show 3 digits precision overall. So it would look like:

['3.02', '0.800', '0.00512']

Any ideas on the most robust way to do this?

You can do this with the decimal module and setting precision to 3 on the context I guess. You're probably best served by casting it to an engineering string.

ed: forgot link

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.
^^^ I'd have to do a speed test to see, but if I remember correctly, doing it with Decimals is a little slower.

outlier posted:

Here's something basic, but it might represent a gap in my Python-fu.

I have a bunch of floating point numbers of indeterminate size. Say, 3.02340, 0.8, 0.0051234. Now with the string formatting, it's fairly easy to specify the number of digits before the decimal points and the number of digits after:

'%2f' % x => ['3.023400', '0.800000', '0.005123']

'%0.2f' % x => ['3.02', '0.80', '0.01']

What I'd like to do is something a bit different, show 3 digits precision overall. So it would look like:

['3.02', '0.800', '0.00512']

Any ideas on the most robust way to do this?

There's not really an easy way to do this. Here's a small function I found in ASPN's python cookbook that I tidied up a little.

code:
def sig_digits(num, digits):
    digs, order = ('%.20e' % num).split('e') 
    order = int(order)
    digs = (digs.replace('.', '') + '0' * digits)[:digits]
    if 0 <= order < 5 and order < len(digs) - 1:
        return '%s.%s' % (digs[:order + 1], digs[order + 1:])
    elif -5 <= order < 0: 
        return '0.%s%s' % ('0' * (-order-1), digs)
    else:
        return '%s.%se%+d' % (digs[0], digs[1:], order)

Adbot
ADBOT LOVES YOU

Marzzle
Dec 1, 2004

Bursting with flavor

mantaworks posted:

Don't execute it in python's interactive prompt, execute it into a command line (ie Terminal).

I have run the "ez_setup.py" in IDLE's prompt, this was right yes? Now when I try easy_install in a terminal I just get

code:
computer:~ user$ easy_install
-bash: /Library/Frameworks/Python.framework/Versions/Current/bin/easy_install: "/Applications/MacPython: bad interpreter: No such file or directory
It does the same thing when used on the .egg. Is it broken somehow?

  • Locked thread