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
Hammerite
Mar 9, 2007

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

code:
>>> import math
>>> def f ():
...     for x in range(1, 334):
...         for y in range(x, math.floor(501 - x / 2)):
...             if x**2 + y**2 == (1000 - x - y)**2:
...                 return x * y * (1000 - x - y)
...     return 'Not found'
...
>>> f()
31875000
If you want me to explain anything, then ask.

Adbot
ADBOT LOVES YOU

xPanda
Feb 6, 2003

Was that me or the door?

Cheers. Those appear to be the correct things (PyArray_Scalar() in particular) but the fact that the documentation refers to parameters which aren't even in the prototype (and has done so since at least 2008 according to git log) and the intermittent references to whether a function needs you to worry about refcounting is freaking me out and leaving me without any confidence in using these functions reliably.

I stumbled across this mailing list discussion which says to use the PyArrayScalar_New and PyArrayScalar_ASSIGN macros defined in <numpy/arrayscalars.h>. These things call macros down about 7 layers, so I'm not really sure what the hell they're doing or whether they're handling refcounting correctly. I just return a PyObject pointer to the return value of the _New macro and the calling Python code appears to be a numpy.float32 and sys.refcount says it has a refcount of 2, so I assume everything is correct. These macros aren't documented in the source code and don't appear in the generated docs at all, but aren't called by anything else in the include directory so I don't think they're meant for internal use only.
C++ code:
    float lol = 2.2;
    PyObject *r = PyArrayScalar_New(Float32);
    PyArrayScalar_ASSIGN(r, Float32, lol);
    return r;
Python code:
>>> v = that_cmodule.f() # Doesn't return 2.2 as the above C code isn't the real code, ignore it
>>> v
465.7811
>>> type(v)
<class 'numpy.float32'>
>>> sys.getrefcount(v)
2
Am I missing something, or is this a failing of the documentation? I would have expected it to have a code example snippet saying "here's the simple way of returning a value reliably".

BigRedDot
Mar 6, 2008

That is the correct way to do it.
code:
PyArrayScalar_VAL(r, Float32) = lol
should also work, that's really all PyArrayScalar_ASSIGN does anyway.

BigRedDot fucked around with this message at 04:08 on Aug 30, 2012

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES
I learned something today about python coding that is probably very durr to the rest of you but actually will save my rear end in the future.

When making arrays from data files, it's not uncommon of me to do something like:

code:
import numpy as num
-snip-

x_data = num.array([])
y_data = num.array([])
for i in num.arange(0, len(data), 1):
    x_data = num.append(x_data, data[i,0])
    y_data = num.append(y_data, data[i,1])
I never thought this was terrible, and seemed to work fine, and fairly quickly. However, I recently learned that due to the way numpy handles append, it is rewriting the array to a new memory block (or something) each time. Apprently, using the native append is far better. So I should be doing something like.

code:
import numpy as num
-snip-

x_data = []
y_data = []
for i in num.arange(0, len(data), 1):
    x_data.append(data[i,0])
    y_data.append(data[i,1])

x_data = num.array(x_data)
y_data = num.array(y_data)
I also like this because it was a pain in the rear end to create an empty row doing my approach for anything beyond a 1D array. That is, num.array([,]) is not allowed, so I'd usually just start with num.array([0,0]) and kill the first line when done.

Anyway, I don't know how much time this saves, but if it even saves 1 second for a decent sized array, it means that for my latest project, which has ~2000 of said data files, I'll save easily half an hour.

I didn't think the coding I did was intensive enough for memory management to mater, but here I am.

OnceIWasAnOstrich
Jul 22, 2006

JetsGuy posted:

I learned something today about python coding that is probably very durr to the rest of you but actually will save my rear end in the future.

When making arrays from data files, it's not uncommon of me to do something like:

code:
import numpy as num
-snip-

x_data = num.array([])
y_data = num.array([])
for i in num.arange(0, len(data), 1):
    x_data = num.append(x_data, data[i,0])
    y_data = num.append(y_data, data[i,1])
