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
king_kilr
May 25, 2007

Lonely Wolf posted:

No, that's not possible. Yes, it sounds like you are not using objects right. It sounds like you want is a function that returns a Film object iff it is constructible.

Actually it technically is possible, it just involves a metaclass.

Adbot
ADBOT LOVES YOU

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Hmm, I suppose so but it's also technically possible to shoot yourself in the face. I wouldn't recommend either, except in special circumstances.

duck monster
Dec 15, 2004

Milde posted:

Sounds like either his distribution of Python is built incorrectly, or the app he's trying to build is adding those flags itself.

Running python-config --cflags will tell you what the default CFLAGS are for building extensions with distutils. If that faulty flag is in there, you probably need to fix/rebuild your Python installation.

afaik its just bog standard apple python on a pretty standard snow leopard install

mindyou theres been many iiterations of Xcode on there, so gently caress knows what impact that has.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

duck monster posted:

afaik its just bog standard apple python on a pretty standard snow leopard install

mindyou theres been many iiterations of Xcode on there, so gently caress knows what impact that has.

well --cflags gives me this on the default Snow Leopard python install:

code:
-I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 \
-I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 \
-fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE

duck monster
Dec 15, 2004

Sailor_Spoon posted:

well --cflags gives me this on the default Snow Leopard python install:

code:
-I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 \
-I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 \
-fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE

code:
bash-3.2# python-config --cflags
-I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3
Should I be on v2.6 by now? Seems to have hung onto an old build or something whacko like that.

How would I give it a kick in the teeth and tell it to use the proper version?

Allie
Jan 17, 2004

duck monster posted:

code:
bash-3.2# python-config --cflags
-I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3
Should I be on v2.6 by now? Seems to have hung onto an old build or something whacko like that.

How would I give it a kick in the teeth and tell it to use the proper version?

Are you using python.org's distribution? If so, uninstall it and use Apple Python (it lives in /System).

Alternatively, install python2.6 from MacPorts.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

duck monster posted:

Should I be on v2.6 by now? Seems to have hung onto an old build or something whacko like that.

How would I give it a kick in the teeth and tell it to use the proper version?

If you're on Snow Leopard, than you have 2.6.2 installed, only it's in /System as Milde mentioned. It should just be a matter of changing your PATH to point to it first. I recommend ensuring that /System/Library/Frameworks/Python.framework/Versions/2.6/bin is first, or at least before any of the usual bin/ dirs in $PATH.

If you want to stick with 2.5, or at least use it by default, there is also a 2.5.4 framework in /System.

From the sound of the problems you're having, I'd probably just nuke your existing python install. If none of the /System frameworks will do for whatever reason, just grab one of the .dmg installers from python.org.

I don't have any good, concrete reasoning, but I strongly advise against installing from macports. That way lies madness and sorrow.

duck monster
Dec 15, 2004

Found it. There was some poo poo stuck in my .profile (or whatever it is again) that was locking it down to the apple 2.5 instead of 2.6. Removed that and victory ensured.

Still a little puzzling why apples 2.5 python has GCC options that are not compatible with its prefered GCC. Maybe it didn't upgrade it from leopard when I upgraded, maybe due to some dumb poo poo.

Thermopyle
Jul 1, 2003

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

Ok, so the different pieces of software I'm writing are getting close to 5k lines total, and managing all this is getting irritating. Maintaining different versions while trying out different methods to solve problems, keeping old versions around, etc is not fun.

Given that I know nothing about the subject, I'm guessing I need some sort of version control system/code repository/magic.

I guess this maybe isn't Python specific...but maybe it is, I don't know:

What's a good solution for a developer on a Windows machine? Is this completely language agnostic, meaning I should make a new thread about it?

griliard
May 12, 2006

Thermopyle posted:

What's a good solution for a developer on a Windows machine? Is this completely language agnostic, meaning I should make a new thread about it?

Pretty much this.

But the common open source revision control systems are:

Subversion(Centralized RCS)
Mercurial(Distributed RCS)
Git(Distributed RCS - Used by most Linux kernel developers)

See wikipedia for the difference between centralized and
distributed revision control.

Edit:

And here is the megathread.

griliard fucked around with this message at 01:19 on Dec 9, 2009

Captain Lou
Jun 18, 2004

