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
Dren
Jan 5, 2001

Pillbug
Ah, I just remembered. Classmethods are not really pythonic. They're kind of a kludge for implementing something like a static class method in Java/C++. The pythonic way to do static class methods is to make them module methods.

So in this case you'd have a Record module with a read method. Inside the Record module there would be a Record class. Objects of the Record class type would be returned by the Record module's read method.

Adbot
ADBOT LOVES YOU

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
classmethods are very Pythonic, especially as factory methods. staticmethods are not.

Modern Pragmatist
Aug 20, 2008

Dren posted:


This is an outline of what you need. I put the dictionary/enum in there as an example if you feel that something like that would be convenient. You can pass around integer values or whatever is actually in the field if you want.

My read methodology and while loop could probably be more pythonic, I've been writing C for a while. You should probably use the with syntax for the open. Handle IO errors in the scope of the file open, not inside the Record class. In the Record class it'd be a good idea to throw an error if you see an incomplete record or an enum value of an unknown type. You might want to store the records in something other than a list for access purposes. You might also want to implement some comparator operators and @total_ordering in the Record class so that you can easily sort it with sorted(). http://docs.python.org/py3k/library/functools.html?highlight=functools#functools

If you have records of a type other than string, you could rework decode to properly decode them and call decode on everything.

Excellent. Thanks for your help with this. This helps me have a better grasp on the way to tackle this.

One design question though, would it make more sense to subclass Record with something else and have the decode() method there? I have things like integers and lists that won't necessarily be able to be decoded. The other option would be to keep decode() as a method of Record and just return the original value if it is of a datatype that doesn't need to be decoded, right? The second option seems simpler, but I'm not sure if it's confusing/worse to have a decode method for an integer-containing record.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
Have you considered using something like pydicom? I've never used it and can't vouch for its functionality, but I get the feeling you're working on a solved problem (at least for most intents and purposes).

Dren
Jan 5, 2001

Pillbug

Modern Pragmatist posted:

Excellent. Thanks for your help with this. This helps me have a better grasp on the way to tackle this.

One design question though, would it make more sense to subclass Record with something else and have the decode() method there? I have things like integers and lists that won't necessarily be able to be decoded. The other option would be to keep decode() as a method of Record and just return the original value if it is of a datatype that doesn't need to be decoded, right? The second option seems simpler, but I'm not sure if it's confusing/worse to have a decode method for an integer-containing record.

It certainly makes sense to subclass Record and overload the decode operator. That said, I wouldn't do it.

It sounds like for most of your data you don't need to do the decode in a second pass, you can decode it as it is unpacked because its decoding depends on its datatype. You could set up the factory method to return two types of records, UnknownEncRecords and KnownRecords. KnownRecords would have their data decoded right in the factory method. UnknownEncRecords would store binary data that is decoded after the encoding is determined.

You could do something like not give KnownRecords a decode method but give UnknownEncRecords a decode method. Then, after all records have been read from the file, you could loop through them all and if hasattr(rec, 'decode') do the decode.

There are a dozen ways to deal with this design problem in Python. My least favorite, in this case, would be to subclass for each of your datatypes. It'd just be a ton of code and for what? A bunch of decode methods that mostly do nothing? Bleh.

Something I am given to is to create dictionary for the enum and do something like this:
code:
DataTypes = {
  1 : ('LIST', unpacklist),
  2 : ('INTEGER', ">I"),
  ...
}
Where unpacklist is a method that gets called in order to do the unpacking. The integer gets a format string that can be an argument to struct.unpack(). There's no big advantage to doing this instead of say, a big if/else, I just like it.

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe
Just wanted to toss my two cents, as I've been heavily programming in Python at work.

Holy poo poo blasting god drat! I mean, I knew about the power of interpreted/scripting languages, but you never can really appreciate that power until you actually program in it. Something like reading a file is a complete :psyduck:, coming from a heavy Java, C, and C# background. Two lines to open a file, loop through and read each line, AND close it? :fap:

No, :flashfap:

ufarn
May 30, 2009

pliable posted:

Just wanted to toss my two cents, as I've been heavily programming in Python at work.

Holy poo poo blasting god drat! I mean, I knew about the power of interpreted/scripting languages, but you never can really appreciate that power until you actually program in it. Something like reading a file is a complete :psyduck:, coming from a heavy Java, C, and C# background. Two lines to open a file, loop through and read each line, AND close it? :fap:

