Re: Lists
Seymore4Head wrote: > import random > nums=range(1,11) > print (nums) > samp=random.sample(nums,10) > top=nums > newlist=nums[::-1] > tail=newlist > > for x in range(10): > print ("Top {:2d}Tail {:2.0f} Sample {:2d} > ".format(top[x],tail[x],samp[x])) > > I don't understand why the command nums=range(1,11) doesn't work. Of course it works. It does exactly what you told it to do: set the variable "nums" to the result of calling range(1, 11). The only question is, what does range(1, 11) do? > I would think that print(nums) should be 1,2,3 ect. > Instead it prints range(1,11) Did you read the documentation for range? py> help(range) class range(object) | range([start,] stop[, step]) -> range object | | Returns a virtual sequence of numbers from start to stop by step. [...] range in Python 3 does not return a list. It returns a special object which provides a sequence of numbers, but without actually storing them all in a list. > Why does random.sample(nums,10) give me the numbers between 1 and 10. What did you expect it to do? Did you read the documentation? py> import random py> help(random.sample) Help on method sample in module random: sample(self, population, k) method of random.Random instance Chooses k unique random elements from a population sequence or set. [...] To choose a sample in a range of integers, use range as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(1000), 60) The docs even tell you that (1) sample supports range objects, and (2) using range is more efficient than lists. > I am missing something subtle again. range objects behave *like* lists when you index them: py> nums = range(1, 100) py> nums[0] # First item. 1 py> nums[-1] # Last item. 99 They're even smart enough that you can take a slice, and they give you a new range object: py> nums[1:10] range(2, 11) When you iterate over them, you get each item in turn: py> for i in range(1, 4): ... print(i) ... 1 2 3 range objects are more efficient than lists if the numbers follow the right sort of pattern. While a list can contain any values you like, in any order: py> nums = [1, 33, 5, 222, 4, 6, 0, 888, 7] range objects are limited to a linear sequence of: start, start+step, start+2*step, start+3*step, ... up to some end value. The reason range is more efficient is that, unlike lists, it doesn't need to pre-populate all the values required, it can calculate them on the fly when and as required. The reason why lists are more flexible is that the values don't have to be calculated as needed, they can just be stored, ready to use. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Lists
Christian Gollwitzer wrote: > range() does > not return a list of numbers, but rather a generator Technically, it's not a generator. It's a range object. Generators can return anything, and you have to program them by using yield: def gen(): yield 1 yield 2 if today() is Tuesday: yield 99 yield 3 whereas range() objects are much more specific in what they can do. But otherwise, they behave in a similar fashion. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: CSV methodology
je...@newsguy.com writes: > Hello. Back in the '80s, I wrote a fractal generator, which, over the years, > I've modified/etc to run under Windows. I've been an Assembly Language > programmer for decades. Recently, I decided to learn a new language, > and decided on Python, and I just love it, and the various IDEs. > > Anyway, something I thought would be interesting, would be to export > some data from my fractal program (I call it MXP), and write something > in Python and its various scientific data analysis and plotting modules, > and... well, see what's in there. > Tools that are worth mentioning: ipython notebook, pandas For example, http://nbviewer.ipython.org/github/twiecki/financial-analysis-python-tutorial/blob/master/1.%20Pandas%20Basics.ipynb -- Akira -- https://mail.python.org/mailman/listinfo/python-list
Lists
import random nums=range(1,11) print (nums) samp=random.sample(nums,10) top=nums newlist=nums[::-1] tail=newlist for x in range(10): print ("Top {:2d}Tail {:2.0f} Sample {:2d} ".format(top[x],tail[x],samp[x])) I don't understand why the command nums=range(1,11) doesn't work. I would think that print(nums) should be 1,2,3 ect. Instead it prints range(1,11) Why does random.sample(nums,10) give me the numbers between 1 and 10. I am missing something subtle again. -- https://mail.python.org/mailman/listinfo/python-list
Re: CSV methodology
jayte wrote: > Sorry, I neglected to mention the values' significance. The MXP program > uses the "distance estimate" algorithm in its fractal data generation. > The values are thus, for each point in a 1778 x 1000 image: > > Distance, (an extended double) > Iterations, (a 16 bit int) > zc_x,(a 16 bit int) > zc_y (a 16 bit int) > Probably a bit too early in your "Python career", but you can read raw data with numpy. Something like with open(filename, "rb") as f: a = numpy.fromfile(f, dtype=[ ("distance", "f16"), ("iterations", "i2"), ("zc_x", "i2"), ("zc_y", "i2"), ]).reshape(1778, 1000) might do, assuming "extended double" takes 16 bytes. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lists
Christian Gollwitzer wrote: > Am 15.09.14 04:40, schrieb Seymore4Head: >> nums=range(1,11) >> print (nums) > >> I don't understand why the command nums=range(1,11) doesn't work. >> I would think that print(nums) should be 1,2,3 ect. >> Instead it prints range(1,11) > > It does work, but in a different way than you might think. range() does > not return a list of numbers, but rather a generator - that is an object > which produces the values one after another. But you can transform it > into a list: > > print(list(nums)) > > should give you what you want. > > Christian I'd call range() an iterable. A generator is a specific kind of iterator. The difference between iterable and iterator is that the latter cannot be restarted: >>> def f(): ... yield 1 ... yield 2 ... >>> g = f() >>> list(g) [1, 2] >>> list(g) [] # empty --> g is an iterator >>> r = range(1, 3) >>> list(r) [1, 2] >>> list(r) [1, 2] # same as before --> r is an iterable -- https://mail.python.org/mailman/listinfo/python-list
something like pyfilesystem, fs.zipfs that works on windows
I need something that is similar to zipfs, but it should work on Windows and Unix too. Requirements: * store a complete directory structure and multiple files in a single file * be able to add, replace and delete files and directories * binary write/append to files is NOT a requirement but it would be good * should work with any file-like object that implements read(), write(), seek(), tell(), close(), flush() and truncate() [e.g. no fileno()] * does not need to store the files in compressed form Is there something like this available? Thanks, Laszlo -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. -- https://mail.python.org/mailman/listinfo/python-list
List insert at index that is well out of range - behaves like append that too SILENTLY
Hi , Let me demonstrate the problem I encountered : I had a list a = [1, 2, 3] when I did a.insert(100, 100) [1, 2, 3, 100] as list was originally of size 4 and I was trying to insert value at index 100 , it behaved like append instead of throwing any errors as I was trying to insert in an index that did not even existed . Should it not throw IndexError: list assignment index out of range exception as it throws when I attempt doing a[100] = 100 Personal Opinion : Lets see how other languages behave in such a situation : 1. Ruby : > a = [1, 2] > a[100] = 100 > a => [1, 2, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, 100] The way ruby handles this is pretty clear and sounds meaningful (and this is how I expected to behave and it behaved as per my expectation) at least to me . Here also it was silently handled but the way it fills non existing indexes in between with nil sounded meaningful . 2. Java : When I do such an action in java by using .add(index.value) on may be arraylist or linkedlist I get java.lang.IndexOutOfBoundException Here instead of handling it silently it throws an error . But the python way of handling such a problem by appending to the end sounds more unexpected to me . This in fact flummoxed me in the beginning making me think it could be a bug . Then when I raised it in stackoverflow I got chance to look at source and found that's the way code is written . Question : 1. Any idea Why it has been designed to silently handle this instead of at least informing the user with an exception(as in java) or attaching null values in empty places (as in ruby) ? Thanks Harish -- https://mail.python.org/mailman/listinfo/python-list
Re: Marco's atexit issue was: Re: ANN: wxPython 3.0.1.1
all the code addressed by the exception is out of my source. I don't have any atexit.register in my code Marco On Friday, September 12, 2014 6:33:09 PM UTC+2, Nathan McCorkle wrote: > > > > On Friday, September 12, 2014 1:14:41 AM UTC-7, Marco Prosperi wrote: >> >> >> I'm trying to pass my application from wxpython2.9.4 to 3.0.1 but there >> seems to be still some of the problems that made me skip wxpy2.9.5: when >> I >> close the main window of my application (windows7-64bit, python 2.7) I >> get >> exceptions like this below (none with wxpy2.9.4). How can I avoid that my >> users get this? this happens after my OnExit function is completed >> >> Marco >> >> Error in atexit._run_exitfuncs: >> Traceback (most recent call last): >> File "C:\Programmi\Python27\lib\atexit.py", line 24, in _run_exitfuncs >> func(*targs, **kargs) >> PyAssertionError: C++ assertion "GetEventHandler() == this" failed at >> ..\..\src\ >> common\wincmn.cpp(478) in wxWindowBase::~wxWindowBase(): any pushed event >> handle >> rs must have been removed >> Error in sys.exitfunc: >> Traceback (most recent call last): >> File "C:\Programmi\Python27\lib\atexit.py", line 24, in _run_exitfuncs >> func(*targs, **kargs) >> wx._core.PyAssertionError: C++ assertion "GetEventHandler() == this" >> failed >> at . >> .\..\src\common\wincmn.cpp(478) in wxWindowBase::~wxWindowBase(): any >> pushed eve >> nt handlers must have been removed >> > > > Post some code? Sounds like you're trying to interact with a wxPython > object in a function using atexit.register(AtExit)... which likely is > always going to happen after the wx Destroy method is all done. > > -- https://mail.python.org/mailman/listinfo/python-list
Re:Lists
Seymore4Head Wrote in message: > import random > nums=range(1,11) > print (nums) > samp=random.sample(nums,10) > top=nums > newlist=nums[::-1] > tail=newlist > > for x in range(10): > print ("Top {:2d}Tail {:2.0f} Sample {:2d} > ".format(top[x],tail[x],samp[x])) > > I don't understand why the command nums=range(1,11) doesn't work. > I would think that print(nums) should be 1,2,3 ect. > Instead it prints range(1,11) You need to specify that you're using python 3.x In python 2, nums would indeed be a list. And range (500) would be a list of 5 million items, taking quite a while and lots of memory to build. So python 3 uses lazy evaluation when it can. In this case it returns a range sequence type, not a list. https://docs.python.org/3/library/stdtypes.html#typesseq-range If you need the ints all at once, simply call list. nums =list (range (1, 11) > > Why does random.sample(nums,10) give me the numbers between 1 and 10. > I am missing something subtle again. > > It doesn't give you the numbers between 1 and 10, it gives you a list composed of those numbers in an arbitrary order, but with no duplicates. Your question is incomplete. It does that because it's defined to. But clearly you're puzzled. So what is confusing? The fact that there are 10? The fact that they're between 1 and 10 inclusive? Or the fact there are no duplicates? Or something else? You might help your confusion by experimenting. Try 7 instead of 10. Or pick different range limits. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:protocol.py, brine.py, and compat.py causing trouble
Josh English Wrote in message: > I do not know what these three filesare doing, but suddenly they have caught > in a loop every time I try to run some code. > > I grabbed the trace decorator from the python library and this is the last > bit of the output: > > > trollvictims.py(129): if self.current_attack: > trollvictims.py(130): print "returning", self.current_attack, > type(self.current_attack) > (532): protocol.py(439): protocol.py(228): protocol.py(229): > protocol.py(244): brine.py(366): brine.py(368): brine.py(369): > brine.py(369): brine.py(366): brine.py(367): . > This is where I managed to send a keybord interrupt. I was working just fine, > tweaking a line, running the code, tweaking a line, running the code, until > this point. > > I'm on Windows 7 using Python 2.7.5. I should upgrade, and will do so, but > what are these files and why are they suddenly crashing on me? > Since they're not part of the stdlib, and you don't remember writing them, you might get a hint by printing import brine print (brine.__brine__) -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.3.2 help
Hi, We are using windows 7 and it is all pupils as they are more restricted than staff. They are using the python 3.3.2 shell and trying to print from there Thank you, David Moorcroft ICT Operations Manager & Website Manager Turves Green Girls' School - Original Message - From: "Steven D'Aprano" To: python-list@python.org Sent: Wednesday, 10 September, 2014 1:15:49 PM Subject: Re: Python 3.3.2 help Hello, My response is below, interleaved with your comments. D Moorcroft wrote: >> Hi, >> >> We are running Python 3.3.2 but pupils are unable to print as they >> cannot use the command prompt. What operating system are you using? Windows, Linux, Mac? Something else? Is it ALL pupils who are unable to print or just some of them? Which command prompt are they using? Can you reproduce the failure to print? If so, please tell us the detailed steps you (and the pupils) go through. E.g. something like this: "On Windows XP, choose Run from the Start Menu. Type cmd.exe and press Enter. When the terminal window opens, type print 'Hello World' and Enter." It will help if you can tell us whether your pupils are using IDLE, IPython, or the default Python interactive interpreter. If you can answer these questions, which should have a better chance of diagnosing the problem. Further responses below. >> An error comes up saying printing failed (exit status Oxff). Based on this, my guess is that your students are accidentally running the DOS "print" command at the DOS prompt, not Python at all. Perhaps they are forgetting to run the "python" command first to launch the Python interpreter, and are running directly in the DOS prompt? You can check this by reading the command prompt. If it looks like three greater-than signs >>> then you are running in Python's default interpreter. If it looks something like this: C:\Documents and Settings\user\> or perhaps like this: C:\> then you are still inside the DOS command prompt. Unfortunately, I am not very experienced with Windows, so I cannot tell you the right method to start Python. I would expect there to be a Start menu command, perhaps called "IDLE", or "Python", but I'm not sure. >> Is there any way that we can get users who can't see the command >> prompt to be able to print? I'm not entirely sure I understand this question. Can you explain in more detail? By the way, as you know there are two meanings of "print" in computing. There is printing to the screen, and printing to sheets of paper with an actual printer. Which are you intending? Regards, -- Steven -- https://mail.python.org/mailman/listinfo/python-list * This message has been checked for viruses by the Birmingham Grid for Learning. For guidance on good e-mail practice, e-mail viruses and hoaxes please visit: http://www.bgfl.org/emailaup * * This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify postmas...@bgfl.org The views expressed within this email are those of the individual, and not necessarily those of the organisation * -- https://mail.python.org/mailman/listinfo/python-list
Re:CSV methodology
je...@newsguy.com Wrote in message: > > Hello. Back in the '80s, I wrote a fractal generator, which, over the years, > I've modified/etc to run under Windows. I've been an Assembly Language > programmer for decades. Recently, I decided to learn a new language, > and decided on Python, and I just love it, and the various IDEs. > > Anyway, something I thought would be interesting, would be to export > some data from my fractal program (I call it MXP), and write something > in Python and its various scientific data analysis and plotting modules, > and... well, see what's in there. > > An example of the data: > 1.850358651774470E-0002 > 32 > 22 > 27 > ... (this format repeats) > > So, I wrote a procedure in MXP which converts "the data" and exports > a csv file. So far, here's what I've started with: > > --- > import csv > > fname = 'E:/Users/jayte/Documents/Python Scripts/XportTestBlock.csv' > > f = open(fname) > > reader = csv.reader(f) > > for flt in reader: > x = len(flt) > file.close(f) > --- > > This will get me an addressable array, as: > > flt[0], flt[1], flt[350], etc... from which values can be assigned to > other variables, converted... > > My question: Is there a better way? Do I need to learn more about > how csv file are organized? Perhaps I know far too little of Python > to be attempting something like this, just yet. > > Looks to me like your MXP has produced a single line file, with all the values on that single line separated by commas. If the data is really uniform, then it'd be more customary to put one item per line. But your sample seems to imply the data is a float followed by 3 ints. If so, then I'd expect to see a line for each group of 4. The only advantage of a csv is if the data is rectangular. If it's really a single column, it should be one per line, and you'd use readline instead. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:protocol.py, brine.py, and compat.py causing trouble
Dave Angel Wrote in message: > Josh English Wrote in message: >> I do not know what these three filesare doing, but suddenly they have caught >> in a loop every time I try to run some code. >> >> I grabbed the trace decorator from the python library and this is the last >> bit of the output: >> >> >> trollvictims.py(129): if self.current_attack: >> trollvictims.py(130): print "returning", self.current_attack, >> type(self.current_attack) >> (532): protocol.py(439): protocol.py(228): protocol.py(229): >> protocol.py(244): brine.py(366): brine.py(368): brine.py(369): >> brine.py(369): brine.py(366): brine.py(367): > > . > >> This is where I managed to send a keybord interrupt. I was working just >> fine, tweaking a line, running the code, tweaking a line, running the code, >> until this point. >> >> I'm on Windows 7 using Python 2.7.5. I should upgrade, and will do so, but >> what are these files and why are they suddenly crashing on me? >> > > > Since they're not part of the stdlib, and you don't remember > writing them, you might get a hint by printing > import brine > print (brine.__brine__) > Oops, meant print (brine.__file__) -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Shuffle
Michael Torrie Wrote in message: > On 09/13/2014 05:47 PM, Seymore4Head wrote: >> Here is a screenshot of me trying Dave Briccetti's quiz program from >> the shell and it (the shuffle command) works. >> https://www.youtube.com/watch?v=VR-yNEpGk3g >> http://i.imgur.com/vlpVa5i.jpg >> >> Two questions >> If you import random, do you need to "from random import shuffle"? >> >> Why does shuffle work from the command line and not when I add it to >> this program? >> >> import random >> import shuffle >> nums=list(range(1,11)) >> shuffle(nums) >> print (nums) >> >> I get: >> No module named 'shuffle' > > You can do it two ways: > Refer to it as random.shuffle() > > or > > from random import shuffle > > I tend to use the first method (random.shuffle). That way it prevents > my local namespace from getting polluted with random symbols imported > from modules. > > Or a third way: import random shuffle = random.shuffle -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Shuffle
Dave Angel wrote: > Michael Torrie Wrote in message: >> You can do it two ways: >> Refer to it as random.shuffle() >> >> or >> >> from random import shuffle >> >> I tend to use the first method (random.shuffle). That way it prevents >> my local namespace from getting polluted with random symbols imported >> from modules. > > Or a third way: > > import random > shuffle = random.shuffle Our three weapons are: (1) fully qualified names: import random random.shuffle (2) unqualified local imports: from random import shuffle (3) local name binding: import random shuffle = random.shuffle (4) messing about under the hood: shuffle = __import__('random', fromlist=['shuffle']).shuffle (5) and a fanatical devotion to the Pope. A serious question -- what is the point of the fromlist argument to __import__? It doesn't appear to actually do anything. https://docs.python.org/3/library/functions.html#__import__ -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.3.2 help
Hello David, and thanks for replying. More comments below. D Moorcroft wrote: > Hi, > > We are using windows 7 and it is all pupils as they are more restricted > than staff. > > They are using the python 3.3.2 shell and trying to print from there What you are describing does not sound like the sort of error the Python shell will give. Are you able to copy and paste the student's exact input and output, including the complete error message? If not, can you take a screenshot and post that? (As a general rule, we prefer text-based communication rather than pictures. For all we know, there could be blind or other visually-impaired users on this forum who can read text via a screen reader, but cannot contribute when it is a screenshot. But if all else fails, a screenshot is better than nothing.) We would love to help you, but without further information we have no idea what is going on. The more concrete information you can pass on to us, the better. Regards, Steve > > Thank you, > > David Moorcroft > ICT Operations Manager & > Website Manager > Turves Green Girls' School > > - Original Message - > From: "Steven D'Aprano" > To: python-list@python.org > Sent: Wednesday, 10 September, 2014 1:15:49 PM > Subject: Re: Python 3.3.2 help > > Hello, > > My response is below, interleaved with your comments. > > D Moorcroft wrote: > >>> Hi, >>> >>> We are running Python 3.3.2 but pupils are unable to print as they >>> cannot use the command prompt. > > What operating system are you using? Windows, Linux, Mac? Something else? > > Is it ALL pupils who are unable to print or just some of them? > > Which command prompt are they using? Can you reproduce the failure to > print? If so, please tell us the detailed steps you (and the pupils) go > through. E.g. something like this: > > "On Windows XP, choose Run from the Start Menu. Type cmd.exe and press > Enter. When the terminal window opens, type print 'Hello World' and > Enter." > > It will help if you can tell us whether your pupils are using IDLE, > IPython, or the default Python interactive interpreter. > > If you can answer these questions, which should have a better chance of > diagnosing the problem. > > Further responses below. > > >>> An error comes up saying printing failed (exit status Oxff). > > Based on this, my guess is that your students are accidentally running the > DOS "print" command at the DOS prompt, not Python at all. Perhaps they are > forgetting to run the "python" command first to launch the Python > interpreter, and are running directly in the DOS prompt? > > You can check this by reading the command prompt. If it looks like three > greater-than signs >>> then you are running in Python's default > interpreter. If it looks something like this: > > C:\Documents and Settings\user\> > > or perhaps like this: > > C:\> > > then you are still inside the DOS command prompt. > > Unfortunately, I am not very experienced with Windows, so I cannot tell > you the right method to start Python. I would expect there to be a Start > menu command, perhaps called "IDLE", or "Python", but I'm not sure. > > >>> Is there any way that we can get users who can't see the command >>> prompt to be able to print? > > I'm not entirely sure I understand this question. Can you explain in more > detail? > > By the way, as you know there are two meanings of "print" in computing. > There is printing to the screen, and printing to sheets of paper with an > actual printer. Which are you intending? > > > Regards, > > > -- Steven -- https://mail.python.org/mailman/listinfo/python-list
What's the function location that reads the cached .pyc file from disk.
Hi. what's the location of the function that reads the .pyc file ? I bet it should lie in somewhere in https://hg.python.org/cpython/file/322ee2f2e922/Lib/importlib But what's the actual location? Btw, why I need it? I want to know the structure of a .pyc file. Of course the function that reads the .pyc must know something about it. (I am aware of the structure of a typical .pyc file from some clicks of google pages, but I am interested in the *source* and the most authoritative answer, aka, the source code). Thanks. -- 吾輩は猫である。ホームーページはhttp://introo.me。 -- https://mail.python.org/mailman/listinfo/python-list
__import__(name, fromlist=...), was Re: Shuffle
Steven D'Aprano wrote: > A serious question -- what is the point of the fromlist argument to > __import__? It doesn't appear to actually do anything. > > > https://docs.python.org/3/library/functions.html#__import__ It may be for submodules: $ mkdir -p aaa/bbb $ tree . └── aaa └── bbb 2 directories, 0 files $ python3 Python 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> __import__("aaa").bbb Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'bbb' >>> __import__("aaa", fromlist=["bbb"]).bbb -- https://mail.python.org/mailman/listinfo/python-list
Re: Lists
On Mon, 15 Sep 2014 09:05:50 -0400 (EDT), Dave Angel wrote: >Seymore4Head Wrote in message: >> import random >> nums=range(1,11) >> print (nums) >> samp=random.sample(nums,10) >> top=nums >> newlist=nums[::-1] >> tail=newlist >> >> for x in range(10): >> print ("Top {:2d}Tail {:2.0f} Sample {:2d} >> ".format(top[x],tail[x],samp[x])) >> >> I don't understand why the command nums=range(1,11) doesn't work. >> I would think that print(nums) should be 1,2,3 ect. >> Instead it prints range(1,11) > >You need to specify that you're using python 3.x > >In python 2, nums would indeed be a list. And range (500) > would be a list of 5 million items, taking quite a while and lots > of memory to build. So python 3 uses lazy evaluation when it > can. In this case it returns a range sequence type, not a > list. > >https://docs.python.org/3/library/stdtypes.html#typesseq-range > >If you need the ints all at once, simply call list. >nums =list (range (1, 11) > >> >> Why does random.sample(nums,10) give me the numbers between 1 and 10. >> I am missing something subtle again. >> >> > >It doesn't give you the numbers between 1 and 10, it gives you a > list composed of those numbers in an arbitrary order, but with no > duplicates. > >Your question is incomplete. It does that because it's defined > to. But clearly you're puzzled. So what is confusing? The fact > that there are 10? The fact that they're between 1 and 10 > inclusive? Or the fact there are no duplicates? Or something > else? > >You might help your confusion by experimenting. Try 7 instead of > 10. Or pick different range limits. Actually I do understand that random.sample(nums,10) does give a sample of the numbers in the list. What was throwing me off was that nums=range(1,11) did not appear to be a list ,but sample was still treating it as a list. But I also figured out what I really needed to do was nums=list(range(1,11) Thanks everyone. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lists
On Mon, 15 Sep 2014 16:59:36 +1000, Steven D'Aprano wrote: >Seymore4Head wrote: > >> import random >> nums=range(1,11) >> print (nums) >> samp=random.sample(nums,10) >> top=nums >> newlist=nums[::-1] >> tail=newlist >> >> for x in range(10): >> print ("Top {:2d}Tail {:2.0f} Sample {:2d} >> ".format(top[x],tail[x],samp[x])) >> >> I don't understand why the command nums=range(1,11) doesn't work. > >Of course it works. It does exactly what you told it to do: set the >variable "nums" to the result of calling range(1, 11). The only question >is, what does range(1, 11) do? > > >> I would think that print(nums) should be 1,2,3 ect. >> Instead it prints range(1,11) > >Did you read the documentation for range? > >py> help(range) >class range(object) > | range([start,] stop[, step]) -> range object > | > | Returns a virtual sequence of numbers from start to stop by step. > [...] > >range in Python 3 does not return a list. It returns a special object which >provides a sequence of numbers, but without actually storing them all in a >list. > > >> Why does random.sample(nums,10) give me the numbers between 1 and 10. > >What did you expect it to do? Did you read the documentation? > > >py> import random >py> help(random.sample) >Help on method sample in module random: > >sample(self, population, k) method of random.Random instance >Chooses k unique random elements from a population sequence or set. >[...] >To choose a sample in a range of integers, use range as an argument. >This is especially fast and space efficient for sampling from a >large population: sample(range(1000), 60) > >The docs even tell you that (1) sample supports range objects, and (2) using >range is more efficient than lists. > > >> I am missing something subtle again. > >range objects behave *like* lists when you index them: > >py> nums = range(1, 100) >py> nums[0] # First item. >1 >py> nums[-1] # Last item. >99 > >They're even smart enough that you can take a slice, and they give you a new >range object: > >py> nums[1:10] >range(2, 11) > >When you iterate over them, you get each item in turn: > >py> for i in range(1, 4): >... print(i) >... >1 >2 >3 > >range objects are more efficient than lists if the numbers follow the right >sort of pattern. While a list can contain any values you like, in any >order: > >py> nums = [1, 33, 5, 222, 4, 6, 0, 888, 7] > >range objects are limited to a linear sequence of: > >start, start+step, start+2*step, start+3*step, ... > >up to some end value. The reason range is more efficient is that, unlike >lists, it doesn't need to pre-populate all the values required, it can >calculate them on the fly when and as required. The reason why lists are >more flexible is that the values don't have to be calculated as needed, >they can just be stored, ready to use. I see now Thanks everyone -- https://mail.python.org/mailman/listinfo/python-list
Re: Lists
On Mon, Sep 15, 2014 at 1:36 AM, Peter Otten <__pete...@web.de> wrote: > I'd call range() an iterable. I'd even go so far as to call it a sequence. >>> from collections import Sequence >>> issubclass(range, Sequence) True -- https://mail.python.org/mailman/listinfo/python-list
Re: Lists
Ian Kelly wrote: > On Mon, Sep 15, 2014 at 1:36 AM, Peter Otten <__pete...@web.de> wrote: >> I'd call range() an iterable. > > I'd even go so far as to call it a sequence. > from collections import Sequence issubclass(range, Sequence) > True If you want to be as specific as possible call it a range ;) -- https://mail.python.org/mailman/listinfo/python-list
Re: protocol.py, brine.py, and compat.py causing trouble
On 9/13/2014 11:44 PM, Josh English wrote: I do not know what these three filesare doing, but suddenly they have caught in a loop every time I try to run some code. This is where I managed to send a keybord interrupt. I was working just fine, tweaking a line, running the code, tweaking a line, running the code, until this point. That's your clue -- I'd take a close look at the last changes you made a result of which caused this failure and apparent looping. It's easy to lay blame on the (whatever) library and look for a root cause there, but I'd first suspect I did something inappropriate as that's much more likely. Emile -- https://mail.python.org/mailman/listinfo/python-list
Re: Storing instances using jsonpickle
On Wednesday, September 3, 2014 7:19:07 PM UTC-7, Ned Batchelder wrote: > Typically, you need to decide explicitly on a serialized representation > for your data. Even if it's JSON, you need to decide what that JSON > looks like. Then you need to write code that converts the JSON-able > data structure (dict of lists, whatever) into your object. Often a > version number is a good idea so that you have some chance of using old > data as your code changes. > Right now my cheap workaround is to define a function that saves the instances __dict__ using json, and to recreate the object, I create a new object using the __init__ method and cycle through the rest of the json keys and apply them to the new object using setattr. It's a quick and dirty hack, but it seems to be working. I do have to make sure that everything that lands in the instance's __dict__ is serializable, but that's not so tough. I need to add a version number, though. Good idea, that. Josh -- https://mail.python.org/mailman/listinfo/python-list
PyCharm refactoring tool?
I started up an instance of PyCharm last Friday. It's mostly just been sitting there like a bump on a log. I set things up to use Emacs as my editor. It seems most of its functionality won't be all that useful. Most of my work is on libraries/platforms - stuff which is not runnable in isolation, so the Run menu doesn't look all that useful. I have git, etc integrated into my Emacs environment, so don't need the VCS menu. Most everything else looks fairly genertic. Except the Refactor menu. Before I try to do much/anything with it, I thought I would solicit feedback on its capability. Does it work as intended? I read through the PyCharm help sections on refactoring. It seems to describe a number of code refactorings which aren't available for Python code. For example, I don't see an "invert boolean" refactoring. How useful is PyCharm's refactoring subsystem? Thx, Skip -- https://mail.python.org/mailman/listinfo/python-list
Re: PyCharm refactoring tool?
It's pretty useful. I use it for some time now and I very much like it. There are some things that might not be available on Python because of it's duck typing behavior (Pycharm perhaps can't confirm that the type is boolean to suggest it's inversion, for instance). The most powerful for me are the rename refactor and extract. Works like charm (no pun intended). On Mon, Sep 15, 2014 at 4:44 PM, Skip Montanaro wrote: > I started up an instance of PyCharm last Friday. It's mostly just been > sitting there like a bump on a log. I set things up to use Emacs as my > editor. It seems most of its functionality won't be all that useful. Most > of my work is on libraries/platforms - stuff which is not runnable in > isolation, so the Run menu doesn't look all that useful. I have git, etc > integrated into my Emacs environment, so don't need the VCS menu. Most > everything else looks fairly genertic. > > Except the Refactor menu. Before I try to do much/anything with it, I > thought I would solicit feedback on its capability. Does it work as > intended? I read through the PyCharm help sections on refactoring. It seems > to describe a number of code refactorings which aren't available for Python > code. For example, I don't see an "invert boolean" refactoring. > > How useful is PyCharm's refactoring subsystem? > > Thx, > > Skip > > > -- > https://mail.python.org/mailman/listinfo/python-list > > -- George R. C. Silva SIGMA Consultoria http://www.consultoriasigma.com.br/ -- https://mail.python.org/mailman/listinfo/python-list
Re: PyCharm refactoring tool?
George Silva schrieb am 15.09.2014 um 21:49: > It's pretty useful. I use it for some time now and I very much like it. > [...] > The most powerful for me are the rename refactor and extract. Works like > charm (no pun intended). Dito. > On Mon, Sep 15, 2014 at 4:44 PM, Skip Montanaro wrote: >> I started up an instance of PyCharm last Friday. It's mostly just been >> sitting there like a bump on a log. I set things up to use Emacs as my >> editor. It seems most of its functionality won't be all that useful. Most >> of my work is on libraries/platforms - stuff which is not runnable in >> isolation, so the Run menu doesn't look all that useful. I also do most exec stuff on the command line - it needs to work there anyway, so the additional config in PyCharm is really something on top that I often don't do. However, running stuff within PyCharm can still be really handy because it integrates very nicely with py.test and other test runners. You get nice visual feedback for your tests, can rerun failing tests with one click, can visually debug problems, get coverage analysis for free, etc. It's all very nicely integrated. Stefan -- https://mail.python.org/mailman/listinfo/python-list
functools.wraps behaviour
The purpose of 'functools.wraps' is to make a decorated function look like the original function, i.e. such that the __name__, __module__, __doc__ attributes are the same as the wrapped function. However, I've noticed inconsistent behaviour. Given the following: import functools def decorator(func): @functools.wraps(func) def wrapper(self): func(self) return wrapper class Klass: @decorator def method(self): raise Exception('boom!') print('Klass.method:',Klass.method) k = Klass() print('k.method',k.method) try: k.method(1) except Exception as e: print('exception:',e) The output (Python 3.3) is: Klass.method: k.method > exception: wrapper() takes 1 positional argument but 2 were given The first two lines are as expected, using the name of the decorated function. However, the exception uses the name of the decorating wrapper function. Is this a bug in functools? Or is this a language feature? If so, is there a valid argument to change this behaviour? -- isedev -- https://mail.python.org/mailman/listinfo/python-list
python script monitor
I have made an app that is not fully stable and I would like to monitor the performance of the app and try and improve the speed of it. I tried to use the activity monitor on the mac but what I want I'm to see how much ram, cup and other stats on what resources that app is using. Is there any apps to specifically monitor a certain app. I am on Mac is so any suggestions that could work with that would be great. -- https://mail.python.org/mailman/listinfo/python-list
Re: python script monitor
On Tue, Sep 16, 2014 at 10:07 AM, Nicholas Cannon wrote: > I have made an app that is not fully stable and I would like to monitor the > performance of the app and try and improve the speed of it. I tried to use > the activity monitor on the mac but what I want I'm to see how much ram, cup > and other stats on what resources that app is using. Is there any apps to > specifically monitor a certain app. I am on Mac is so any suggestions that > could work with that would be great. > If by "not fully stable" you mean that it sometimes isn't working, then playing with performance is a bad idea. Start by getting it correct, then worry about how fast it is. Otherwise, what do you mean by that? What's not stable about your app? ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: functools.wraps behaviour
On Tue, Sep 16, 2014 at 9:15 AM, ISE Development wrote: > @functools.wraps(func) > def wrapper(self): > func(self) > return wrapper > > try: > k.method(1) > except Exception as e: > print('exception:',e) > > The output (Python 3.3) is: > > Klass.method: > k.method 0x7f2d7c4570d0>> > exception: wrapper() takes 1 positional argument but 2 were given > > The first two lines are as expected, using the name of the decorated > function. However, the exception uses the name of the decorating wrapper > function. In your wrapper, you're swallowing all arguments. That means you're consciously rejecting them, and passing none on. If you want a wrapper to let the wrapped function decide about arguments, try this: def decorator(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): func(self, args, kwargs) return wrapper With that change, the error message reports that it's method() that's rejecting the args. So yes, I'd say this is a feature; you can either let the wrapped function make the decision, or you can have the wrapping function deal with args. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: protocol.py, brine.py, and compat.py causing trouble
On Monday, September 15, 2014 12:12:50 PM UTC-7, Emile van Sebille wrote: > > That's your clue -- I'd take a close look at the last changes you made a > result of which caused this failure and apparent looping. > It's easy to lay blame on the (whatever) library and look for a root > cause there, but I'd first suspect I did something inappropriate as > that's much more likely. > > > Emile I deleted the original post because I had figured out what I had changed. The troubleshooting I had done pointed me to those files, which turn out to be part of PyScripter, my IDE. Oddly enough, once I fixed the actual problem (minutes after posting) it still makes no sense... I had a list of things that I processed and returned, but some refactoring left out filling the return list with anything. I'm not sure what happened, except possibly an endless loop. Josh -- https://mail.python.org/mailman/listinfo/python-list
Re: protocol.py, brine.py, and compat.py causing trouble
On Sunday, September 14, 2014 10:59:07 AM UTC-7, Terry Reedy wrote: > On 9/14/2014 2:44 AM, Josh English wrote: > > > To the best of my knowledge, protocol.py, brine.py, compat.py, are not > part of the stdlib. What have you installed other than Python? What > editor/IDE are you using? Check your lib/site-packages directory. From > a google search, brine.py is a pickle replacement in the rpyc and > dreampie (and other) packages. The other two names are pretty generic > and probably common. > They turned out to be part of PyScripter, my IDE. I think the problem was an enless loop, and eventually a memory error, but I'm not sure. Thanks, Josh -- https://mail.python.org/mailman/listinfo/python-list
Re: python script monitor
On Sep 15, 2014, at 8:07 PM, Nicholas Cannon wrote: > I have made an app that is not fully stable and I would like to monitor the > performance of the app and try and improve the speed of it. I tried to use > the activity monitor on the mac but what I want I'm to see how much ram, cup > and other stats on what resources that app is using. Is there any apps to > specifically monitor a certain app. I am on Mac is so any suggestions that > could work with that would be great. > -- > https://mail.python.org/mailman/listinfo/python-list Have you investigated the (long) list of options to the “top” command? I’ve noticed that most Mac users seem to assume that top won’t show anything that Apple’s Activity Monitor doesn’t show. In fact top is WAY more powerful. It should do pretty much what you want. Bill -- https://mail.python.org/mailman/listinfo/python-list
Re: protocol.py, brine.py, and compat.py causing trouble
On Tue, Sep 16, 2014 at 11:02 AM, Josh English wrote: > I deleted the original post because I had figured out what I had changed. This is primarily a newsgroup and a mailing list. You can't delete posts. The best thing to do is to send a follow-up explaining that you no longer need answers. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: functools.wraps behaviour
On Mon, Sep 15, 2014 at 5:15 PM, ISE Development wrote: > The first two lines are as expected, using the name of the decorated > function. However, the exception uses the name of the decorating wrapper > function. > > Is this a bug in functools? Or is this a language feature? If so, is there a > valid argument to change this behaviour? I believe this is done in order to have useful stack traces. If it said 'method' in the stack trace, it could mislead the person debugging into thinking that method is actually raising the exception, but here the exception is actually coming from wrapped, and method is not even called. -- https://mail.python.org/mailman/listinfo/python-list
Re: List insert at index that is well out of range - behaves like append that too SILENTLY
Harish Tech writes: > Let me demonstrate the problem I encountered : > > I had a list > > a = [1, 2, 3] > > when I did > > a.insert(100, 100) > > [1, 2, 3, 100] > > as list was originally of size 4 and I was trying to insert value at index > 100 , it behaved like append instead of throwing any errors as I was trying > to insert in an index that did not even existed . > > > Should it not throw > > IndexError: list assignment index out of range At least the documentation states that what you observe is the intended behaviour. According to the documentation, "a.insert(i, x)" is equivalent to "a[i:i] = x" (i.e. a slice assignment) and if in a slice "a[i:j]" "i" or "j" are larger then "len(a)", then it is replaced by "len(a)". If this is not what you want, derive your own list type and override its "insert" method. -- https://mail.python.org/mailman/listinfo/python-list
Re: What's the function location that reads the cached .pyc file from disk.
Shiyao Ma writes: > what's the location of the function that reads the .pyc file ? > > I bet it should lie in somewhere in > https://hg.python.org/cpython/file/322ee2f2e922/Lib/importlib > > But what's the actual location? Maybe, you look at the "importlib" source? Note: the function you search is likely implemented in C. Finally, you will likely need to look at the C code. > Btw, why I need it? > I want to know the structure of a .pyc file. Of course the function > that reads the .pyc must know something about it. > (I am aware of the structure of a typical .pyc file from some clicks > of google pages, but I am interested in the *source* and the most > authoritative answer, aka, the source code). In documentation relative to the "marshal" module (internally used for ".pyc" files), I have read that the details may vary between Python versions. As "mashal" is used for ".pyc" files, the same likely applies to ".pyc" files as well. Thus, do not depend too closely on the things you may find by code inspection. -- https://mail.python.org/mailman/listinfo/python-list
[OT] Question about Git branches
Hi all I know there some Git experts on this list, so I hope you don't mind me posting this question here. I am slowly getting comfortable with Git, but there is something that confuses me. You are encouraged to make liberal use of 'branches', and if required you can have multiple branches running concurrently. When you commit changes on one branch, those changes are not visible to other branches until you merge, so each branch can be worked on independently. However, if you are working on a branch and make some changes, those changes are visible to *all* branches until you commit. If you run 'git status' from any branch, you can see all files that have been modified or added. It seems to me that this can be confusing. When you are ready to commit changes on one branch, you have to - - check that it is the currently checked-out branch, which is not always obvious - choose which altered files you want to add to the staging area - stage them and then commit This seems error-prone. Am I missing something? Frank Millman -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] Question about Git branches
"Frank Millman" writes: > I know there some Git experts on this list, so I hope you don't mind > me posting this question here. I do. There may be experts on parquetry flooring in this forum, but a topic is not on-topic merely because some people here may know about it. Please engage with the Git community http://git-scm.com/community> instead of starting non-Python discussions here. -- \ “We must become the change we want to see.” —Mohandas K. Gandhi | `\ | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list