buenas tardes amigo
I don't recommend using Git if you're only developing on Windows, it's a pain to use.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Captain Lou posted:

I don't recommend using Git if you're only developing on Windows, it's a pain to use.

Listen to this man.

I use TortoiseHg.

echinopsis
Apr 13, 2004

by Fluffdaddy
I'm having trouble with the immutable strings.. I'm writing something small and gimmicky, and it relies on changing individual characters in a string.. (many many times over)

I'm struggling to work out how to get around it

No Safe Word
Feb 26, 2005

echinopsis posted:

I'm having trouble with the immutable strings.. I'm writing something small and gimmicky, and it relies on changing individual characters in a string.. (many many times over)

I'm struggling to work out how to get around it

code:
new_string = transformation_function(old_string)
new_string = old_string.method()

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

echinopsis posted:

I'm having trouble with the immutable strings.. I'm writing something small and gimmicky, and it relies on changing individual characters in a string.. (many many times over)

I'm struggling to work out how to get around it

use lists? You're going to have to be a little more specific.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

Sailor_Spoon posted:

use lists? You're going to have to be a little more specific.

I think you mean "NumPy arrays". The overhead from a list of characters in Python would be hilarious.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Avenging Dentist posted:

I think you mean "NumPy arrays". The overhead from a list of characters in Python would be hilarious.

he said it was "small and gimmicky"

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

Sailor_Spoon posted:

he said it was "small and gimmicky"

I would assume he's worried about performance to some degree, or he'd have just written a function that did s[0:i]+char+s[i+1:]

echinopsis
Apr 13, 2004

by Fluffdaddy

Sailor_Spoon posted:

use lists? You're going to have to be a little more specific.

i'm attempting to make that program dawkins used to "prove" evolution
it takes a random string of characters

"tyikjc"

and a target

"target"

and then every cycle it randomly changes each character unless it ends up as one of the target letters
output might look like this: (but will take many more iterations)


tyikjc
trruyt
tarewt
targut
target

so I'd cycle through each character in the string replacing each one with a random character unless it matched the target letter, then print the string, then repeat, until eventually all the letters were the same as the target

edit: this is the first thing I've ever coded in python and I'm a noob when it comes to coding eitherway

echinopsis fucked around with this message at 23:13 on Dec 10, 2009

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...

echinopsis posted:

i'm attempting to make that program dawkins used to "prove" evolution
it takes a random string of characters

(I remember writing a program just like that to learn Python.)

The simplest solution speedwise is probably - as Sailor_Spoon said - to model the "chromosome" or sentence as a list of characters (single letter strings) rather than a string. Actually I seem to remember someone using this exact problem to compare the various ways of mutating strings in Python.

If you just don't want to bothered about the immutability of strings (for the purposes of the exercise), you could use MutableString. It's not fast, but I think it's still hanging around in the standard library.

tripwire
Nov 19, 2004

        ghost flow

echinopsis posted:

i'm attempting to make that program dawkins used to "prove" evolution
it takes a random string of characters

"tyikjc"

and a target

"target"

and then every cycle it randomly changes each character unless it ends up as one of the target letters
output might look like this: (but will take many more iterations)


tyikjc
trruyt
tarewt
targut
target

so I'd cycle through each character in the string replacing each one with a random character unless it matched the target letter, then print the string, then repeat, until eventually all the letters were the same as the target

edit: this is the first thing I've ever coded in python and I'm a noob when it comes to coding eitherway
Here's a version which uses lists of letters in place of strings. Its slow but for your purposes I think it will work.

code:
import string, random

class TextGenome(object):
    genome = list(  '@' * 20 )
    
    def __init__(self,genome):
        self.genome = genome
        
    def distance(self,target_str):
        error = sum(
            abs(ord(self.genome[i])-ord(target_str[i]))
                for i in xrange(len(target_str)) )
        return error
    
    def mutate(self):
        index_to_mutate = random.randint( len(self.genome) )
        self.genome[index_to_mutate] = random.choice(string.letters)
Have a population class which stores collections of genomes and evaluates them and reproduces in cycles.

echinopsis
Apr 13, 2004

by Fluffdaddy

tripwire posted:

Here's a version which uses lists of letters in place of strings. Its slow but for your purposes I think it will work.

code:
import string, random

