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
Clandestine!
Jul 17, 2010
The guide that I'm using is telling me that I can use the 'sort' and 'item' functions to alphabetize my output, but since it's not working AT ALL, I guess I'm messing something up. Your code, however, makes much more sense than mine ever did (and I was not aware of the 'sorted' function or defaultDict class, obviously, so thanks for teaching me that!).

Adbot
ADBOT LOVES YOU

TasteMyHouse
Dec 21, 2006

Clandestine! posted:

The guide that I'm using is telling me that I can use the 'sort' and 'item' functions to alphabetize my output, but since it's not working AT ALL, I guess I'm messing something up. Your code, however, makes much more sense than mine ever did (and I was not aware of the 'sorted' function or defaultDict class, obviously, so thanks for teaching me that!).

code:

>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__',
 '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', 
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', 
'__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault',
 'update', 'values']
There is no sort method of python dictionaries. If your guide tells you there is, it is wrong. Maybe you're getting lists and dictionaries confused? There's also no method called "item", though there is one called "items" that may be what you're referring to.

this page explains how all the dictionary methods work.

xtal
Jan 9, 2011

by Fluffdaddy
The dict itself can't be sorted, but it can be represented as two lists (keys and/or items) and sorted thereby.

e: Didn't realize tripwire's post included the exact same code I posted!
e: V :(

xtal fucked around with this message at 20:33 on Jun 26, 2011

German Joey
Dec 18, 2004

NOISIA posted:

Couldn't that be accomplished with this? It's absolutely not Pythonic, but.

code:
for word in sorted(word_counts.keys()):
  print word, word_counts[word]
Tell me if I'm understanding you incorrectly.

what exactly is not "Pythonic" in this code? it's perfectly fine.

Lurchington
Jan 2, 2003

Forums Dragoon

German Joey posted:

what exactly is not "Pythonic" in this code? it's perfectly fine.

I'd say it'd be more pythonic to use an iterator whenever you're doing a for-loop, and in general, It's not super pythonic to iterate over the indexes/keys of something and just use them to access the values of that key/index.

It's not bad code, but that's my take.

But yeah, on 2.7 and above, it's all about collections.Counter (which I think is what tripwire meant): http://docs.python.org/dev/library/collections.html#collections.Counter

chemosh6969
Jul 3, 2004

code:
cat /dev/null > /etc/professionalism

I am in fact a massive asswagon.
Do not let me touch computer.

German Joey posted:

what exactly is not "Pythonic" in this code? it's perfectly fine.

There's no comments with quotes from Monty Python.

Plastic Snake
Mar 2, 2005
For Halloween or scaring people.
So I've got this function:
code:
def letterCount(argString=sys.argv[1]):
    """
    This function runs a count on the string passed as a command line argument.
    It returns a dictionary of the results.
    """
    letterCounts = {}
    
    for letter in argString.lower():
        letterCounts[letter] = letterCounts.get(letter, 0) + 1
    return letterCounts
taking one argument that defaults to a command-line input. It works fine, except if I want to call it in another program, like this:
code:
import letter_counts.py

def readFile():
    f = open(alice_in_wonderland.txt, r)
    letterCounts = letterCount(f)
    tablePrint(letterCounts)
Here I'm calling it on the file, but it complains about sys.argv[1] being an out of range index because I'm not calling a command line argument. Can I get around this?

Thermopyle
Jul 1, 2003

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

Plastic Snake posted:

So I've got this function:
code:
def letterCount(argString=sys.argv[1]):
    """
    This function runs a count on the string passed as a command line argument.
    It returns a dictionary of the results.
    """
    letterCounts = {}
    
    for letter in argString.lower():
        letterCounts[letter] = letterCounts.get(letter, 0) + 1
    return letterCounts
taking one argument that defaults to a command-line input. It works fine, except if I want to call it in another program, like this:
code:
import letter_counts.py

def readFile():
    f = open(alice_in_wonderland.txt, r)
    letterCounts = letterCount(f)
    tablePrint(letterCounts)
Here I'm calling it on the file, but it complains about sys.argv[1] being an out of range index because I'm not calling a command line argument. Can I get around this?

code:
def letterCount(argString=None):
    """
    This function runs a count on the string passed as a command line argument.
    It returns a dictionary of the results.
    """
    if argString is None:
        try:
            argString=sys.argv[1]
        except:
            return
    
    
    letterCounts = {}
    
    for letter in argString.lower():
        letterCounts[letter] = letterCounts.get(letter, 0) + 1
    return letterCounts
Not sure exactly if this fits your needs...

tripwire
Nov 19, 2004

        ghost flow
I realize i'm being overly nitpicky, but it always irks me to see camelcase in python.

Also nitpicky (and I realize you are probably just writing a small one off script), but I would be careful about your choice of keyword argument defaults- usually you try to write functions like the one you are talking about so that they're completely agnostic about everything not immediately related to their role. In other words, you should avoid whenever possible having the behaviour of a function definition depend on module level variables, especially things like the position of a command line argument.

The function really doesn't need to know anything about the position of module level variables like sys.argv- if you want it to use those values, just feed them in explicitly in your function call.

Another related note, be especially wary of constructions like this:
code:
def foo(x,container = []):
    container.append(x)
    return container
A lot of people would think in that case that the function would try to call append on whichever object was passed in as a second argument, and in the absence of one make a new list. This is not what python would do. The function definition is only executed once, so that list used for the default argument for container only gets created once (the default arguments are attached to the function object itself. Check foo.func_defaults if you don't believe me!).






The Counter class in python2.7 and newer simplifies it even further:
code:
from collections import Counter
def character_tally(input_string):
    counter = Counter()
    for letter in input_string:
        counter[letter] += 1
    
    return counter

tripwire fucked around with this message at 00:05 on Jul 1, 2011

Thermopyle
Jul 1, 2003

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

tripwire posted:

I realize i'm being overly nitpicky, but it always irks me to see camelcase in python.

Also nitpicky (and I realize you are probably just writing a small one off script), but I would be careful about your choice of keyword argument defaults- usually you try to write functions like the one you are talking about so that they're completely agnostic about everything not immediately related to their role.

In other words, you should probably try when possible not to couple things like the position of a command line argument to the behaviour of a function definition. The function really doesn't need to know anything about the position of module level variables like sys.argv- if you want it to use those values, just feed them in explicitly in your function call.



The Counter class in python2.7 and newer simplifies it even further:
code:
from collections import Counter
def character_tally(input_string):
    counter = Counter()
    for letter in input_string:
        counter[letter] += 1
    
    return counter

This is all true, and I'm glad you said it. I was going to but figured I was just being overly nitpicky. :D

Captain Capacitor
Jan 21, 2008

The code you say?
Posted this in the Minecraft thread, but I felt my efforts may be appreciated here too.

Scaevolus
Apr 16, 2007

Captain Capacitor posted:

Posted this in the Minecraft thread, but I felt my efforts may be appreciated here too.



Someone already implemented a beanshell repl, which integrates more easily with minecraft itself, but this is still neat.

Captain Capacitor
Jan 21, 2008

The code you say?

Scaevolus posted:

Someone already implemented a beanshell repl, which integrates more easily with minecraft itself, but this is still neat.

Ah, neat. I'm building scriptable blocks and adapting ModLoader to support Jython classes.

Jarl
Nov 8, 2007

So what if I'm not for the ever offended?
What does it mean when the Python Shell GUI for Windows writes a line of "---------------------------------", and then just stops doing anything, although the program is still running? When this happened the program would stop using the CPU, but the RAM consumption didn't fall until I killed the pythonw.exe process (which was after I killed the shell process).

I was not into swap file territory.

EDIT:
I just realized that it probably is because the Python Windows implementation I'm running is 32-bit.

EDIT:
Yep, 64-bit cleared that right up.

Jarl fucked around with this message at 14:41 on Jul 1, 2011

Lysidas
Jul 26, 2002

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

tripwire posted:

The Counter class in python2.7 and newer simplifies it even further:
code:
from collections import Counter
def character_tally(input_string):
    counter = Counter()
    for letter in input_string:
        counter[letter] += 1
    
    return counter

:raise:
code:
from collections import Counter
def character_tally(input_string):
    return Counter(input_string)

tripwire
Nov 19, 2004

        ghost flow

Lysidas posted:

:raise:
code:
from collections import Counter
def character_tally(input_string):
    return Counter(input_string)

Even better.

Opinion Haver
Apr 9, 2007

Lysidas posted:

:raise:
code:
from collections import Counter
def character_tally(input_string):
    return Counter(input_string)

code:
from collections import Counter
character_tally = Counter
:v:

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

yaoi prophet posted:

code:
from collections import Counter
character_tally = Counter
:v:

code:
from collections import Counter as character_tally
Do I win?

Graviton v2
Mar 2, 2007

by angerbeet
Im a newb to Python, been working in it for the past 2 months, pleased with it getting things done, but ive got a couple of newb questions which this might be the place for.

Imports. If ive got say 2 modules which both import 're' (regular expressions module) for example is it clever enough to ... you know what while typing that i think realised the answer, the pyc in the python install dir will be be the one both modules access yeah?

Imports again, lots of sample code examples use 'Import [object] from [library/module]'. Is there any disadvantage to just saying 'Import [library/module]' and having it all unless you are making something that has to be mega small?

Error handling. While I really do love working in Python I find the feedback from it can be next to useless. Simple example:

code:
class aclass(x,y)  
    def __init__
        cx = x
        cy = y
    def aclassmethod(self)
        print z

o = aclass(1,2)
o.aclassmethod
Will not work cos I forgot the brackets. And I get no feedback at all

code:
o.aclassmethod()
Will work fine though. Maybe ive just been imersed in MS languages for so long that ive come to expect to have the animation tools and stuff but that seems pretty unforgiving to just have not feedback. I spent half an hour last week cos i accidently deleted a * on a method arg. Are there any 'stack trace' tools I can use? Im seeming to have to spend allot of time writing to logfiles to debug.

Thanks guys if you got anything on those questions.

German Joey
Dec 18, 2004

Profane Obituary! posted:

code:
from collections import Counter as character_tally
Do I win?

lol, for all the complaints about "Pythonic" code, y'all sure are acting like a bunch of Perl geeks. :laugh:

German Joey
Dec 18, 2004

Graviton v2 posted:

Im a newb to Python, been working in it for the past 2 months, pleased with it getting things done, but ive got a couple of newb questions which this might be the place for.

Imports. If ive got say 2 modules which both import 're' (regular expressions module) for example is it clever enough to ... you know what while typing that i think realised the answer, the pyc in the python install dir will be be the one both modules access yeah?

Imports again, lots of sample code examples use 'Import [object] from [library/module]'. Is there any disadvantage to just saying 'Import [library/module]' and having it all unless you are making something that has to be mega small?

Error handling. While I really do love working in Python I find the feedback from it can be next to useless. Simple example:

code:
class aclass(x,y)  
    def __init__
        cx = x
        cy = y
    def aclassmethod(self)
        print z

o = aclass(1,2)
o.aclassmethod
Will not work cos I forgot the brackets. And I get no feedback at all

code:
o.aclassmethod()
Will work fine though. Maybe ive just been imersed in MS languages for so long that ive come to expect to have the animation tools and stuff but that seems pretty unforgiving to just have not feedback. I spent half an hour last week cos i accidently deleted a * on a method arg. Are there any 'stack trace' tools I can use? Im seeming to have to spend allot of time writing to logfiles to debug.

Thanks guys if you got anything on those questions.

it's not that it didn't give you feedback for an error, its that
code:
o.aclassmethod
is a valid statement. a simple print statement would have told you this. for instance, try this bit of code:

code:
print o.aclassmethod
z = o.aclassmethod
print z
print z()
so you see, in python, methods and functions are also objects, an extremely important feature of the language which allows some rather advanced flow control. anyways, that's neither here nor there. your real problem here is that you don't seem to know how to debug. the type of errors you're having problems with here don't really need any kind of advanced tools, just careful inspection of what your code is actually doing. i mean, that's some pretty basic stuff. if you're feeling too lordly for print, then you can take a look at the logging module.

as far as imports go, i'm not sure what you're talking about. a module that imports a file into its namespace still keeps its own namespace as sacred, of course. conflicts can unfortunately occur if you're trying to import two things into the same module that have the same name (although surely not with a builtin module like 're' ????), but you can resolve them by renaming them in the import like this:

code:
from whatever_cool_module import settings as cool_settings
import decimal as messimal
etc. maybe that will help you keep your head straight. it helps for me, at least. the code i'm working on now uses this all over the freaking place.

German Joey fucked around with this message at 18:34 on Jul 2, 2011

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

German Joey posted:

lol, for all the complaints about "Pythonic" code, y'all sure are acting like a bunch of Perl geeks. :laugh:

You take that back !

Opinion Haver
Apr 9, 2007

Profane Obituary! posted:

code:
from collections import Counter as character_tally
Do I win?

No, because now if you want to count something other than characters you still have to use character_tally. :colbert:

Graviton v2
Mar 2, 2007

by angerbeet

German Joey posted:

stuff
I was going to respond in an angry fashion to your smugness but after reading your post a couple of times it was actually very helpfull. So thanks (smartarse).

Hughlander
May 11, 2005

German Joey posted:

code:
print o.aclassmethod
z = o.aclassmethod
print z
print z()
so you see, in python, methods and functions are also objects, an extremely important feature of the language which allows some rather advanced flow control. anyways, that's neither here nor there. your real problem here is that you don't seem to know how to debug. the type of errors you're having problems with here don't really need any kind of advanced tools, just careful inspection of what your code is actually doing. i mean, that's some pretty basic stuff. if you're feeling too lordly for print, then you can take a look at the logging module.


Something I just thought of while reading this and I can't seem to find from googling is: Given all of that, how do you specify the repr of a method? (IE: Implement/override __repr__(), __str__(), or __unicode__()?

German Joey
Dec 18, 2004

Graviton v2 posted:

I was going to respond in an angry fashion to your smugness but after reading your post a couple of times it was actually very helpfull. So thanks (smartarse).

well, i mean, i was just responding in kind. the tone of your post sounded to me like "Wow, can't believe I'm stuck in this backwater hick town. You guys seriously poo poo in holes... outside? Back in the city, where I'm from, we got these 'thangs' called 'toilets', can't believe you've never heard of 'em. How are you supposed to live like this?"

there's all kinds of crazy rear end IDEs for python if you want something more like you're used to with .net or whatever you meant. i think there's even an eclipse plugin if you don't mind your computer throbbing and near-bursting at the seams just from editing text.

you can also use the interactive shell to test code that you might be unfamiliar with; i just learned python myself about a year ago, coming from a background in Perl and Java where, (especially compared to Perl), everything is The Same But Different, and still find myself using the shell to test out simple python mechanics.

Graviton v2
Mar 2, 2007

by angerbeet

German Joey posted:

well, i mean, i was just responding in kind. the tone of your post sounded to me like "Wow, can't believe I'm stuck in this backwater hick town. You guys seriously poo poo in holes... outside? Back in the city, where I'm from, we got these 'thangs' called 'toilets', can't believe you've never heard of 'em. How are you supposed to live like this?"

there's all kinds of crazy rear end IDEs for python if you want something more like you're used to with .net or whatever you meant. i think there's even an eclipse plugin if you don't mind your computer throbbing and near-bursting at the seams just from editing text.

you can also use the interactive shell to test code that you might be unfamiliar with; i just learned python myself about a year ago, coming from a background in Perl and Java where, (especially compared to Perl), everything is The Same But Different, and still find myself using the shell to test out simple python mechanics.
Yeah a .net style ide would be awesome but you know what I think I can do without it. Having those tools actually changes the way you work I think, you do debugging/coding on the fly. Im actually enjoying getting away from that mindset. Makes you pay more attention to detail :)

And I only discovered the fact that you could use the shell to try stuff out a couple of weeks ago, that really should have been one of the first things my boss told me about!

In praise of the language I have to say that amazed how easy it was to implement RPC-XML stuff, ive had a fear of network programming since I did a contract 5'ish years ago where I had to use MS DCOM. There is no loving question at all about which is easier.

German Joey
Dec 18, 2004

Hughlander posted:

Something I just thought of while reading this and I can't seem to find from googling is: Given all of that, how do you specify the repr of a method? (IE: Implement/override __repr__(), __str__(), or __unicode__()?

well, that's not so straightforward. it's pretty crazy to even want to do this, so you better believe the solution is gonna be pretty crazy too.

so, the obvious way would be to do this is this:

code:
class A():
   def z(self):
       print "z"

q = A()
print q.z

def funky(self):
   print "asfasdfdsf"

q.z.__repr__ = funky
print q.z
however, guess what! ok, i'll tell you - that doesn't work, because __repr__ is read only! woops, too bad! it is fairly reasonable that it is this way since it is a deep core builtin type, after all. however, that doesn't answer your question. next, it doesn't even seem that you can subclass from instancemethod (which is the base class for methods). even if you could, it would be pretty awkward handling. so, instead, you'll have to something crazy, like this:

code:
   import new
   q.z = magicdelegate(new.instancemethod(funky, q, A))
   q.z.__repr__ = funky
using the bongtastic magicdelegate function that tef developed here:

http://forums.somethingawful.com/showthread.php?threadid=2675400&pagenumber=134&perpage=40#post385293739

anyways, good luck! :2bong:

German Joey fucked around with this message at 19:20 on Jul 2, 2011

TK422
Dec 22, 2007

I hate being right
why there isn't a module offering a threading pool which behaves this way:

code:
create a pool of 5 threads

if number of idle threads > 0: task is submitted instantly

if number of idle threads == 0: calling thread blocks until a thread is available
multiprocessing.Pool from standard library does not behave this way. It never blocks, letting you submit tons of tasks.

I had to resort to a custom made thread Pool, which is way more confortable: http://pastebin.com/xZ0j5cfi

German Joey
Dec 18, 2004

TK422 posted:

why there isn't a module offering a threading pool which behaves this way:

code:
create a pool of 5 threads

if number of idle threads > 0: task is submitted instantly

if number of idle threads == 0: calling thread blocks until a thread is available
multiprocessing.Pool from standard library does not behave this way. It never blocks, letting you submit tons of tasks.

I had to resort to a custom made thread Pool, which is way more confortable: http://pastebin.com/xZ0j5cfi

uh, just use Queue, its exactly for this. or maybe i'm confused as to what you're trying to do?

Lurchington
Jan 2, 2003

Forums Dragoon
My interpretation is that the desire is to have the guarantee that as soon as a job is submitted, it was be worked immediately, or it will block until it's worked immediately.

So even if Queue has a maxsize set (link), it won't block unless it hits that max size, which doesn't necessarily guarantee the kind of thing outline above.

That said, Queue is definitely how this (this being having multiple workers attack things) kind of thing is normally done

Graviton v2
Mar 2, 2007

by angerbeet
You are looking for a mutex then i think?

e: looks like they have it: http://docs.python.org/library/mutex.html

Graviton v2 fucked around with this message at 07:01 on Jul 3, 2011

TURTLE SLUT
Dec 12, 2005

Disclaimer: I just started learning Python and PyQt from a background of C++ and Java, with no graphical applications to speak, so I'm pretty dumb about everything.

I'm making a simple little program for checking the validity of XML files with a chosen XML Schema as an exercise for myself. The program is pretty much working fine right now, with one little annoyance: If I try to validate a valid XML with a faulty Schema, or validate a faulty XML with a valid Schema, I get an error printed into the console about what is wrong with the Schema and/or XML.

This is a problem because I already have a pop-up window notifying of any errors and I don't know how to remove the console messages - the errors don't seem to be Python exceptions at all so a try block doesn't do anything. I googled around a bit and it seems a possible fix would involve hooks into sys.excepthook or something complicated like that, and would possibly screw up other error messages, and I didn't really understand the fix proposed.

It seems like it's a fairly simple thing that should have a simple fix, since why would PyQt have random stuff printed into the console and no way to stop it?

I am using Python 2.7 with PyQt4, on Windows 7. The specific methods that make the errors are QtXmlPatterns.QXmlSchema.isValid and QtXmlPatterns.QXmlSchemaValidator.validate.

Graviton v2
Mar 2, 2007

by angerbeet

Cukel posted:

Disclaimer: I just started learning Python and PyQt from a background of C++ and Java, with no graphical applications to speak, so I'm pretty dumb about everything.

I'm making a simple little program for checking the validity of XML files with a chosen XML Schema as an exercise for myself. The program is pretty much working fine right now, with one little annoyance: If I try to validate a valid XML with a faulty Schema, or validate a faulty XML with a valid Schema, I get an error printed into the console about what is wrong with the Schema and/or XML.

This is a problem because I already have a pop-up window notifying of any errors and I don't know how to remove the console messages - the errors don't seem to be Python exceptions at all so a try block doesn't do anything. I googled around a bit and it seems a possible fix would involve hooks into sys.excepthook or something complicated like that, and would possibly screw up other error messages, and I didn't really understand the fix proposed.

It seems like it's a fairly simple thing that should have a simple fix, since why would PyQt have random stuff printed into the console and no way to stop it?

I am using Python 2.7 with PyQt4, on Windows 7. The specific methods that make the errors are QtXmlPatterns.QXmlSchema.isValid and QtXmlPatterns.QXmlSchemaValidator.validate.
Are you using the 'simplexml parsing' lib, im not on the work box atm so my terminology might be off but that lib deffo hates any non-readable ascii, base64.encode/base64.decode might help. Maybe.

TURTLE SLUT
Dec 12, 2005

Graviton v2 posted:

Are you using the 'simplexml parsing' lib, im not on the work box atm so my terminology might be off but that lib deffo hates any non-readable ascii, base64.encode/base64.decode might help. Maybe.
I'm using PyQt libraries pretty much exclusively, QtXml and QtXmlPatterns. And sorry if I was unclear, the problem isn't that it detects something being wrong with the XML or the Schema, since that's what I want it to do. I just don't want it to print the problem to console, since I'd like to make my own implementation how to deal with problems or exceptions, and there doesn't seem to be any simple way to stop it from printing to console.

Graviton v2
Mar 2, 2007

by angerbeet

Cukel posted:

I'm using PyQt libraries pretty much exclusively, QtXml and QtXmlPatterns. And sorry if I was unclear, the problem isn't that it detects something being wrong with the XML or the Schema, since that's what I want it to do. I just don't want it to print the problem to console, since I'd like to make my own implementation how to deal with problems or exceptions, and there doesn't seem to be any simple way to stop it from printing to console.
Ah ok understand you now, dont have an answer for you now though though thats something id like to know about as well. I wonder if there are any args on the python exe which can change its output behavior?

FoiledAgain
May 6, 2007

Cukel posted:

there doesn't seem to be any simple way to stop it from printing to console.

Is this what you want to do maybe?

code:
import sys
sys.stdout = open(myfile,'a')
And you can "reset" the value this way: sys.stdout = __stdout__


I also have my own question. I'm working on an agent-based simulation, and I'm stuck at how to write a particular function. Here's the scenario:

I have two agents, call them Sender and Reciever. The Sender chooses two items x,y from a set of items and combines them into z, which is sent to the Reciever. On the basis of z, the Receiver should be able to work out what x and y are. It would be ideal if this could be done imperfectly - I actually want the Receiver to occasionally deduce x or y incorrectly. The items x and y are generated from a set of binary features, they could be represented as a sequence of 1s and 0s.

I have no formal background in CS, so maybe this is something standard (it seems like a common problem anyway). I'd really like to solve this myself, I'm just not sure where to start: any useful imports or terms I should google?

Graviton v2
Mar 2, 2007

by angerbeet
There is a library/module called pickle I noticed the other day which seems to be basically an object serializer.

Computer viking
May 30, 2011
Now with less breakage.

FoiledAgain posted:

I also have my own question. I'm working on an agent-based simulation, and I'm stuck at how to write a particular function. Here's the scenario:

I have two agents, call them Sender and Reciever. The Sender chooses two items x,y from a set of items and combines them into z, which is sent to the Reciever. On the basis of z, the Receiver should be able to work out what x and y are. It would be ideal if this could be done imperfectly - I actually want the Receiver to occasionally deduce x or y incorrectly. The items x and y are generated from a set of binary features, they could be represented as a sequence of 1s and 0s.

I have no formal background in CS, so maybe this is something standard (it seems like a common problem anyway). I'd really like to solve this myself, I'm just not sure where to start: any useful imports or terms I should google?


Hm, that's closely related to en-/decryption: "Given a message encrypted with a key, try to guess the message (and the key)". The chance of successfully guessing starts off at 0% if the key is at least as long as the message, rising towards but not hitting 100% as it gets shorter.

I'm not sure what specific terms apply here, though.

Adbot
ADBOT LOVES YOU

Nippashish
Nov 2, 2005

Let me see you dance!

FoiledAgain posted:

I have two agents, call them Sender and Reciever. The Sender chooses two items x,y from a set of items and combines them into z, which is sent to the Reciever. On the basis of z, the Receiver should be able to work out what x and y are. It would be ideal if this could be done imperfectly - I actually want the Receiver to occasionally deduce x or y incorrectly. The items x and y are generated from a set of binary features, they could be represented as a sequence of 1s and 0s.

"Error correcting code" is probably a good search term to start with.

I'm imagining a process like this:

1. Sender combines x and y in a reversible way to get z (e.g. concatenate their bitstring representations)
2. Sender encodes z using an error correcting code.
3. Receiver gets z' which is z + some flipped bits. Choose the number of flipped bits randomly around the error correction threshold of the code you're using. If you pick below the threshold then Receiver can recover z from z' and thus decode x and y correctly, if you pick above the threshold then z will not be recovered and the x and y Receiver sees will not be correct. Adjust the amount of noise to control how often Receiver makes mistakes.

  • Locked thread