No, :flashfap:
On the other hand, it really spoils you, when you suddenly start reading pseudocode in C in algorithm books.

Python is as close to pseudocode as it gets.

Emacs Headroom
Aug 2, 2003

pliable posted:

Just wanted to toss my two cents, as I've been heavily programming in Python at work.

Holy poo poo blasting god drat! I mean, I knew about the power of interpreted/scripting languages, but you never can really appreciate that power until you actually program in it. Something like reading a file is a complete :psyduck:, coming from a heavy Java, C, and C# background. Two lines to open a file, loop through and read each line, AND close it? :fap:

No, :flashfap:

Don't know if you've come across this pattern yet. Say you have a file with two columns of numbers, and you want to read them into a list:

Python code:
a = []
with open('numbers.dat', 'r') as file:
    for line in file:
        a.append([int(x) for x in line.split()])
The 'with' keyword will close the file at the end of the block, so you don't have to explicitly.

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe

ufarn posted:

On the other hand, it really spoils you, when you suddenly start reading pseudocode in C in algorithm books.

Python is as close to pseudocode as it gets.

I completely agree. I'm going to have to return to C#/Java land soon, so it'll be interesting to make that switch. I've already broken the habit of putting semi-colons at the end of my statements :(

Emacs Headroom posted:

Don't know if you've come across this pattern yet. Say you have a file with two columns of numbers, and you want to read them into a list:

Python code:
a = []
with open('numbers.dat', 'r') as file:
    for line in file:
        a.append([int(x) for x in line.split()])
The 'with' keyword will close the file at the end of the block, so you don't have to explicitly.

That is precisely what I was talking about :). Minus the append line and list assignment, it's a mere two lines. When I learned you don't even have to check for EOF, my head exploded.

Captain Capacitor
Jan 21, 2008

The code you say?
I recently stumbled upon this and while quite simple I can't help but marvel at the results.

Python code:
_                                      =   (
                                        255,
                                      lambda
                               V       ,B,c
                             :c   and Y(V*V+B,B,  c
                               -1)if(abs(V)<6)else
               (              2+c-4*abs(V)**-0.4)/i
                 )  ;v,      x=1500,1000;C=range(v*x
                  );import  struct;P=struct.pack;M,\
            j  ='<QIIHHHH',open('M.bmp','wb').write
for X in j('BM'+P(M,v*x*3+26,26,12,v,x,1,24))or C:
            i  ,Y=_;j(P('BBB',*(lambda T:(T*80+T**9
                  *i-950*T  **99,T*70-880*T**18+701*
                 T  **9     ,T*i**(1-T**45*2)))(sum(
               [              Y(0,(A%3/3.+X%v+(X/v+
                               A/3/3.-x/2)/1j)*2.5
                             /x   -2.7,i)**2 for  \
                               A       in C
                                      [:9]])
                                        /9)
                                       )   )
Source

And some high-resolution results:

huhu
Feb 24, 2006
I've just started watching the MIT lectures found here:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008

The videos are not clear enough to view the code. Is there some better quality video or do they realize their error and get a better quality video camera or something? Not trying to decipher blurry code.

Captain Capacitor
Jan 21, 2008

The code you say?

huhu posted:

I've just started watching the MIT lectures found here:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008

The videos are not clear enough to view the code. Is there some better quality video or do they realize their error and get a better quality video camera or something? Not trying to decipher blurry code.

You can look at the course readings here which has most of the material for the course.

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe

Captain Capacitor posted:

I recently stumbled upon this and while quite simple I can't help but marvel at the results.

Python code:
_                                      =   (
                                        255,
                                      lambda
                               V       ,B,c
                             :c   and Y(V*V+B,B,  c
                               -1)if(abs(V)<6)else
               (              2+c-4*abs(V)**-0.4)/i
                 )  ;v,      x=1500,1000;C=range(v*x
                  );import  struct;P=struct.pack;M,\
            j  ='<QIIHHHH',open('M.bmp','wb').write