class TextGenome(object):
    genome = list(  '@' * 20 )
    
    def __init__(self,genome):
        self.genome = genome
        
    def distance(self,target_str):
        error = sum(
            abs(ord(self.genome[i])-ord(target_str[i]))
                for i in xrange(len(target_str)) )
        return error
    
    def mutate(self):
        index_to_mutate = random.randint( len(self.genome) )
        self.genome[index_to_mutate] = random.choice(string.letters)
Have a population class which stores collections of genomes and evaluates them and reproduces in cycles.

I think I need to go back to the documentation because I can't follow that code at all

what I wanted to do would look like this
code:
import random
target = "jizzmongrel"
alphalist = "abcdefghijklmnopqrstuvwxyz "

#init randomphrase
for i in range(len(target)):
  toy[i] = random.choice(alphalist)

#randomise and print out iterations
print toy
while (toy != target)):
  for i in range(len(target)):
    if (toy[i] != target[i]):
      toy[i] = random.choice(alphalist)
  print toy
I'm poo poo at coding anyway, I don't know if it would even work in theory (I can never work out how poo poo will run until it does) but it seems like it could be really simple if I could edit strings. I'll look into mutable strings maybe..

echinopsis
Apr 13, 2004

by Fluffdaddy
code:
import random
target = "diddle"
alphalist = "abcdefghijklmnopqrstuvwxyz "

#init random
toy=[range(len(target))]
for i in range(len(target)):
        print i
        toy[i]= random.choice(alphalist)

#init iterate
print toy
while toy != target:
	for i in range(len(target)):
		if toy[i] != target[i]:
			toy[i] = random.choice(alphalist)
	print toy
so that's my attempt using lists but I must fundamentally misunderstand something as it complains that I am indexing out of range whenever I got toy[i] something (and i=>1).. what is wrong with me

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

echinopsis posted:

so that's my attempt using lists but I must fundamentally misunderstand something as it complains that I am indexing out of range whenever I got toy[i] something (and i=>1).. what is wrong with me

code:
import random
toy=[range(len(target))]
This creates a list of one element which is the list returned by range.

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

echinopsis posted:

code:
import random
target = "diddle"
alphalist = "abcdefghijklmnopqrstuvwxyz "

#init random
toy=[range(len(target))]
for i in range(len(target)):
        print i
        toy[i]= random.choice(alphalist)

#init iterate
print toy
while toy != target:
	for i in range(len(target)):
		if toy[i] != target[i]:
			toy[i] = random.choice(alphalist)
	print toy
so that's my attempt using lists but I must fundamentally misunderstand something as it complains that I am indexing out of range whenever I got toy[i] something (and i=>1).. what is wrong with me

I actually took your earlier example and made it work with not very many changes at all. It manages it in about 50-100 iterations. Here is is, with comments about why I changed things.

code:
# -*- coding: utf-8 -*-
import random
#toy is a list, so the target needs to be a list for comparisons between them to work
target = list("jizzmongrel") 
#I think there's something in the standard library for this, but this way's fine
alphalist = "abcdefghijklmnopqrstuvwxyz " 

# you need to create the list first and make it the correct size - otherwise you'll get out of range errors or
# errors about the list not existing. 
toy = ['a']*len(target) 

#I'm using xrange here for no other reason that it's faster for loops, as it returns an iterator
#if you don't know what they are, look generators up. one day, you will realise they're absolutely awesome
for i in xrange(len(target)): 
  toy[i] = random.choice(alphalist)
  
#I'd actually personally use a list comprehension here
toy = [random.choice(alphalist) for i in xrange(len(target))] 
#but that might be less clear. Still, they're worth knowing as they're quite powerful 
#and you avoid that needless array filling first

#I'm converting the list back to a string for printing here by using the join method of strings
#I'm basically just saying 'make this a string by joining the elements together with empty spaces' 
#It's not essential, but it makes things prettier
print "".join(toy) 

#had I not made target a list earlier, I'd need to make toy a string here (like I did above)
#also, you don't need brackets round the expressions for ifs and whiles and things in Python, so I've taken those out
while toy != target: 
  for i in xrange(len(target)):
    if toy[i] != target[i]:
      toy[i] = random.choice(alphalist)
  print "".join(toy)