I never thought this was terrible, and seemed to work fine, and fairly quickly. However, I recently learned that due to the way numpy handles append, it is rewriting the array to a new memory block (or something) each time. Apprently, using the native append is far better. So I should be doing something like.



You can pre-allocate numpy arrays with something like numpy.zeros if you know the size of the data, which it appears you do, and it saves you have having to copy everything from a list to a numpy array. Depending on your input format you could also use numpy.loadtxt, which is also quite quick.

edit: Also using numpy.arange as your iterable in a for loop is...a strange thing to do, just use xrange so you aren't allocating an entire array just to hold your indices.

OnceIWasAnOstrich fucked around with this message at 23:37 on Aug 30, 2012

AmericanBarbarian
Nov 23, 2011
I'm working on Ex. 15 of LearnPythonTheHardWay and I'm a bit stuck. This is the exercise I am trying to complete. http://learnpythonthehardway.org/book/ex15.html
I'm running this exercise with Powershell in my C:\Python27 folder. Both my .py file and sample text file I am trying to open and read with this program are in the same C:\python27 folder. When I run python ex15.py ex15_sample.txt I don't get an error, the shell just returns to my C:\python27 > prompt. I read all the comments for the exercise page already and I couldn't figure out the exact problem I'm causing. I think I don't understand something about directing python to the correct folder to open my text file, but I don't believe I'm making the obvious mistakes other people did on the exercise.

code:
from sys import argv

script, filename = argv

txt = open(filename)

print "Here's your file %r:" % filename
print txt.read()

print "Type the filename again:"
file_again = raw_input("> ")

txt_again = open(file_again)

print txt_again.read()
Anyone pointing out the foolish things I'm missing would be appreciated.

AmericanBarbarian fucked around with this message at 20:13 on Aug 31, 2012

accipter
Sep 12, 2003

JetsGuy posted:

I learned something today about python coding that is probably very durr to the rest of you but actually will save my rear end in the future.

When making arrays from data files, it's not uncommon of me to do something like:

code:
import numpy as num
-snip-

x_data = num.array([])
y_data = num.array([])
for i in num.arange(0, len(data), 1):
    x_data = num.append(x_data, data[i,0])
    y_data = num.append(y_data, data[i,1])
I never thought this was terrible, and seemed to work fine, and fairly quickly. However, I recently learned that due to the way numpy handles append, it is rewriting the array to a new memory block (or something) each time. Apprently, using the native append is far better. So I should be doing something like.

code:
import numpy as num
-snip-

x_data = []
y_data = []
for i in num.arange(0, len(data), 1):
    x_data.append(data[i,0])
    y_data.append(data[i,1])

x_data = num.array(x_data)
y_data = num.array(y_data)
I also like this because it was a pain in the rear end to create an empty row doing my approach for anything beyond a 1D array. That is, num.array([,]) is not allowed, so I'd usually just start with num.array([0,0]) and kill the first line when done.

Anyway, I don't know how much time this saves, but if it even saves 1 second for a decent sized array, it means that for my latest project, which has ~2000 of said data files, I'll save easily half an hour.

I didn't think the coding I did was intensive enough for memory management to mater, but here I am.

I would something like this:

code:
x_data = np.array([d[0] for d in data])
y_data = np.array([d[1] for d in data])
Or use records:
code:
data = np.rec.fromrecords(data, names='x,y')
# You can then access the values with values with data.x and data.y
Edit: I used np instead of num because that is convention. There is also np.rec.fromarrays() columns of data, instead of rows.

accipter fucked around with this message at 15:53 on Aug 31, 2012

accipter
Sep 12, 2003

Dr.Spaceman posted:

