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
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}}

Adbot
ADBOT LOVES YOU

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}}

leterip
Aug 25, 2004

BattleMaster posted:

I'm having a problem getting a script to work. I've traced the problem back to getopt returning two empty lists no matter what arguments are supplied to the script. Here's how it is being used:

code:
opts, args = getopt.getopt(sys.argv[1:], "bcsuo:", ["memspace=", "native-file="])
I actually didn't write the program this is used it (It's pmImgCreator.py for PyMite), but I'm pulling my hair out trying to get it to work. I've looked at the reference for getopt and everything seems right. Additionally no one else is complaining about it on the project's Google group. It just isn't working no matter what combination of arguments I've tried using it with. Even if I just tack a load of gibberish non-options onto the command line, args is empty.

Is getopt just plain broken in Windows? I've tried running it with Python 2.6.4 and even 2.5.4 with no luck.

Are you sure sys.argv[1:] has data in it? It seems likely to have data so that might be something easily overlooked. That same script works perfect for me on OS X.

leterip
Aug 25, 2004

deichkind42 posted:

Ok, does anyone know how to properly write windows filenames in python 2.7?

I've tried target_dir = r"d:/pythonbackup/" but that fucks everything up.
I need a detailed explanation because i have been googling this for 20 minutes and all the explanations on the web fail on my machine for some reason. :/

I've also tried double backslashes like "C:\\backup\\" but that just gives out a windows error that it can't find the dir (probably because of the double backslashes)

I recently saw a suggestion on solving this problem from here (it has a long write up on this problem). You do
code:
dir_name = os.path.normpath("c:/a_directory/")
and let it fix the forward slashes to backslashes.

leterip
Aug 25, 2004
code:
>>> data = range(9)
>>> n = 3
>>> for b in (data[i:i+n] for i in xrange(len(data) - n + 1)):
...     print b
... 
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]

leterip fucked around with this message at 16:17 on Jul 29, 2010

leterip
Aug 25, 2004

tef posted:

code:

>>> x = range(1,11)
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> zip(x[:], x[1:], x[2:])
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)]


Very nice. This is a version that generalizes to any n:

code:
>>> x = range(1, 11)
>>> n = 3
>>> zip(*(x[i:] for i in xrange(n)))
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)]

leterip
Aug 25, 2004
Why not just use append?

>>> usernames = []
>>> usernames.append("praxxis")
>>> usernames
['praxxis']
>>>

leterip
Aug 25, 2004
You could also write a simple generator.

code:
def stripped(iterable):
  for line in iterable:
    yield line.strip()

for line in stripped(lines):
  # do stuff

leterip
Aug 25, 2004

Suspicious Dish posted:

Except that's not what the for...else loop does. It's what it should do, though.
code:
>>> for x in []:
...     print "foo"
... else:
...     print "empty"
... 
empty
edit: Oops. If there is data it still does the else! So you're right.

leterip
Aug 25, 2004

Rocko Bonaparte posted:

I'm looking for some general advice on getting a Python REPL working in a GUI. I am doing some stuff with 3d, and kind of want a Python console to plop down when I hit tilde, like one would expect a console generally to be for stuff like that. Is there any existing stuff to do that in Python? I was hoping for some helpers for things like history and getting all the tab indent prompts correct. I had been through doing this somewhat manually in C# before, and found it to be really tedious. So I want to avoid having to start from scratch.

I did a little bit of Googling and if you can throw twisted in there you can use twisted.conch.stdio. Either python -m twisted.conch.stdio or just from twisted.conch import stdio; stdio.main() and you get a nice REPL (it even had syntax coloring for me!)

leterip
Aug 25, 2004

MeramJert posted:

Hold on, how does 169.254.13.24 get converted to the 14th and 25th words? I don't understand

Well, 0 is the 1st word, so 13 is the 14th word, and you get the picture.

leterip
Aug 25, 2004

Lister_of_smeg posted:

Just come across this little snippet of code.

code:
ret = execute(os.system, cmd)
if ret and ret != 0:
    raise Error("%s returned %d" % (cmd, ret))
Am I missing something or is that if statement a bit silly? If ret was 0 it wouldn't evaluate to true.
For any number, "if ret" implies "ret != 0", so yeah you don't need that second condition. But you can construct crazy objects that don't have that property, like
code:
class Duck(object):
    def __ne__(self, o):
        return o != 0
d = Duck()
so "if d" would evaluate to true, but "d != 0" would evaluate to false. Thus, "if d" does not imply "d != 0". Obviously this is contrived and not what's going on there (I hope), so in the case of things not specifically crafted to break your ideas, like return codes from a command (assumably numbers), you're right.

leterip
Aug 25, 2004
Your solution doesn't merge them in linear time. The sorted call runs in O(n logn) time.

leterip
Aug 25, 2004

tef posted:

Despite this, people will tell you its performance without profiling it. Don't listen to these people, they are bad people. (also they do not know how python's sort works)

You guys might enjoy finding out how sort works in python :v: http://en.wikipedia.org/wiki/Timsort

Oh right, I forgot Timsort is amazing and uses ranges of already sorted data to run quicker. Thanks for pointing that out.

leterip
Aug 25, 2004

Munkeymon posted:

What am I missing?

If your input has no elements, i is never created.

Python code:
>>> def foo():
...     for i in []:
...             pass
...     else:
...             print i
... 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in foo
UnboundLocalError: local variable 'i' referenced before assignment

leterip
Aug 25, 2004

Suspicious Dish posted:

That would make bar(None) behave wrong. I'm not sure what Bodhi wants, though.

How so? Seems like bar(None) would behave just like foo(None) would.

leterip
Aug 25, 2004

PiotrLegnica posted:

bar uses None as default argument, which is supposed to correspond to calling foo with a defaulted argument. But foo doesn't use None for that, so now semantics have changed.
Uh, in the code he was responding to, bar was defined as def bar(*args, **kwargs). I don't see a default argument there. :confused:

leterip
Aug 25, 2004

PiotrLegnica posted:

That code is a response to this:

Yeah but that code was a completely different definition. I guess I just got confused because I thought the code he quoted didn't have the problem he was describing.

leterip
Aug 25, 2004

tef posted:

javascript/json only has double precision floating point

That's just javascript. json as a spec allows arbitrary sized integers/decimals.

Adbot
ADBOT LOVES YOU

leterip
Aug 25, 2004

yaoi prophet posted:

What's the idiomatic way for initializing a bunch of variables to the same value without that kind of sharing?

I might do something like

Python code:
x, y, z = (thinger() for _ in xrange(3))
I'd be interested to hear other options.

  • Locked thread