If you don't understand anything, please do ask. I'm sure AD would have you using numpy and JIT compilers and poo poo, but for your purposes, that's fine. It's worth noting, though, that this isn't really an accurate simulation of evolution (whereas tripwire's is) because once you've got something you know to be right, you stick to it. Real evolution doesn't have that luxury - it just knows how good something is as a whole - so it just tries to better that by randomising everything. Work through tripwire's code, and you'll hopefully get what I'm aiming at.

Jonnty fucked around with this message at 03:26 on Dec 11, 2009

echinopsis
Apr 13, 2004

by Fluffdaddy

Jonnty posted:

If you don't understand anything, please do ask. I'm sure AD would have you using numpy and JIT compilers and poo poo, but for your purposes, that's fine. It's worth noting, though, that this isn't really an accurate simulation of evolution (whereas tripwire's is) because once you've got something you know to be right, you stick to it. Real evolution doesn't have that luxury - it just knows how good something is as a whole - so it just tries to better that by randomising everything. Work through tripwire's code, and you'll hopefully get what I'm aiming at.

thanks for the help man, I'll work through it

I'm not trying to make an evolution simulator though, just this specific program..

:D

echinopsis
Apr 13, 2004

by Fluffdaddy
Just had a work through it.. thanks for the help it's really, um, helpful :) I appreciate it.

I'm glad my theory was there, just not my understanding of the implementations of lists etc.. One day I will get there :)

edit:http://forums.somethingawful.com/showthread.php?threadid=3239608

echinopsis fucked around with this message at 03:54 on Dec 11, 2009

itsasnake
Sep 1, 2007
I'm having difficulty with some basic python and wondered if anyone could give me a quick hand, or at least tell me if the solution to this is a simple or a difficult one.

I have two dictionaries of the format {groupID:{IDswithingroup:numberofoccurences}}

I want to merge them together. Can anyone help?

Thanks!

bitprophet
Jul 22, 2004
Taco Defender

itsasnake posted:

I have two dictionaries of the format {groupID:{IDswithingroup:numberofoccurences}}

I want to merge them together. Can anyone help?

Thanks!

code:
dict1.update(dict2)
dict.update

When in doubt, just go to that stdtypes page and look at the available methods for the data type you're working with :)

itsasnake
Sep 1, 2007
nice! Thanks very much. I did look at that method but misunderstood it, i assumed it would not work for dict within dict.

itsasnake
Sep 1, 2007
Actually, after testing it, it doesn't work how i want it to.

I have 2 dictionaries, both of these have a dictionary within them.

So 2 separate dictionaries which are both of the format.

{IDno{IDgroup:numberofoccurences}}

If i simply update one with the other then in cases where both dictionaries have an ID number, the contents of one dictionary gets overwritten. I need the two dictionary contents added together. Such as below

{1:{[A:1],[B:2]}}

{1:{[C:1],[E.4]}}