I'm working on Ex. 15 of LearnPythonTheHardWay and I'm a bit stuck. This is the exercise I am trying to complete. http://learnpythonthehardway.org/book/ex15.html
I'm running this exercise with Powershell in my C:\Python27 folder. Both my .py file and sample text file I am trying to open and read with this program are in the same C:\python27 folder. When I run python ex15.py ex15_sample.txt I don't get an error, the shell just returns to my C:\python27 > prompt. I read all the comments for the exercise page already and I couldn't figure out the exact problem I'm causing. I think I don't understand something about directing python to the correct folder to open my text file, but I don't believe I'm making the obvious mistakes other people did on the exercise.

code:
>>> from sys import argv

script, filename = argv

txt = open(filename)

print "Here's your file %r:" % filename
print txt.read()

print "Type the filename again:"
file_again = raw_input("> ")

txt_again = open(file_again)

print txt_again.read()
Anyone pointing out the foolish things I'm missing would be appreciated.

This might be a bit much but you should check to see if C:\Python27\ is in your path by doing 'echo %PATH%' (don't include the quotes). If your path includes C:\Python27\ then you can call python.exe from any location and it will find python.exe located in C:\Python27\. Note that if you have other installations of Python that are included in the PATH and they are listed earlier they will be selected first. You can modify your path using Control Panel .. Advanced System Settings (google for more detail), or by creating a batch file to set a custom path prior to loading PowerShell. Once you solve your path issue you can move your Python code to a more sane location.

Is that code block the text in your file? If so you shouldn't have the >>> in there.

AmericanBarbarian
Nov 23, 2011
No, the >>> wasn't in my code. That was an artifact from a copy past I did somewhere else. I added python to my Environmental Variable so now I don't have to abbreviate .\python in powershell to run it. I was aware of how to change that but just lazy.

I ran python exp15.py ex15_sample.txt again with the change and got the same result. To be extra clear this is what I get when I run it in Powershell.
code:
 PS C:\python27> python exp15.py ex15_sample.txt
 PS C:\python 27> 
If I had an error message I would be happier about this...

OnceIWasAnOstrich
Jul 22, 2006

accipter posted:

I would something like this:

code:
x_data = np.array([d[0] for d in data])
y_data = np.array([d[1] for d in data])
Or use records:
code:
data = np.rec.fromrecords(data, names='x,y')
# You can then access the values with values with data.x and data.y
Edit: I used np instead of num because that is convention. There is also np.rec.fromarrays() columns of data, instead of rows.

The list comprehensions are probaly the cleanest way to do exactly what your code segments did but again need extra memory as you are reading the entire data array into a list and then reading the list into a numpy array. The records are the fastest but I don't know if they are any slower to access than an array, and they obviously change what kind of format you are dealing with.

If you really care how fast this one operation takes.

data = 2x1000 array of random ints
Numpy append - 1.5s
Native append - 151ms
List comprehensions - 112ms
Preallocated numpy arrays with np.zeros() and direct assignment - 63ms
(records) - 24ms

Cat Plus Plus
Apr 8, 2011

:frogc00l:

Dr.Spaceman posted:

No, the >>> wasn't in my code. That was an artifact from a copy past I did somewhere else. I added python to my Environmental Variable so now I don't have to abbreviate .\python in powershell to run it. I was aware of how to change that but just lazy.

I ran python exp15.py ex15_sample.txt again with the change and got the same result. To be extra clear this is what I get when I run it in Powershell.
code:
 PS C:\python27> python exp15.py ex15_sample.txt
 PS C:\python 27> 
If I had an error message I would be happier about this...

Try running with -v flag. Try running outside of PowerShell, too. Do you use standard console or something like Console2?

AmericanBarbarian
Nov 23, 2011
I tried it in Console2 and got the same results. Would I use -v flag like this? I've tried this in Powershell and it returns the same results as before.
code:
PS C:\python27> python exp15.py -vex15_sample.txt
 
I don't know if I am using the -v flag correctly here.

AmericanBarbarian fucked around with this message at 19:26 on Aug 31, 2012

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
A silly question, but are you sure "exp15.py" is the one that contains your code?

AmericanBarbarian
Nov 23, 2011

Suspicious Dish posted:

A silly question, but are you sure "exp15.py" is the one that contains your code?

No worries, no questions are silly when learning something from scratch. And yes, I'm very sure exp15.py is the correct file with my code, and ex15_sample.txt is the sample text file I am trying to open. At one point I thought I was saving the example file as ex15_sample.txt.txt , but I checked and that wasn't it. When I ran it in Console2 it looks like a file opens and then closes very quickly in the top of the window , but I can't tell anything more than that.

Cat Plus Plus
Apr 8, 2011

:frogc00l:

Dr.Spaceman posted:

I don't know if I am using the -v flag correctly here.

code:
python -v file
Console2 question was more about "if you use it, it might be the cause, because it uses horrible hacks to do what it does". Can you run the REPL (i.e. just python, with no arguments)?

AmericanBarbarian
Nov 23, 2011
When you ask if I can run the REPL with no arguments do you mean just running python? That works fine but I'm not sure what you are exactly asking.
I tried the proper -v flag
code:
 python -v exp15.py ex15_sample.txt 
and it produced a large amount of text that ended with lots of cleanup messages. My program didn't run and it returned to C:\python27

Cat Plus Plus
Apr 8, 2011

:frogc00l:
Well, I thought it might be a bigger problem with Python being unable to output anything, but if -v and REPL work, then that is out of the window.

Do type exp15.py (and/or try running python full\path\to\exp15.py), because running an empty file is the only other explanation that I've got — it would error out on non-existing file, it would error out on opening non-existing file, with no errors your prints would output.

If this is really the file with the exact code you've posted, I'm out of ideas.

AmericanBarbarian
Nov 23, 2011
Thanks for looking into my problem, I might give up on it for now. I tried an alternative solution that teaches the same idea (opening and looking at data in other files) like so
code:
from sys import argv

filename = raw_input()
txt  = open(filename)

print "Here's your file %r." % filename
print txt.read() 
And I got that to work. So I might just skip to the next lesson.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Do other sorts of errors get printed out? PowerShell could be doing something stupid with stderr (does Windows even have a stderr?)

Cat Plus Plus
Apr 8, 2011

:frogc00l:

Suspicious Dish posted:

(does Windows even have a stderr?)

It does.

I've tried running that script in a PowerShell and it works fine (errors are displayed correctly, too). I don't really use PS, maybe there's a magic switch to make it behave in a weird way?

huhu
Feb 24, 2006
I have this code:
code:
test=0
remainder=1
while remainder !=0:
    test=test+1
    for i in range(1,21):
        if test%i !=0:
            remainder=1
            break
        else:
            remainder=0
            print(test)
It's a test for the smallest number that can be divided evenly by the numbers 1 to 20. Where I wrote break, I want it to break out of the if statement and start over with a new test number. Is there such a command to do this?

yippee cahier
Mar 28, 2005

huhu posted:

I have this code:
code:
test=0
remainder=1
while remainder !=0:
    test=test+1
    for i in range(1,21):
        if test%i !=0:
            remainder=1
            break
        else:
            remainder=0
            print(test)
It's a test for the smallest number that can be divided evenly by the numbers 1 to 20. Where I wrote break, I want it to break out of the if statement and start over with a new test number. Is there such a command to do this?

continue

edit: continue would be useful in restarting a loop, but just leave the whole line out as there are no more lines after the if block. it will continue automatically.

yippee cahier fucked around with this message at 21:26 on Sep 1, 2012

huhu
Feb 24, 2006

sund posted:

continue

edit: continue would be useful in restarting a loop, but just leave the whole line out as there are no more lines after the if block. it will continue automatically.
I think I didn't explain myself properly. I want to break out of the if statement and start the while loop over again. I ended up redoing my coding and got it to work a different way though by moving 'test' around.

Any suggestions for making this more efficient though? It took somewhere between two and five minutes to solve. Also, is making coding more efficient in regards to math problems mostly done by knowing more advanced theories? Like for example, here is another method for solving this problem:
http://ca.answers.yahoo.com/question/index?qid=20100123221401AA7q4lR
code:
test=1
remainder=1
while remainder !=0:
    for i in range(1,21):
        if test%i==0:
            remainder=0
        elif test%i !=0:
            remainder=1
            test=test+1
            break
print(test)

Nippashish
Nov 2, 2005

Let me see you dance!

huhu posted:

Any suggestions for making this more efficient though? It took somewhere between two and five minutes to solve. Also, is making coding more efficient in regards to math problems mostly done by knowing more advanced theories? Like for example, here is another method for solving this problem:
http://ca.answers.yahoo.com/question/index?qid=20100123221401AA7q4lR

Often the best way to make a program more efficient is to find a strategy for solving the same problem that requires fewer steps, rather than trying to make each step faster. This applies pretty much everywhere, not just to coding in regards to math.

Lysidas
Jul 26, 2002

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

huhu posted:

I think I didn't explain myself properly. I want to break out of the if statement and start the while loop over again. I ended up redoing my coding and got it to work a different way though by moving 'test' around.

Any suggestions for making this more efficient though? It took somewhere between two and five minutes to solve. Also, is making coding more efficient in regards to math problems mostly done by knowing more advanced theories? Like for example, here is another method for solving this problem:
http://ca.answers.yahoo.com/question/index?qid=20100123221401AA7q4lR
code:
test=1
remainder=1
while remainder !=0:
    for i in range(1,21):
        if test%i==0:
            remainder=0
        elif test%i !=0:
            remainder=1
            test=test+1
            break
print(test)

Your code probably can't be significantly improved, but as Nippashish stated, your algorithm is very sub-optimal. You're counting up from 1 and checking whether that number is divisible by each of 1 through 20.

A better way to do this (the best that I can think of) is to factorize each of the integers from 1 to 20, take the union of those factor counts, and then multiply to find your number. For example:

  1. You don't need to worry about whether something is divisible by 1. No factors.
  2. You need a 2 to make the number divisible by 2.
  3. Again, need a 3 to make the final product divisible by 3.
  4. You need two 2s to make the product divisible by 4, but you already have one in your collection of factors. Add another 2.
  5. Add a 5.
  6. You already have a 2 and a 3 in your factors, so 6 is covered.
  7. Add a 7.
  8. Add a 2, since you already have two of them and 8 is 23.
... and so on. Then, return the product of your factors. Come to think of it, it'd probably make sense to count down from 20 instead, but counting up from 1 works just as well.

I've hacked up a version of the Python collections.Counter class that overrides update to use the max instead of the sum of values. Assuming that I didn't screw anything up, it took 53 milliseconds to find the least common multiple of all integers from 1 to 100 inclusive (69720375229712477164533808935312303556800).

EDIT: oh hey that's what the Yahoo Answers link says. Oops.

Lysidas fucked around with this message at 06:24 on Sep 2, 2012

huhu
Feb 24, 2006
Thanks again for all of your input.

Can anyone point me to a basic introduction to matrices and interacting with rows, columns, changing elements, adding, rows/columns, etc? I must be searching the wrong thing because I've been looking for twenty minutes and can't find anything useful.

Nippashish
Nov 2, 2005

Let me see you dance!

huhu posted:

Thanks again for all of your input.

Can anyone point me to a basic introduction to matrices and interacting with rows, columns, changing elements, adding, rows/columns, etc? I must be searching the wrong thing because I've been looking for twenty minutes and can't find anything useful.

Do you want to know about doing these things in code or are you asking where you can learn linear algebra? Assuming the former (since you're in the python thread) you should look at numpy.

melon cat
Jan 21, 2010

Nap Ghost
Python experts! I'm trying to get started with Python via Udacity. It has been a humbling experience. I'm already stumped on one of Udacity's lessons on extracting links. The whole course has gone from "Okay, I'm following. This is do-able!" to :stare:.

I feel as if there's some additional material I should be reviewing before I move on in this course (CS101). The OP has an amazing wealth of information, but is there any particular starting point where a novice coder like myself should start?

\/So I guess I'm not imagining things. Not even kidding you, the course went from easy to "What the heck are they asking for?" I'm not even brand new to coding languages. I was just hoping to get better acquainted with Python. Thanks a lot for those two resources, Suspicious Dish! Any other great starting points you guys would recommend?

melon cat fucked around with this message at 05:15 on Sep 4, 2012

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
um, this course looks not very well put together. The chapter on Backus Naur Form comes before the chapter on Python Expressions, which comes before the chapter on Variables.

If you have any specific question, feel free to ask, but my very biased and rushed opinion is that it doesn't look like a proper introduction for new programmers. They apparently want you to have a search engine by the end of this.

The two go-to things that I like to refer people to for new programmers are Think Python and Learn Python the Hard Way. Both are free resources.

Suspicious Dish fucked around with this message at 05:05 on Sep 4, 2012

Dren
Jan 5, 2001

Pillbug

JetsGuy posted:

I learned something today about python coding that is probably very durr to the rest of you but actually will save my rear end in the future.

When making arrays from data files, it's not uncommon of me to do something like:

code:
import numpy as num
-snip-

x_data = num.array([])
y_data = num.array([])
for i in num.arange(0, len(data), 1):
    x_data = num.append(x_data, data[i,0])
    y_data = num.append(y_data, data[i,1])
I never thought this was terrible, and seemed to work fine, and fairly quickly. However, I recently learned that due to the way numpy handles append, it is rewriting the array to a new memory block (or something) each time. Apprently, using the native append is far better. So I should be doing something like.

code:
import numpy as num
-snip-

x_data = []
y_data = []
for i in num.arange(0, len(data), 1):
    x_data.append(data[i,0])
    y_data.append(data[i,1])

x_data = num.array(x_data)
y_data = num.array(y_data)
I also like this because it was a pain in the rear end to create an empty row doing my approach for anything beyond a 1D array. That is, num.array([,]) is not allowed, so I'd usually just start with num.array([0,0]) and kill the first line when done.

Anyway, I don't know how much time this saves, but if it even saves 1 second for a decent sized array, it means that for my latest project, which has ~2000 of said data files, I'll save easily half an hour.

I didn't think the coding I did was intensive enough for memory management to mater, but here I am.

What is this data[i,0] syntax?

AmericanBarbarian
Nov 23, 2011

melon cat posted:

Any other great starting points you guys would recommend?

I'm using Learn Python the Hard Way as my main resource, with supplements from the interactive tutorials on the other two sites below.

http://learnpythonthehardway.org/book
http://www.diveintopython.net/getting_to_know_python/index.html
http://www.learnpython.org/


Big List -
http://programming-motherfucker.com/become.html#Python

Lysidas
Jul 26, 2002

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

Dren posted:

What is this data[i,0] syntax?

There's no special syntax.

Python code:
In [1]: d = {(2, 1): 'two, one', (0, 0): 'zeroes'}

In [2]: d[2, 1]
Out[2]: 'two, one'
NumPy arrays have different semantics when you call __getitem__ with a tuple argument, however -- this pulls certain elements out of a multidimensional array.

Optimus Prime Ribs
Jul 25, 2007

Random Python question:
I was playing around with the Python shell and noticed that you could extend Python's built-in types:
Python code:
class int(int):
  def foo(self):
    print("bar")

int(42).foo()
But you cannot do this:
Python code:
class int(int):
  def foo(self):
    print("bar")

42.foo()
I don't actually plan on doing this in real code, but I'm just wondering why constructing an int works, but using a literal value does not. Does the literal value use a primitive type that is not affected by that goofy class or something?

Red Mike
Jul 11, 2011
Python code:
isinstance(42, int)
Note how that returns false after you create your own int class.

OnceIWasAnOstrich
Jul 22, 2006

Optimus Prime Ribs posted:

I don't actually plan on doing this in real code, but I'm just wondering why constructing an int works, but using a literal value does not. Does the literal value use a primitive type that is not affected by that goofy class or something?

Pretty much

Python code:
In [64]: type(42)
Out[64]: int

In [65]: type(int(42))
Out[65]: __main__.int

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
There are really two issues:

  1. Redefining the int name in some namespace doesn't change the type of integer literals.

    Python code:
    In [1]: class int(int):
       ...:     def foo(self):
       ...:         print("bar")
       ...:         
    
    In [2]: int(42).foo()
    bar
    
    In [3]: type(42) is int
    Out[3]: False
    
    In [4]: type(42)
    Out[4]: builtins.int
    
  2. It's tricky to call methods on integer literals -- this is actually allowed by the grammar but it looks like the parser is greedy about trying to parse things as floating point literals. A bit of whitespace makes a huge difference:
    Python code:
    In [1]: 42.bit_length()
      File "<ipython-input-1-aa320a430c93>", line 1
        42.bit_length()
                    ^
    SyntaxError: invalid syntax
    
    
    In [2]: 42 .bit_length()
    Out[2]: 6
    

EDIT: Beaten with #1; it took me too long to research #2 :)

Lysidas fucked around with this message at 22:03 on Sep 4, 2012

Cat Plus Plus
Apr 8, 2011

:frogc00l:

Lysidas posted:

A bit of whitespace makes a huge difference:

It's better to do (42).stuff(), if you really have a need to call something on an integer literal. I don't recall ever seeing it in the wild, though.

Suspicious Dish
Sep 24, 2011

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

Dr.Spaceman posted:

I'm using Learn Python the Hard Way as my main resource, with supplements from the interactive tutorials on the other two sites below.

http://learnpythonthehardway.org/book
http://www.diveintopython.net/getting_to_know_python/index.html
http://www.learnpython.org/


Big List -
http://programming-motherfucker.com/become.html#Python

Do not read Dive into Python. It was built for a version of Python that's over 10 years old, and the creator has not updated it.

Suspicious Dish
Sep 24, 2011

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

Optimus Prime Ribs posted:

Random Python question:
I was playing around with the Python shell and noticed that you could extend Python's built-in types:
Python code:
class int(int):
  def foo(self):
    print("bar")

int(42).foo()
But you cannot do this:
Python code:
class int(int):
  def foo(self):
    print("bar")

42.foo()
I don't actually plan on doing this in real code, but I'm just wondering why constructing an int works, but using a literal value does not. Does the literal value use a primitive type that is not affected by that goofy class or something?

Python code:
def foo(self):
  print("bar")

import ctypes
f = ctypes.pythonapi._PyObject_GetDictPtr
f.restype = ctypes.POINTER(ctypes.py_object)
f.argtypes = [ctypes.py_object]
d = f(int).contents.value
d['foo'] = foo

42 .foo()

Adbot
ADBOT LOVES YOU

Optimus Prime Ribs
Jul 25, 2007

The part about int and __main__.int makes sense; I had a feeling it was something like that.

Lysidas posted:

Python code:
In [1]: 42.bit_length()
  File "<ipython-input-1-aa320a430c93>", line 1
    42.bit_length()
                ^
SyntaxError: invalid syntax


In [2]: 42 .bit_length()
Out[2]: 6

Never knew that about Python.
Thanks for the tip. :)

Suspicious Dish posted:

Python code:
def foo(self):
  print("bar")

import ctypes
f = ctypes.pythonapi._PyObject_GetDictPtr
f.restype = ctypes.POINTER(ctypes.py_object)
f.argtypes = [ctypes.py_object]
d = f(int).contents.value
d['foo'] = foo

42 .foo()

I don't really understand this, but that's a neat trick.

  • Locked thread