for X in j('BM'+P(M,v*x*3+26,26,12,v,x,1,24))or C:
            i  ,Y=_;j(P('BBB',*(lambda T:(T*80+T**9
                  *i-950*T  **99,T*70-880*T**18+701*
                 T  **9     ,T*i**(1-T**45*2)))(sum(
               [              Y(0,(A%3/3.+X%v+(X/v+
                               A/3/3.-x/2)/1j)*2.5
                             /x   -2.7,i)**2 for  \
                               A       in C
                                      [:9]])
                                        /9)
                                       )   )
Source

And some high-resolution results:


What in the mother gently caress? :psyduck:

I want to try this but, 18 minutes to process...:(

huhu
Feb 24, 2006

Captain Capacitor posted:

You can look at the course readings here which has most of the material for the course.

Just realized that they actually zoom in to the coding later in the video so all is well. Have another question though. In the video they do operations such as 9/5 equals 1 and 'a' < 3 equals false. I understand the reason for this but I'm using Python 2.0 which gives answers of 1.8 and "TypeError: unorderable types: str() < int()" Are they using Python 1? If not what is the difference between their setup and mine?

Captain Capacitor
Jan 21, 2008

The code you say?

pliable posted:

What in the mother gently caress? :psyduck:

I want to try this but, 18 minutes to process...:(

Python code:
_                                      =   (
                                        255,
                                      lambda
                               V       ,B,c
                             :c   and Y(V*V+B,B,  c
                               -1)if(abs(V)<6)else
               (              2+c-4*abs(V)**-0.4)/i
                 )  ;v,      x=360,240;C=range(v*x
                  );import  struct;P=struct.pack;M,\
            j  ='<QIIHHHH',open('M.bmp','wb').write
for X in j('BM'+P(M,v*x*3+26,26,12,v,x,1,24))or C:
            i  ,Y=_;j(P('BBB',*(lambda T:(T*80+T**9
                  *i-950*T  **99,T*70-880*T**18+701*
                 T  **9     ,T*i**(1-T**45*2)))(sum(
               [              Y(0,(A%3/3.+X%v+(X/v+
                               A/3/3.-x/2)/1j)*2.5
                             /x   -2.7,i)**2 for  \
                               A       in C
                                      [:9]])
                                        /9)
                                       )   )
This one took about 20 seconds on my machine. You can change the 'x=360,240' to adjust the resolution and how long it'll take to complete.

Edit: Also, PyPy really does make a difference.

Captain Capacitor fucked around with this message at 02:13 on Aug 26, 2012

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Too bad PyPy developers are sick of seeing mandelbrots already.

huhu
Feb 24, 2006
Another small question. I see that 25**.5==9**.5+16**.5 is false and I understand why. What is the correct way to work around this?

how!!
Nov 19, 2011

by angerbot

huhu posted:

Another small question. I see that 25**.5==9**.5+16**.5 is false and I understand why. What is the correct way to work around this?

25 ** .5 == 5
9 ** .5 == 3
16 ** .5 == 4

3 + 4 != 5

not sure what you mean by a work around

huhu
Feb 24, 2006

how!! posted:

25 ** .5 == 5
9 ** .5 == 3
16 ** .5 == 4

3 + 4 != 5

not sure what you mean by a work around

Oh gently caress, I think it's time for me to stop coding for the night I'm starting to lose it. Thanks for clarifying.

Edit:I swear I have a real question now.

The problem is:

quote:

A Pythagorean triplet is a set of three natural numbers, a b c, for which,

a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

Here is my code:
code:
a=0
b=0
c=0
for x in range(1,1000):
    a=x
    for y in range(1,1000):
        b=y
        for z in range(1,1000):
            c=z
            if a<b<c and a+b+c==1000:
                if a**2+b**2==c**2:
                    print(a,b,c)
It gets the answer but takes about 30 seconds to do so. What makes it so horribly inefficient? I thought that moving around the last three commands of a<b<c a+b+c==1000 and a**2+b**2==c**2 to their own if statements would make it faster but I don't think so.

huhu fucked around with this message at 18:04 on Aug 26, 2012

tef
May 30, 2004

-> some l-system crap ->

Captain Capacitor posted:

I recently stumbled upon this and while quite simple I can't help but marvel at the results.

Python code:
_                                      =   (
                                        255,
                                      lambda
                               V       ,B,c
                             :c   and Y(V*V+B,B,  c
                               -1)if(abs(V)<6)else
               (              2+c-4*abs(V)**-0.4)/i
                 )  ;v,      x=1500,1000;C=range(v*x
                  );import  struct;P=struct.pack;M,\
            j  ='<QIIHHHH',open('M.bmp','wb').write
for X in j('BM'+P(M,v*x*3+26,26,12,v,x,1,24))or C:
            i  ,Y=_;j(P('BBB',*(lambda T:(T*80+T**9
                  *i-950*T  **99,T*70-880*T**18+701*
                 T  **9     ,T*i**(1-T**45*2)))(sum(
               [              Y(0,(A%3/3.+X%v+(X/v+
                               A/3/3.-x/2)/1j)*2.5
                             /x   -2.7,i)**2 for  \
                               A       in C
                                      [:9]])
                                        /9)
                                       )   )
Source

And some high-resolution results:


This is beautiful :swoon:

FoiledAgain
May 6, 2007

huhu posted:

Oh gently caress, I think it's time for me to stop coding for the night I'm starting to lose it. Thanks for clarifying.

Edit:I swear I have a real question now.

The problem is:


Here is my code:
code:
a=0
b=0
c=0
for x in range(1,1000):
    a=x
    for y in range(1,1000):
        b=y
        for z in range(1,1000):
            c=z
            if a<b<c and a+b+c==1000:
                if a**2+b**2==c**2:
                    print(a,b,c)
It gets the answer but takes about 30 seconds to do so. What makes it so horribly inefficient? I thought that moving around the last three commands of a<b<c a+b+c==1000 and a**2+b**2==c**2 to their own if statements would make it faster but I don't think so.

These are small suggestions, but:

Don't use the extra variables of a,b,c. Just use the x,y,z from the loops, i.e just write if x+y+z==1000.

Put a quit() under the print. Right now it finds the correct number, prints it, and then just keeps on loopin'. You might be finding the the right number in the first 10 seconds, and then waiting the other 20 seconds for some needless looping to finish.

Hammerite
Mar 9, 2007

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

huhu posted:

Oh gently caress, I think it's time for me to stop coding for the night I'm starting to lose it. Thanks for clarifying.

Edit:I swear I have a real question now.

The problem is:


Here is my code:
code:
a=0
b=0
c=0
for x in range(1,1000):
    a=x
    for y in range(1,1000):
        b=y
        for z in range(1,1000):
            c=z
            if a<b<c and a+b+c==1000:
                if a**2+b**2==c**2:
                    print(a,b,c)
It gets the answer but takes about 30 seconds to do so. What makes it so horribly inefficient? I thought that moving around the last three commands of a<b<c a+b+c==1000 and a**2+b**2==c**2 to their own if statements would make it faster but I don't think so.

There is no reason for the third, innermost loop. Once you have chosen values for a and b, the value of c is fixed (namely, it is 1000 - a - b). You are looping a factor of 1000 times more than you should be.

Since you are requiring that a < b, you could also build that requirement into the second range(). (i.e. have the range for b / y be dependent on the current value of a.)

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
By the way as well, its much cleaner to use itertools.product for nested for loops like that. This is an example with two lists, but it can do more.

Python code:
>>> from itertools import product

>>> list1 = [1, 2, 3, 4]
>>> list2 = ['a', 'b', 'c', 'd']
>>> for num, alp in product(list1, list2):
...     print "List 1 is %d, List 2 is %s" % (num, alp)
... 
List 1 is 1, List 2 is a
List 1 is 1, List 2 is b
List 1 is 1, List 2 is c
List 1 is 1, List 2 is d
List 1 is 2, List 2 is a
List 1 is 2, List 2 is b
List 1 is 2, List 2 is c
List 1 is 2, List 2 is d
List 1 is 3, List 2 is a
List 1 is 3, List 2 is b
List 1 is 3, List 2 is c
List 1 is 3, List 2 is d
List 1 is 4, List 2 is a
List 1 is 4, List 2 is b
List 1 is 4, List 2 is c
List 1 is 4, List 2 is d
>>> 

Munkeymon
Aug 14, 2003

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



pliable posted:

What in the mother gently caress? :psyduck:

I want to try this but, 18 minutes to process...:(

That guy was on a slower Core 2. Took 10 minutes in regular Python and 3 minutes on IronPython on my i5.

Dren
Jan 5, 2001

Pillbug
My solution to problem 9 takes 49.5 ms. It's written in python. However, it is not in the spirit of project euler to give you the answer.

Instead I'll give you some hints:
1) You only need two loops.
2) You can greatly constrain the numbers that you have to search. For instance, the answer will obviously not be a = 1000, b = 1000, c = 1000 since a + b + c would be 3000, not 1000.

huhu
Feb 24, 2006
Thanks everyone for your input, I'm going to take a look at your suggestions now. Have another question. If I have a def such as prime_test(#) and I have it setup to print 'nprime' if it's not prime and 'prime' if it's prime. Another part of my program has if prime_test(#)=='prime' then do something else. If I type prime_test(5) I get prime but if I type prime_test(5)=='prime' I get false. How do I make these two things interact with each other? Here is my code so far.

code:
#Find Primes
def prime_test(test_prime):
    test_list=range(2,round(test_prime/2)+2)
    for i in test_list: #Creates list of numbers from 2 to one more than test_prime/2
        if test_prime%i == 0: #If it finds the number is not prime, ends right away.
            print('nprime')
            break
        elif i==(round(test_prime/2)+1): #If i is the last number of the list, the # is prime.
            print('prime')


prime_list=[2]
i=3
prime_count=1
while prime_count <10:
    if prime_test(i) == 'prime':
        prime_list.append(i)
        prime_count=prime_count+1
        print(prime_list)

huhu fucked around with this message at 20:56 on Aug 27, 2012

jusion
Jan 24, 2007


huhu posted:

Thanks everyone for your input, I'm going to take a look at your suggestions now. Have another question. If I have a def such as prime_test(#) and I have it setup to print 'nprime' if it's not prime and 'prime' if it's prime. Another part of my program has if prime_test(#)=='prime' then do something else. If I type prime_test(5) I get prime but if I type prime_test(5)=='prime' I get false. How do I make these two things interact with each other? Here is my code so far.

code:
#Find Primes
def prime_test(test_prime):
    test_list=range(2,round(test_prime/2)+2)
    for i in test_list: #Creates list of numbers from 2 to one more than test_prime/2
        if test_prime%i == 0: #If it finds the number is not prime, ends right away.
            print('nprime')
            break
        elif i==(round(test_prime/2)+1): #If i is the last number of the list, the # is prime.
            print('prime')


prime_list=[2]
i=3
prime_count=1
while prime_count <10:
    if prime_test(i) == 'prime':
        prime_list.append(i)
        prime_count=prime_count+1
        print(prime_list)
You'll want to return 'prime' for that to work, not print it.

VV Much better explanation

jusion fucked around with this message at 20:56 on Aug 27, 2012

Civil Twilight
Apr 2, 2011

huhu posted:

How do I make these two things interact with each other?

You want to return a value, not print it. And since you're just testing whether something is true/false, then "return true" if you find a prime, and "return false" at the end of your loop if you don't; no need to do string comparisons. Returning will also implicitly break the loop; it jumps you out of your function when used.

huhu
Feb 24, 2006
Played around with my code and got:
code:
a=0
b=0
c=0
for x in range(1,1000):
    for y in range(1,1000):
        z=1000-x-y
        if x<y<z and x**2+y**2==z**2:
                    print(x,y,z)
                    break
Which takes less than a second to compute. Thanks for the input! Also another question about the line if x<y<z and x**2+y**2==z**2: if it finds that x<y<z is false will it break the loop and go back to the beginning or will it still try to compute x**2+y**2==z**2? I feel that this operation could slow down the code.

Also, :suicide: forgot to include a counter for my while loop and took me ten minutes to figure out that was the problem.

huhu fucked around with this message at 21:08 on Aug 27, 2012

Reformed Pissboy
Nov 6, 2003

huhu posted:

Also another question about the line if x<y<z and x**2+y**2==z**2: if it finds that x<y<z is false will it break the loop and go back to the beginning or will it still try to compute x**2+y**2==z**2?

No, it won't compute x**2+y**2==z**2. Python will see the and, which means both sides need to be True, then see that the first part is False. Now it knows the whole thing will end up being False and it can short circuit the if evaluation and proceed on to the next value in the y loop, as you'd expect.

Nippashish
Nov 2, 2005

Let me see you dance!

huhu posted:

Also another question about the line if x<y<z and x**2+y**2==z**2: if it finds that x<y<z is false will it break the loop and go back to the beginning or will it still try to compute x**2+y**2==z**2? I feel that this operation could slow down the code.

When you write 'A and B' then if A is false then B will not be evaluated (this is called short circuiting, and a similar thing happens with 'or').

Really though, you don't need the 'if x < y < z' check at all if you set up the bounds of your loops to make it so this is always true.

xPanda
Feb 6, 2003

Was that me or the door?
How do I return a numpy.float32 value using the C-API? I can return a Python builtin float with
C++ code:
float lol = 2.2;
return Py_BuildValue("f", lol);
I expect I pass a type object with "O!", but I haven't got it yet.

Cat Plus Plus
Apr 8, 2011

:frogc00l:

xPanda posted:

How do I return a numpy.float32 value using the C-API?

Try these: http://docs.scipy.org/doc/numpy/reference/c-api.array.html#array-scalars

super_chair
Mar 13, 2012
I've got a question.

Is it just me, or is del redundant? I can't seem to find anything worth doing with it that can't be done another way.

I know that, for example, you could do:

code:
>>> a = [1,2,3]
>>> del a[2]
>>> a
[1, 2]
But this could just as easily be done as:
code:
>>> a = [1,2,3]
>>> a = a[:2]
>>> a
[1, 2]
I'm sure that I'm missing something obvious here, could anyone tell me what it is?

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
What if you want to del a?

Cat Plus Plus
Apr 8, 2011

:frogc00l:

super_chair posted:

I'm sure that I'm missing something obvious here, could anyone tell me what it is?

You can't replace it when deleting local names, and it's more convenient for lists when you delete from the middle, or by range:

Python code:
a = [1, 2, 3, 4]
del a[1]   # a = a[:1] + a[1:]
del a[1:3] # a = a[:1] + a[3:]
Plus, it might potentially be optimised, since it's language-level mutating operation.
Also used for dicts, so you get consistency:

Python code:
a = {'x': 42}
del a['x'] # a.pop('x')

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Lysidas posted:

What if you want to del a?

That's very rare. The only case I can imagine is if you litter the module namespace and want to clean up afterwards.

super_chair posted:

I've got a question.

Is it just me, or is del redundant? I can't seem to find anything worth doing with it that can't be done another way.

I know that, for example, you could do:

code:
>>> a = [1,2,3]
>>> del a[2]
>>> a
[1, 2]
But this could just as easily be done as:
code:
>>> a = [1,2,3]
>>> a = a[:2]
>>> a
[1, 2]
I'm sure that I'm missing something obvious here, could anyone tell me what it is?

Python code:
>>> a = [1, 2, 3]
>>> b = a
>>> a = a[:2]
>>> a, b
([1, 2], [1, 2, 3])
Python code:
>>> a = [1, 2, 3]
>>> b = a
>>> del a[2]
>>> a, b
([1, 2], [1, 2])

Cat Plus Plus
Apr 8, 2011

:frogc00l:

Suspicious Dish posted:

Python code:
>>> a = [1, 2, 3]
>>> b = a
>>> a = a[:2]
>>> a, b
([1, 2], [1, 2, 3])
Python code:
>>> a = [1, 2, 3]
>>> b = a
>>> del a[2]
>>> a, b
([1, 2], [1, 2])

Well, you could do a[:] = a[:2] there.

FoiledAgain
May 6, 2007

super_chair posted:

I've got a question.

Is it just me, or is del redundant? I can't seem to find anything worth doing with it that can't be done another way.

I used it just today to delete a key,value pair from a dictionary. I liked it better than using pop or popitem.

Adbot
ADBOT LOVES YOU

Dren
Jan 5, 2001

Pillbug

huhu posted:

Played around with my code and got:
code:
a=0
b=0
c=0
for x in range(1,1000):
    for y in range(1,1000):
        z=1000-x-y
        if x<y<z and x**2+y**2==z**2:
                    print(x,y,z)
                    break
Which takes less than a second to compute. Thanks for the input! Also another question about the line if x<y<z and x**2+y**2==z**2: if it finds that x<y<z is false will it break the loop and go back to the beginning or will it still try to compute x**2+y**2==z**2? I feel that this operation could slow down the code.

Also, :suicide: forgot to include a counter for my while loop and took me ten minutes to figure out that was the problem.

You can create better constraints for the ranges you search.

  • Locked thread