= {1:{[A:1],[B:2],[C:1],[E,4]}

Group IDs will always be different so i do not need to worry about them being the same.

edited for more clarity.
edit: nevermind, solved it. Using that update function and for loops. thanks.
edit: again, no still not working. Sorry for indecisiveness! Would appreciate some help on this if possible!

itsasnake fucked around with this message at 06:23 on Dec 16, 2009

leterip
Aug 25, 2004
Something like this?

code:
>>> d1 = {1:{'A':1, 'B':2}, 2:{'W':1, 'X':2}}
>>> d2 = {1:{'C':3, 'D':4}, 2:{'Y':3, 'Z':4}}
>>> for key in d1:
...     if key in d2:
...             d1[key].update(d2[key])
... 
>>> print d1
{1: {'A': 1, 'C': 3, 'B': 2, 'D': 4}, 2: {'Y': 3, 'X': 2, 'Z': 4, 'W': 1}}

itsasnake
Sep 1, 2007
Sort of, though i don't think that accounts for circumstances where only one of the 2 dictionaries has a specific persons ID.

leterip
Aug 25, 2004
Well how about this then:

code:
>>> d1 = {1:{'A':1, 'B':2}, 2:{'W':1, 'X':2}, 3:{'A':1}}
>>> d2 = {1:{'C':3, 'D':4}, 2:{'Y':3, 'Z':4}, 4:{'A':1}}
>>> for key in d1:
...     if key in d2:
...             d1[key].update(d2[key])
... 
>>> for key in d2:
...     if key not in d1:
...             d1[key] = d2[key]
... 
>>> print d1
{1: {'A': 1, 'C': 3, 'B': 2, 'D': 4}, 2: {'Y': 3, 'X': 2, 'Z': 4, 'W': 1}, 3: {'A': 1}, 4: {'A': 1}}

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
Or you could roughly halve the performance cost and:
code:
for key in d2:
    if key in d1:
        d1[key].update(d2[key])
    else:
        d1[key] = d2[key]

Avenging Dentist fucked around with this message at 08:26 on Dec 16, 2009

itsasnake
Sep 1, 2007
Yeah, thats it, thanks guys.

NadaTooma
Aug 24, 2004

The good thing is that everyone around you has more critical failures in combat, the bad thing is - so do you!
I'm not sure what problem you're trying to solve, but have you considered flattening your dictionary and using tuples as keys instead? That would simplify your merges since keys wouldn't overlap. Seeing one dictionary stored in another makes me :raise: a bit, since whenever I've used that pattern in my own code, I've always refactored it out later.

So, you might want to try changing this:
code:
>>> d1 = {1:{'A':1, 'B':2}, 2:{'W':1, 'X':2}, 3:{'A':1}}
>>> d2 = {1:{'C':3, 'D':4}, 2:{'Y':3, 'Z':4}, 4:{'A':1}}
To this:
code:
>>> d1 = {(1,'A'):1, (1,'B'):2, (2,'W'):1, (2,'X'):2, (3,'A'):1}
>>> d2 = {(1,'C'):3, (1,'D'):4, (2,'Y'):3, (2,'Z'):4, (4,'A'):1}
>>> d1.update(d2)
>>> d1
{(1, 'A'): 1, (1, 'B'): 2, (1, 'C'): 3, (1, 'D'): 4,
 (2, 'W'): 1, (2, 'X'): 2, (2, 'Y'): 3, (2, 'Z'): 4, 
 (3, 'A'): 1,
 (4, 'A'): 1}
(Results sorted for clarity, and no table breakage.)

Once again, not sure what you're trying to do, just some food for thought.

Thermopyle
Jul 1, 2003

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

What's a good heuristic for figuring out whether something would be better as a method or a function?

I'm always torn about this. For example, I have this class:

code:
class Video_fileinfo():
    def __init__(self):
        self.codec = None
        self.vres = None
        self.hres = None

    def __str__(self):
        msg = []
        msg.append('---Video Info---')
        msg.append('Codec: %s' % self.codec)
        msg.append('Resolution: %sx%s' % (self.hres, self.vres))
        return '\n'.join(msg)
I've got this function which uses an external tool to get the codec and resolution info:

code:
def build_video_object(path):
    vid_obj = Video_fileinfo()
    codec_cmd = "--inform=General;%Video_Format_WithHint_List%"
    hres_cmd = "--inform=Video;%Width%"
    vres_cmd = "--inform=Video;%Height%"

    cmd = [minfo, codec_cmd, path]
    vid_obj.codec = exec_n_return(cmd).strip()

    cmd = [minfo, hres_cmd, path]
    vid_obj.hres = exec_n_return(cmd).strip()

    cmd = [minfo, vres_cmd, path]
    vid_obj.vres = exec_n_return(cmd).strip()
    return vid_obj
Would it be better to modify the class so that you pass it a path when instantiating it and use a method to get the info, or is it better to have the function set the attributes on the object?

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.

Thermopyle posted:

What's a good heuristic for figuring out whether something would be better as a method or a function?

Would it be better to modify the class so that you pass it a path when instantiating it and use a method to get the info, or is it better to have the function set the attributes on the object?

If you are setting attributes on just a specific type of object, that should be a method of that object not a function. Let the class's __init__ method do all the initializing by passing it the path. It would also be nice to store the file path in the class as well. You could also make stuff like codec, vres and hres properties(using either the builtin or the decorator) with their own setters and getters if you were so inclined so that exec_n_return is only called once when you actually first try and get the attribute not on initialization.

tehk fucked around with this message at 19:07 on Dec 16, 2009

Adbot
ADBOT LOVES YOU

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

Thermopyle posted:

What's a good heuristic for figuring out whether something would be better as a method or a function?

Is it an intrinsic action on the abstraction itself or is it an action that uses the abstraction? That's what I use.

In your specific case, it seems that you want that function to be __init__ unless there are several ways to create the object in which case several such factory functions is the way to go.

  • Locked thread