From dmandini@inet.hr Thu Oct 27 03:25:12 2011 From: dmandini@inet.hr (djuro mandinic) Date: Wed, 26 Oct 2011 22:25:12 -0400 Subject: [Tutor] Re: Tutor -- confirmation of subscription -- request 919243 In-Reply-To: References: Message-ID: <20111026222512.266c4d7c.dmandini@inet.hr> On Mon, 05 Nov 2001 08:01:09 -0500 tutor-request@python.org wrote: > Tutor -- confirmation of subscription -- request 919243 > > We have received a request from 213.191.128.202 for subscription of > your email address, , to the tutor@python.org > mailing list. To confirm the request, please send a message to > tutor-request@python.org, and either: > > - maintain the subject line as is (the reply's additional "Re:" is > ok), > > - or include the following line - and only the following line - in the > message body: > > confirm 919243 > > (Simply sending a 'reply' to this message should work from most email > interfaces, since that usually leaves the subject line in the right > form.) > > If you do not wish to subscribe to this list, please simply disregard > this message. Send questions to tutor-admin@python.org. > From alan.gauld at btinternet.com Sat Oct 1 01:19:53 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 01 Oct 2011 00:19:53 +0100 Subject: [Tutor] guess age programme (still stuck!!!!!) In-Reply-To: <4E8624B5.3020305@davea.name> References: , <4E85B6B8.60907@compuscan.co.za> <4E8624B5.3020305@davea.name> Message-ID: On 30/09/11 21:21, Dave Angel wrote: >> print "\n\nGood guess!!" >> input ("\n\nPress the enter key to exit.") > > input() returns a character string. Given the OP's print style I assume he is running Python v2 so input() will evaluate a number as an int. But given that using input() is usually frowned on it would probably be better to convert the input() calls to raw_input() and then convert to int with int() To the OP. You don't actually tell us what is going wrong with your program. How is it failing? Does it just loop forever or is it giving the wrong messages? When you say you are "still stuck" what exactly is happening? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Oct 1 04:36:57 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 01 Oct 2011 12:36:57 +1000 Subject: [Tutor] Input In-Reply-To: References: Message-ID: <4E867CC9.3050500@pearwood.info> Cameron Macleod wrote: > Hi, > > When you type > > Input("\n\nPress The Enter Key To Exit") > > it forces you to press the enter key to close the program. Why is it the > enter key instead of e.g. the 'esc' key? Because the convention is that you use the Enter key to ENTER information. That's why it is called Enter. Your question is kind of like asking "Why do you use a screw driver for driving screws, instead of a socket wrench?" In all terminals I know of, the user's input is collected in a buffer until the Enter key is pressed. Until then, what the user types isn't available to the caller. This is how raw_input (Python 2) and input (Python 3) work. If you want to read the user's input character by character, as they are typed, it is actually quite tricky, but it can be done. You can install a full-blown GUI tool kit, like wxPython or Tkinter, and use that. Or you can use the curses module, which is a bit lighter than Tkinter but still pretty heavyweight. For Linux, there's a FAQ: http://docs.python.org/faq/library.html#how-do-i-get-a-single-keypress-at-a-time On Windows, you can use msvcrt.getch(). -- Steven From steve at pearwood.info Sat Oct 1 06:13:43 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 01 Oct 2011 14:13:43 +1000 Subject: [Tutor] guess age programme (please help) In-Reply-To: References: Message-ID: <4E869377.5030503@pearwood.info> Hi Adrian, ADRIAN KELLY wrote: > Hi all, > can anyone help me with the attached programme. I'd love to, but I can't open it :( If the truth be known, I could open it if I spent the time and effort. But that actually is significant time and effort: in my email, your attachment looks like this: Content-Type: application/octet-stream Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="guess age_game(broken)" DQpwcmludCgiXHRXZWxjb21lIHRvICdHdWVzcyBNeSBOdW1iZXInISIpDQpwcmludCgiSSdtIHRo aW5raW5nIG9mIGEgbnVtYmVyIGJldHdlZW4gMSBhbmQgMTAwLiIpDQpwcmludCgiVHJ5IHRvIGd1 ZXNzIGl0IGluIGFzIGZldyBhdHRlbXB0cyBhcyBwb3NzaWJsZS5cbiIpDQoNCiMgc2V0IHRoZSBp bml0aWFsIHZhbHVlcw0KYWdlID0gMzUNCmd1ZXNzID0gIiAiDQp0cmllcyA9IDUNCg0KIyBndWVz c2luZyBsb29wDQp3aGlsZSBndWVzcyAhPSBhZ2U6DQogICAgDQogICAgZ3Vlc3MgPSBpbnB1dCgi VGFrZSBhIGd1ZXNzOiAiKQ0KICAgIGlmIGd1ZXNzID4gYWdlOg0KICAgICAgICBwcmludCAiTG93 ZXIuLi4iLHRyaWVzLCJsZWZ0Ig0KICAgIGVsc2U6DQogICAgICAgIHByaW50ICJIaWdoZXIuLi4i LHRyaWVzLCJsZWZ0Ig0KICAgICAgICAgICAgDQogICAgdHJpZXM9dHJpZXMtMQ0KICAgDQoNCnBy aW50ICJcblxuWW91IGd1ZXNzZWQgaXQhICBUaGUgYWdlIHdhcyIsIGFnZSwiaXQgb25seSB0b29r IHlvdSAiK2B0cmllc2ArIiBhdHRlbXB0cyB0byBnZXQgaXQiDQoNCiAgDQppbnB1dCAoIlxuXG5Q cmVzcyB0aGUgZW50ZXIga2V5IHRvIGV4aXQuIikNCg== I hope you understand why I don't care enough to go to the time and effort of saving it to a file, decoding it, renaming it, and then finally reading it. You can make it easier for your readers (and therefore increase the number of people able and willing to help) if you do this: (1) For small amounts of code, just copy and paste it into your email. Make sure you send ordinary plain text. No HTML email or "rich text", as that will often break the formatting of the code. (2) For larger amounts, say, more than 50 lines, attach it as a file. Make sure the file has a file extension .txt or .py even if you are using a computer system that doesn't need file extensions. If .py, please make sure the file name is legal for Python: no spaces or brackets or parentheses or dashes. Thanks in advance, -- Steven From amonroe at columbus.rr.com Sat Oct 1 08:06:36 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 1 Oct 2011 02:06:36 -0400 Subject: [Tutor] fake defrag revisited Message-ID: <145120072334.20111001020636@columbus.rr.com> I'm revisiting the fake defrag program I posted about a few months ago. The concept is basically a screensaver or light show where you can enjoy watching entropy being reversed as colored blocks order themselves visually. I set it aside for a while because it was too slow, but I finally came up with a better algorithm for the simulated file creation & deletion. So I can throroughly scramble my imaginary files. Now I want to come up with a simulated defragging, but I wish it for cosmetic reasons to visit the various areas of the drive in a way that appears random, to make it less boring. The fake "drive" is 64 blocks (shown as 8x8 grid onscreen) for test purposes. The files as-is (fragged): freelist:[1, 3, 6, 7, 9, 10, 11, 13, 14, 15, 16, 18, 22, 23, 25, 26, 27, 28, 30, 31, 32, 33, 34, 36, 38, 39, 40, 41, 42, 43, 44, 46, 47, 49, 52, 57, 58, 59, 60, 61, 62, 63] 1000: [45, 0] 1002: [56, 19, 5, 35, 8] 1014: [21, 54, 2, 20, 53, 17, 12, 4, 37, 48] 1013: [50, 51, 55, 24, 29] I can predict the arrangement of the files in the ideal end state (defragged) by sorting the filenames in ascending order then assign them blocks based on an incrementing number and the files' known sizes: freelist: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63] 1000: [0, 1] 1002: [2, 3, 4, 5, 6] 1013: [7, 8, 9, 10, 11] 1014: [12, 13, 14, 15, 16, 17, 18, 19, 20, 21] Which gives this list of before and after blocks: i.e. block 0 is destined to live at 1 after defrag, block 1 is destined to live at 22, etc. [(0, 1), (1, 22), (2, 14), (3, 23), (4, 19), (5, 4), (6, 24), (7, 25), (8, 6), (9, 26), (10, 27), (11, 28), (12, 18), (13, 29), (14, 30), (15, 31), (16, 32), (17, 17), (18, 33), (19, 3), (20, 15), (21, 12), (22, 34), (23, 35), (24, 10), (25, 36), (26, 37), (27, 38 ), (28, 39), (29, 11), (30, 40), (31, 41), (32, 42), (33, 43), (34, 44), (35, 5), (36, 45), (37, 20), (38, 46), (39, 47), (40, 48), (41, 49), (42, 50), (43, 51), (44, 52), (45, 0), (46, 53), (47, 54), (48, 21), (49, 55), (50, 7), (51, 8), (52, 56), (53, 16), (54, 13), (55, 9), (56, 2), (57, 57), (58, 58), (59, 59), (60, 60), (61, 61), (62, 62), (63, 63)] I initially thought I could just do a random.shuffle on this list to achieve the cosmetic randomness, until I realized the real problem is magically determining the correct sequence in which to perform the moves without ruining a future move inadverently. If I move 0-to-1 first, I've now ruined the future 1-to-22 which ought to have taken place in advance. Is there a deterministic-yet-seemingly-random algorithm out there whose name I wasn't aware of to be able to google it? Alan From alan.gauld at btinternet.com Sat Oct 1 10:15:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 01 Oct 2011 09:15:15 +0100 Subject: [Tutor] guess age programme (please help) In-Reply-To: <4E869377.5030503@pearwood.info> References: <4E869377.5030503@pearwood.info> Message-ID: On 01/10/11 05:13, Steven D'Aprano wrote: > (2) For larger amounts, say, more than 50 lines, attach it as a file. Or put it on one of the several public web pastebins. That will give us all syntax colouring and no ambiguity about indentation levels etc that often seems to occur via email. http://en.wikipedia.org/wiki/Comparison_of_pastebins provides a list... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Sat Oct 1 13:48:21 2011 From: d at davea.name (Dave Angel) Date: Sat, 01 Oct 2011 07:48:21 -0400 Subject: [Tutor] fake defrag revisited In-Reply-To: <145120072334.20111001020636@columbus.rr.com> References: <145120072334.20111001020636@columbus.rr.com> Message-ID: <4E86FE05.8040608@davea.name> On 10/01/2011 02:06 AM, R. Alan Monroe wrote: > I'm revisiting the fake defrag program I posted about a few months > ago. The concept is basically a screensaver or light show where you > can enjoy watching entropy being reversed as colored blocks order > themselves visually. > > I set it aside for a while because it was too slow, but I finally came > up with a better algorithm for the simulated file creation& deletion. > So I can throroughly scramble my imaginary files. > > Now I want to come up with a simulated defragging, but I wish it for > cosmetic reasons to visit the various areas of the drive in a way that > appears random, to make it less boring. > > The fake "drive" is 64 blocks (shown as 8x8 grid onscreen) for test > purposes. > > The files as-is (fragged): > freelist:[1, 3, 6, 7, 9, 10, 11, 13, 14, 15, 16, 18, 22, 23, 25, 26, 27, 28, 30, 31, 32, 33, 34, 36, 38, 39, 40, 41, 42, 43, 44, 46, 47, 49, 52, 57, 58, 59, 60, 61, 62, 63] > 1000: [45, 0] > 1002: [56, 19, 5, 35, 8] > 1014: [21, 54, 2, 20, 53, 17, 12, 4, 37, 48] > 1013: [50, 51, 55, 24, 29] > > I can predict the arrangement of the files in the ideal end state > (defragged) by sorting the filenames in ascending order then assign > them blocks based on an incrementing number and the files' known > sizes: > freelist: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63] > 1000: [0, 1] > 1002: [2, 3, 4, 5, 6] > 1013: [7, 8, 9, 10, 11] > 1014: [12, 13, 14, 15, 16, 17, 18, 19, 20, 21] > > > Which gives this list of before and after blocks: i.e. block 0 is > destined to live at 1 after defrag, block 1 is destined to live at 22, > etc. > > [(0, 1), (1, 22), (2, 14), (3, 23), (4, 19), (5, 4), (6, 24), (7, 25), > (8, 6), (9, 26), (10, 27), (11, 28), (12, 18), (13, 29), (14, 30), > (15, 31), (16, 32), (17, 17), (18, 33), (19, 3), (20, 15), (21, 12), > (22, 34), (23, 35), (24, 10), (25, 36), (26, 37), (27, 38 ), (28, 39), > (29, 11), (30, 40), (31, 41), (32, 42), (33, 43), (34, 44), (35, 5), > (36, 45), (37, 20), (38, 46), (39, 47), (40, 48), (41, 49), (42, 50), > (43, 51), (44, 52), (45, 0), (46, 53), (47, 54), (48, 21), (49, 55), > (50, 7), (51, 8), (52, 56), (53, 16), (54, 13), (55, 9), (56, 2), (57, > 57), (58, 58), (59, 59), (60, 60), (61, 61), (62, 62), (63, 63)] > > I initially thought I could just do a random.shuffle on this list to > achieve the cosmetic randomness, until I realized the real problem is > magically determining the correct sequence in which to perform the > moves without ruining a future move inadverently. > > If I move 0-to-1 first, I've now ruined the future 1-to-22 which ought > to have taken place in advance. > Not true. In most sorts, data is moved multiple times. The only real constraint on the moves is the end point, which is a sorted form. > Is there a deterministic-yet-seemingly-random algorithm out there > whose name I wasn't aware of to be able to google it? > > Alan > I'm assuming the purpose is NOT to produce a good (ie. fast) algorithm for the actual moving of data on a disk drive, but rather to produce a pretty display. For one thing, you've pre-defined what order the free space blocks are going to be, even though that doesn't matter. For a deterministic algorithm, simply sort that list of tuples, based on the second item. The sort will swap two tuples each time, and they will gradually become more ordered. Whether this will appear visually random depends partly on what your initial order is, and on which sort algorithm you implement. If you use the builtin sort (by supplying your own compare function callback), you can add the visual swap each time your comparator will return true. Or you could use a bubble sort, which won't generally look as random. For another, non-deterministic approach, since you've already determined the final order, start by randomly choosing a cell. If the cell is in the right place, continue picking randomly until you've found a cell that's in the wrong place. Then swap it with its destination location, which clearly is in the wrong place. Now if that one isn't in the right place (after swapping), do another swap to the location it belongs. Repeat until the swap makes both ends correct. At that point, check the count of how many cells have ended up in the correct place, and if there are still more, loop back to the random function. You could make that deterministic by replacing the random with a simple linear search. In that case, you're done when that linear search hits the end of the list. But of course it wouldn't look as random to the end user. If you are willing to eliminate deterministic entirely, then randomly pick two cells, calculate the distance each is from its correct location, and swap them if the sum of the distances would improve with the swap. On this one it'd be tricky to directly know when to quit, so you could do a linear check for correctness every N loops through the random code. I think this'd make a pretty display, probably because it's not optimal. -- DaveA From amonroe at columbus.rr.com Sat Oct 1 17:53:18 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 1 Oct 2011 11:53:18 -0400 Subject: [Tutor] fake defrag revisited In-Reply-To: <4E86FE05.8040608@davea.name> References: <145120072334.20111001020636@columbus.rr.com> <4E86FE05.8040608@davea.name> Message-ID: <150155273711.20111001115318@columbus.rr.com> >> achieve the cosmetic randomness, until I realized the real problem is >> magically determining the correct sequence in which to perform the >> moves without ruining a future move inadverently. >> >> If I move 0-to-1 first, I've now ruined the future 1-to-22 which ought >> to have taken place in advance. > For a deterministic algorithm, simply sort that list of tuples, based on > the second item. Thanks, although I'm not seeing how that helps: [(63, 63), (62, 62), (61, 61), (60, 60), (59, 59), (58, 58), (57, 57), (52, 56), (49, 55), (47, 54), (46, 53), (44, 52), (43, 51), ( 42, 50), (41, 49), (40, 48), (39, 47), (38, 46), (36, 45), (34, 44), (33, 43), (32, 42), (31, 41), (30, 40), (28, 39), (27, 38), (26 , 37), (25, 36), (23, 35), (22, 34), (18, 33), (16, 32), (15, 31), (14, 30), (13, 29), (11, 28), (10, 27), (9, 26), (7, 25), (6, 24) , (3, 23), (1, 22), (48, 21), (37, 20), (4, 19), (12, 18), (17, 17), (53, 16), (20, 15), (2, 14), (54, 13), (21, 12), (29, 11), (24, 10), (55, 9), (51, 8), (50, 7), (8, 6), (35, 5), (5, 4), (19, 3), (56, 2), (0, 1), (45, 0)] This still suffers the same ruin-a-downstream-move problem when you see 35-to-5 ruining the future move 5-to-4. Alan From d at davea.name Sat Oct 1 20:03:44 2011 From: d at davea.name (Dave Angel) Date: Sat, 01 Oct 2011 14:03:44 -0400 Subject: [Tutor] fake defrag revisited In-Reply-To: <150155273711.20111001115318@columbus.rr.com> References: <145120072334.20111001020636@columbus.rr.com> <4E86FE05.8040608@davea.name> <150155273711.20111001115318@columbus.rr.com> Message-ID: <4E875600.4060400@davea.name> On 10/01/2011 11:53 AM, R. Alan Monroe wrote: >>> achieve the cosmetic randomness, until I realized the real problem is >>> magically determining the correct sequence in which to perform the >>> moves without ruining a future move inadverently. >>> >>> If I move 0-to-1 first, I've now ruined the future 1-to-22 which ought >>> to have taken place in advance. >> For a deterministic algorithm, simply sort that list of tuples, based on >> the second item. > Thanks, although I'm not seeing how that helps: > [(63, 63), (62, 62), (61, 61), (60, 60), (59, 59), (58, 58), (57, 57), > (52, 56), (49, 55), (47, 54), (46, 53), (44, 52), (43, 51), ( 42, 50), > (41, 49), (40, 48), (39, 47), (38, 46), (36, 45), (34, 44), (33, 43), > (32, 42), (31, 41), (30, 40), (28, 39), (27, 38), (26 , 37), (25, 36), > (23, 35), (22, 34), (18, 33), (16, 32), (15, 31), (14, 30), (13, 29), > (11, 28), (10, 27), (9, 26), (7, 25), (6, 24) , (3, 23), (1, 22), (48, > 21), (37, 20), (4, 19), (12, 18), (17, 17), (53, 16), (20, 15), (2, > 14), (54, 13), (21, 12), (29, 11), (24, 10), (55, 9), (51, 8), (50, > 7), (8, 6), (35, 5), (5, 4), (19, 3), (56, 2), (0, 1), (45, 0)] > This still suffers the same ruin-a-downstream-move problem when you > see 35-to-5 ruining the future move 5-to-4. > > Alan You missed the rest of the paragraph. Don't wait for the sort to finish, you do the swapping in the compare function. +++ For a deterministic algorithm, simply sort that list of tuples, based on the second item. The sort will swap two tuples each time, and they will gradually become more ordered. Whether this will appear visually random depends partly on what your initial order is, and on which sort algorithm you implement. If you use the builtin sort (by supplying your own compare function callback), you can add the visual swap each time your comparator will return true. +++ Are you running Python 3.* ? If so, they dropped the compare function parameter, so you'd have to roll your own. What version are you using? In Python 2.x, you can call it as dummy = sorted(mylist, cmp=comp_function) Where comp_function is a function that takes two arguments (in your case each is a two-tuple). Normally, you'd just compare the second member of each tuple, and if less, do your swap of the corresponding items in your display. ..... Continuing on with the same paragraph: +++ Or you could use a bubble sort, which won't generally look as random. +++ In this case, you write your own sort function, calling a common function for doing the comparison, and another to do the actual swap. And when you're swapping the tuples, you can also swap the display. -- DaveA From bgeddy at gmail.com Sat Oct 1 20:52:09 2011 From: bgeddy at gmail.com (Ed Hughes) Date: Sat, 1 Oct 2011 19:52:09 +0100 Subject: [Tutor] Input Message-ID: Have a look at the Windows/Unix/Linux solution posted in the ActiveState Python Recipes, (a fantastic resource), here - a bit long winded maybe but it works fine under Linux and Windows for me. It's pretty much based on the standard docs solution as already mentioned for Linux/Unix. It use the tty and termios modules in Unix/Linux and the msvcrt module in Windows, again, as already mentioned. BgEddy On 1 October 2011 11:00, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Input (Steven D'Aprano) > 2. Re: guess age programme (please help) (Steven D'Aprano) > 3. fake defrag revisited (R. Alan Monroe) > 4. Re: guess age programme (please help) (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 01 Oct 2011 12:36:57 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Input > Message-ID: <4E867CC9.3050500 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Cameron Macleod wrote: > > Hi, > > > > When you type > > > > Input("\n\nPress The Enter Key To Exit") > > > > it forces you to press the enter key to close the program. Why is it the > > enter key instead of e.g. the 'esc' key? > > Because the convention is that you use the Enter key to ENTER > information. That's why it is called Enter. > > Your question is kind of like asking "Why do you use a screw driver for > driving screws, instead of a socket wrench?" > > In all terminals I know of, the user's input is collected in a buffer > until the Enter key is pressed. Until then, what the user types isn't > available to the caller. This is how raw_input (Python 2) and input > (Python 3) work. > > If you want to read the user's input character by character, as they are > typed, it is actually quite tricky, but it can be done. You can install > a full-blown GUI tool kit, like wxPython or Tkinter, and use that. Or > you can use the curses module, which is a bit lighter than Tkinter but > still pretty heavyweight. For Linux, there's a FAQ: > > > http://docs.python.org/faq/library.html#how-do-i-get-a-single-keypress-at-a-time > > On Windows, you can use msvcrt.getch(). > > > -- > Steven > > > ------------------------------ > > Message: 2 > Date: Sat, 01 Oct 2011 14:13:43 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] guess age programme (please help) > Message-ID: <4E869377.5030503 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Hi Adrian, > > ADRIAN KELLY wrote: > > Hi all, > > can anyone help me with the attached programme. > > I'd love to, but I can't open it :( > > If the truth be known, I could open it if I spent the time and effort. > But that actually is significant time and effort: in my email, your > attachment looks like this: > > Content-Type: application/octet-stream > Content-Transfer-Encoding: base64 > Content-Disposition: attachment; filename="guess age_game(broken)" > > > DQpwcmludCgiXHRXZWxjb21lIHRvICdHdWVzcyBNeSBOdW1iZXInISIpDQpwcmludCgiSSdtIHRo > > aW5raW5nIG9mIGEgbnVtYmVyIGJldHdlZW4gMSBhbmQgMTAwLiIpDQpwcmludCgiVHJ5IHRvIGd1 > > ZXNzIGl0IGluIGFzIGZldyBhdHRlbXB0cyBhcyBwb3NzaWJsZS5cbiIpDQoNCiMgc2V0IHRoZSBp > > bml0aWFsIHZhbHVlcw0KYWdlID0gMzUNCmd1ZXNzID0gIiAiDQp0cmllcyA9IDUNCg0KIyBndWVz > > c2luZyBsb29wDQp3aGlsZSBndWVzcyAhPSBhZ2U6DQogICAgDQogICAgZ3Vlc3MgPSBpbnB1dCgi > > VGFrZSBhIGd1ZXNzOiAiKQ0KICAgIGlmIGd1ZXNzID4gYWdlOg0KICAgICAgICBwcmludCAiTG93 > > ZXIuLi4iLHRyaWVzLCJsZWZ0Ig0KICAgIGVsc2U6DQogICAgICAgIHByaW50ICJIaWdoZXIuLi4i > > LHRyaWVzLCJsZWZ0Ig0KICAgICAgICAgICAgDQogICAgdHJpZXM9dHJpZXMtMQ0KICAgDQoNCnBy > > aW50ICJcblxuWW91IGd1ZXNzZWQgaXQhICBUaGUgYWdlIHdhcyIsIGFnZSwiaXQgb25seSB0b29r > > IHlvdSAiK2B0cmllc2ArIiBhdHRlbXB0cyB0byBnZXQgaXQiDQoNCiAgDQppbnB1dCAoIlxuXG5Q > cmVzcyB0aGUgZW50ZXIga2V5IHRvIGV4aXQuIikNCg== > > > I hope you understand why I don't care enough to go to the time and > effort of saving it to a file, decoding it, renaming it, and then > finally reading it. > > You can make it easier for your readers (and therefore increase the > number of people able and willing to help) if you do this: > > (1) For small amounts of code, just copy and paste it into your email. > Make sure you send ordinary plain text. No HTML email or "rich text", as > that will often break the formatting of the code. > > (2) For larger amounts, say, more than 50 lines, attach it as a file. > Make sure the file has a file extension .txt or .py even if you are > using a computer system that doesn't need file extensions. If .py, > please make sure the file name is legal for Python: no spaces or > brackets or parentheses or dashes. > > > Thanks in advance, > > > > -- > Steven > > > ------------------------------ > > Message: 3 > Date: Sat, 1 Oct 2011 02:06:36 -0400 > From: "R. Alan Monroe" > To: tutor at python.org > Subject: [Tutor] fake defrag revisited > Message-ID: <145120072334.20111001020636 at columbus.rr.com> > Content-Type: text/plain; charset=us-ascii > > I'm revisiting the fake defrag program I posted about a few months > ago. The concept is basically a screensaver or light show where you > can enjoy watching entropy being reversed as colored blocks order > themselves visually. > > I set it aside for a while because it was too slow, but I finally came > up with a better algorithm for the simulated file creation & deletion. > So I can throroughly scramble my imaginary files. > > Now I want to come up with a simulated defragging, but I wish it for > cosmetic reasons to visit the various areas of the drive in a way that > appears random, to make it less boring. > > The fake "drive" is 64 blocks (shown as 8x8 grid onscreen) for test > purposes. > > The files as-is (fragged): > freelist:[1, 3, 6, 7, 9, 10, 11, 13, 14, 15, 16, 18, 22, 23, 25, 26, 27, > 28, 30, 31, 32, 33, 34, 36, 38, 39, 40, 41, 42, 43, 44, 46, 47, 49, 52, 57, > 58, 59, 60, 61, 62, 63] > 1000: [45, 0] > 1002: [56, 19, 5, 35, 8] > 1014: [21, 54, 2, 20, 53, 17, 12, 4, 37, 48] > 1013: [50, 51, 55, 24, 29] > > I can predict the arrangement of the files in the ideal end state > (defragged) by sorting the filenames in ascending order then assign > them blocks based on an incrementing number and the files' known > sizes: > freelist: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, > 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, > 57, 58, 59, 60, 61, 62, 63] > 1000: [0, 1] > 1002: [2, 3, 4, 5, 6] > 1013: [7, 8, 9, 10, 11] > 1014: [12, 13, 14, 15, 16, 17, 18, 19, 20, 21] > > > Which gives this list of before and after blocks: i.e. block 0 is > destined to live at 1 after defrag, block 1 is destined to live at 22, > etc. > > [(0, 1), (1, 22), (2, 14), (3, 23), (4, 19), (5, 4), (6, 24), (7, 25), > (8, 6), (9, 26), (10, 27), (11, 28), (12, 18), (13, 29), (14, 30), > (15, 31), (16, 32), (17, 17), (18, 33), (19, 3), (20, 15), (21, 12), > (22, 34), (23, 35), (24, 10), (25, 36), (26, 37), (27, 38 ), (28, 39), > (29, 11), (30, 40), (31, 41), (32, 42), (33, 43), (34, 44), (35, 5), > (36, 45), (37, 20), (38, 46), (39, 47), (40, 48), (41, 49), (42, 50), > (43, 51), (44, 52), (45, 0), (46, 53), (47, 54), (48, 21), (49, 55), > (50, 7), (51, 8), (52, 56), (53, 16), (54, 13), (55, 9), (56, 2), (57, > 57), (58, 58), (59, 59), (60, 60), (61, 61), (62, 62), (63, 63)] > > I initially thought I could just do a random.shuffle on this list to > achieve the cosmetic randomness, until I realized the real problem is > magically determining the correct sequence in which to perform the > moves without ruining a future move inadverently. > > If I move 0-to-1 first, I've now ruined the future 1-to-22 which ought > to have taken place in advance. > > Is there a deterministic-yet-seemingly-random algorithm out there > whose name I wasn't aware of to be able to google it? > > Alan > > > > ------------------------------ > > Message: 4 > Date: Sat, 01 Oct 2011 09:15:15 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] guess age programme (please help) > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 01/10/11 05:13, Steven D'Aprano wrote: > > > (2) For larger amounts, say, more than 50 lines, attach it as a file. > > Or put it on one of the several public web pastebins. > That will give us all syntax colouring and no ambiguity about > indentation levels etc that often seems to occur via email. > > http://en.wikipedia.org/wiki/Comparison_of_pastebins > > provides a list... > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 92, Issue 2 > ************************************ > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Sat Oct 1 23:11:47 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 1 Oct 2011 22:11:47 +0100 Subject: [Tutor] guess age programme (please help) In-Reply-To: <4E869377.5030503@pearwood.info> References: <4E869377.5030503@pearwood.info> Message-ID: Hi, On 1 October 2011 05:13, Steven D'Aprano wrote: > Hi all, can anyone help me with the attached programme. >> > > ADRIAN KELLY wrote: > I'd love to, but I can't open it :( > > If the truth be known, I could open it if I spent the time and effort. But > that actually is significant time and effort: in my email, your attachment > looks like this: > Strange, does your mail program not allow you to just save the attachment as an untyped file without extension? I had no problem saving the attachement and renaming it to have a .py extension (use GMail). Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Sun Oct 2 05:20:01 2011 From: suryak at live.com (surya kasturi ) Date: Sun, 2 Oct 2011 03:20:01 +0000 Subject: [Tutor] How to give input to a list Message-ID: Hi, How give input to a list all at once. I mean if we declared a array and like to take input for it for (i=0;i<5;i++) scanf("%d",&array[i]); here we can give input of 5 numbers with a space in command prompt. Similarly in python if i create a list and do similar process list = [ [ ], [ ] ] for i in range (0,2): for j in range (0, 2): list[i].append ( int (raw_input()) ) here, I am expecting a list like [ [1,2] , [3,4] ] but when I give 1,2,3,4 with space in command prompt at once, it shows error. How do i overcome this problem? Actually my problem goes to sudoku solver where i need to take input all at once. What should i do ? From rdmoores at gmail.com Sun Oct 2 07:17:08 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 1 Oct 2011 22:17:08 -0700 Subject: [Tutor] How to "refresh" the interactive prompt? Message-ID: Python 3.2.2, Win 7 When using the Python 3 interactive prompt, is there a way to quickly "refresh" the prompt? By "refresh" I mean get a new interactive prompt with nothing imported and all things like a = "qwerty", n = 123, etc. no longer in effect. Not sure what the wording should be for that. "imports cancelled and variables deleted"? I know I can do that by entering a Ctrl+z, followed by entering "python". But could print() be used to do the same thing? I can get a beep with print("\a"), or clear the screen with import os; print(os.system("CLS"),chr(13)," ",chr(13)), but how to print a ^Z? Dick Moores From bodsda at googlemail.com Sun Oct 2 09:05:07 2011 From: bodsda at googlemail.com (Bod Soutar) Date: Sun, 2 Oct 2011 08:05:07 +0100 Subject: [Tutor] How to give input to a list In-Reply-To: References: Message-ID: On 2 October 2011 04:20, surya kasturi wrote: > Hi, > > How give input to a list all at once. > I mean if we declared a array and like to take input for it > > for (i=0;i<5;i++) > ? ? scanf("%d",&array[i]); > here we can give input of 5 numbers with a space in command prompt. > > Similarly in python if i create a list and do similar process > > list = [ [ ], [ ] ] > for i in range (0,2): > ? ? ? ?for j in range (0, 2): > ? ? ? ? ? ? ? ? list[i].append ( int (raw_input()) ) > > here, I am expecting a list like > [ [1,2] , [3,4] ] > > but when I give 1,2,3,4 with space in command prompt at once, it shows error. > > How do i overcome this problem? > > Actually my problem goes to sudoku solver where i need to take input all at once. What should i do ? > Can you paste the traceback please, and elaborate slightly on what you mean by 'with a space in command prompt once'. Note that you will have to enter 1,2,3,4 individually 1 2 3 4 Rather than 1,2,3,4 Hope this helps, Bodsda From alan.gauld at btinternet.com Sun Oct 2 10:36:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Oct 2011 09:36:18 +0100 Subject: [Tutor] How to give input to a list In-Reply-To: References: Message-ID: On 02/10/11 04:20, surya kasturi wrote: > for (i=0;i<5;i++) > scanf("%d",&array[i]); > here we can give input of 5 numbers with a space in command prompt. In Python we would normally read the entire string using raw_input() then split the string into its constituent parts like: inStr = raw_input('Type 5 numbers:') array = [int(d) for d in inStr.split()] > list = [ [ ], [ ] ] > for i in range (0,2): > for j in range (0, 2): > list[i].append ( int (raw_input()) ) > > here, I am expecting a list like > [ [1,2] , [3,4] ] > > but when I give 1,2,3,4 with space in command prompt at once, it shows error. That's because int() cannot convert '1 2 3 4' into an integer. int() is like atoi() in C. > How do i overcome this problem? first get a list of numbers then put them into the structure you want: inStr = raw_input('Type 4 numbers:') array = [int(d) for d in inStr.split()] list = [ [array[:2], [array[2:4] ] HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Oct 2 10:41:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Oct 2011 09:41:06 +0100 Subject: [Tutor] How to "refresh" the interactive prompt? In-Reply-To: References: Message-ID: On 02/10/11 06:17, Richard D. Moores wrote: > "refresh" the prompt? By "refresh" I mean get a new interactive prompt > with nothing imported and all things like a = "qwerty", n = 123, > etc. no longer in effect. Not sure what the wording should be for > that. "imports cancelled and variables deleted"? If using the standard console prompt the answer is no. There may be some IDEs that can do that (I thought I'd seen it somewhere but can't recall where! I don't see it in IDLE...) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Oct 2 10:47:17 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 02 Oct 2011 19:47:17 +1100 Subject: [Tutor] How to "refresh" the interactive prompt? In-Reply-To: References: Message-ID: <4E882515.3020809@pearwood.info> Richard D. Moores wrote: > Python 3.2.2, Win 7 > > When using the Python 3 interactive prompt, is there a way to quickly > "refresh" the prompt? By "refresh" I mean get a new interactive prompt > with nothing imported and all things like a = "qwerty", n = 123, > etc. no longer in effect. Not sure what the wording should be for > that. "imports cancelled and variables deleted"? That would be "start a fresh interpreter session". And the easiest way to start a fresh interpreter session is, indeed, to exit the current session and start a fresh one, just as you describe. > I know I can do that by entering a Ctrl+z, followed by entering > "python". But could print() be used to do the same thing? I can get a > beep with print("\a"), or clear the screen with import os; > print(os.system("CLS"),chr(13)," ",chr(13)), but how to print a ^Z? Printing a ^Z is easy, you just have to know what character code ^Z corresponds to. That's chr(26) or 1A in hexadecimal, so this works: >>> print('\x1A') ? But as you can see, that just prints a character. You need to get Ctrl-Z into the *input* stream, not the *output* stream, to exit the interpreter. If you are doing it manually, the easiest way is just to type Ctrl-Z. If doing it programmatically, use either of these: sys.exit() raise SystemExit There is no easy way to reset the current interpreter session to "as new". I suppose you could try something like this: sys.modules[:] = [] globals().clear() but that won't necessarily reset everything to a fresh state. -- Steven From __peter__ at web.de Sun Oct 2 11:04:11 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Oct 2011 11:04:11 +0200 Subject: [Tutor] How to give input to a list References: Message-ID: surya kasturi wrote: > Hi, > > How give input to a list all at once. > I mean if we declared a array and like to take input for it > > for (i=0;i<5;i++) > scanf("%d",&array[i]); > here we can give input of 5 numbers with a space in command prompt. > > Similarly in python if i create a list and do similar process > > list = [ [ ], [ ] ] > for i in range (0,2): > for j in range (0, 2): > list[i].append ( int (raw_input()) ) > > here, I am expecting a list like > [ [1,2] , [3,4] ] > > but when I give 1,2,3,4 with space in command prompt at once, it shows > error. > > How do i overcome this problem? > > Actually my problem goes to sudoku solver where i need to take input all > at once. What should i do ? raw_input() takes one line of input that you can process as you like. Just make it clear to the user what you expect: >>> def input_ints(n): ... s = raw_input("enter %d ints, separated by space " % n) ... values = [int(t) for t in s.split()] ... if len(values) != n: ... raise ValueError("requested %d ints, but got %d" % (n, len(values))) ... return values ... >>> N = 2 >>> values = input_ints(N*N) enter 4 ints, separated by space 1 2 3 4 >>> square = [values[start:start+N] for start in range(0, N*N, N)] >>> square [[1, 2], [3, 4]] Instead of square = [...] which is called "list comprehension" you can continue to use nested loops if you find that easier to understand: >>> square = [] >>> index = 0 >>> for y in range(N): ... row = [] ... for x in range(N): ... row.append(values[index]) ... index += 1 ... square.append(row) ... >>> square [[1, 2], [3, 4]] Personally I would ask for one row at a time: >>> square = [] >>> for y in range(N): ... square.append(input_ints(N)) ... enter 2 ints, separated by space 10 20 enter 2 ints, separated by space 30 40 >>> square [[10, 20], [30, 40]] From rdmoores at gmail.com Sun Oct 2 11:55:53 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 2 Oct 2011 02:55:53 -0700 Subject: [Tutor] How to "refresh" the interactive prompt? In-Reply-To: <4E882515.3020809@pearwood.info> References: <4E882515.3020809@pearwood.info> Message-ID: On Sun, Oct 2, 2011 at 01:47, Steven D'Aprano wrote: > Richard D. Moores wrote: >> >> Python 3.2.2, Win 7 >> >> When using the Python 3 interactive prompt, is there a way to quickly >> "refresh" the prompt? By "refresh" I mean get a new interactive prompt >> with nothing imported and all things like ?a = "qwerty", ? n = 123, >> etc. no longer in effect. Not sure what the wording should be for >> that. "imports cancelled and variables deleted"? > > That would be "start a fresh interpreter session". Thanks. > And the easiest way to start a fresh interpreter session is, indeed, to exit > the current session and start a fresh one, just as you describe. > > >> I know I can do that by entering a Ctrl+z, followed by entering >> "python". But could print() be used to do the same thing? I can get a >> beep with print("\a"), or clear the screen with ? import os; >> print(os.system("CLS"),chr(13)," ",chr(13)), but how to print a ^Z? > > Printing a ^Z is easy, you just have to know what character code ^Z > corresponds to. That's chr(26) or 1A in hexadecimal, so this works: > >>>> print('\x1A') > ? > > > But as you can see, that just prints a character. > > You need to get Ctrl-Z into the *input* stream, not the *output* stream, to > exit the interpreter. If you are doing it manually, the easiest way is just > to type Ctrl-Z. If doing it programmatically, use either of these: > > sys.exit() > raise SystemExit > > > There is no easy way to reset the current interpreter session to "as new". I > suppose you could try something like this: > > > sys.modules[:] = [] > globals().clear() > > but that won't necessarily reset everything to a fresh state. Actually, my goal was to create an Active Word () that would do the job, and I needed to know how to close the interactive prompt as the first step in that AW. I should have thought of sys.exit(), but I didn't. This is OT, but here's the Active Word script that what I want -- to close the current interpreter session and start a fresh one: import syssys.exit()python. The Active Word I chose is "fresh". Here it is in action: Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Windows\System32>python Python 3.2.2 (default, Sep 4 2011, 09:07:29) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = 1234 >>> from math import sqrt >>> sqrt(a) 35.12833614050059 (right her is where I called my AW script, "fresh") >>> import sys >>> sys.exit() C:\Windows\System32>python Python 3.2.2 (default, Sep 4 2011, 09:07:29) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> sqrt(a) Traceback (most recent call last): File "", line 1, in NameError: name 'sqrt' is not defined >>> a Traceback (most recent call last): File "", line 1, in NameError: name 'a' is not defined >>> Thanks, Steven! Dick From g.nius.ck at gmail.com Mon Oct 3 02:33:35 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Sun, 2 Oct 2011 20:33:35 -0400 Subject: [Tutor] String switch Message-ID: Dear Tutors, I was wondering how one would make it so all the cases of all the strings in a python file where switched. I know that for individual strings, you can use .swapcase(), but I'm making a program to edit others, so it would be easier to just do something at the top that would switch all other strings. Thank you in advance. Sincerely, Me -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Oct 3 07:32:10 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 03 Oct 2011 01:32:10 -0400 Subject: [Tutor] String switch In-Reply-To: References: Message-ID: <4E8948DA.50302@gmail.com> On 10/2/2011 8:33 PM, Christopher King wrote: > Dear Tutors, > I was wondering how one would make it so all the cases of all the > strings in a python file where switched. I know that > for individual strings, you can use .swapcase(), but I'm making a > program to edit others, so it would be easier to just do something at > the top that would switch all other strings. This is (to me) vague. What do you mean by "at the top" and "all other strings"? Other than that I interpret: given a file xxx.py switch case of every character in every character string in the file." This requires reading the file into a string, then searching it for the start of a string, the end of that string, then applying swapcase() to to the string between the start and end delimiters the, writing out the result. Recall that string delimiters include " ' """ and ''' and that \" and \' are escaped and therefore not delimiters. Write a program that attempts to meet these requirements, show it to us, tell us that is succeeds or where it fails and let's go from there. -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Mon Oct 3 11:57:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 03 Oct 2011 10:57:40 +0100 Subject: [Tutor] String switch In-Reply-To: References: Message-ID: On 03/10/11 01:33, Christopher King wrote: > Dear Tutors, > I was wondering how one would make it so all the cases of all the > strings in a python file where switched. I know that > for individual strings, you can use .swapcase(), So just apply swapcase() to the whole file as a string: s = open("spam.py").read().swapcase() > but I'm making a program to edit others, I don't know what that means? "edit others" what? > so it would be easier to just do something at > the top that would switch all other strings. Other strings as opposed to what? Do you want to swap case of all characters in the file? Or only some of them? And if only some how do you distinguish which ones? HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From okutsu at pdx.edu Sat Oct 1 05:55:16 2011 From: okutsu at pdx.edu (Anthony Okutsu) Date: Fri, 30 Sep 2011 20:55:16 -0700 Subject: [Tutor] Can't figure out the syntax error! Message-ID: I'm writing a program in which I input a number and the computer has to guess it. Every time I try to run the program it highlights the 'while' at the beginning of my loop and says 'invalid syntax' but I have no idea why. I'll paste a copy of my program below. Why is there a syntax error in my while loop? import random print("\tCan you beat the machine?\n\n") a = 0 b = 101 tries = 1 guess = random.randint(a+1, b-1) number = int(input("Choose a number between 1 and 100 for CPU to guess:") while guess != number: if guess < number: a = guess else: b = guess print(guess) tries += 1 guess = random.randint(a+1, b-1) print("Your number is... ", guess, "!!!") print("And it only took me", tries, "tries. Can you beat me?") input("\n\nPress enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at linux-ip.net Mon Oct 3 18:39:14 2011 From: martin at linux-ip.net (Martin A. Brown) Date: Mon, 3 Oct 2011 18:39:14 +0200 Subject: [Tutor] Tables In-Reply-To: References: Message-ID: Hello Anna and welcome to the python list, : I'm a beginner at Python and I have tried to read the Python : manual, but I still can't figure out how to extract columns from : a table and then create a new table by merge these extracted : tables together. Send us one or two lines of your (sample) input data and your sample output data. When you say table, do you mean tabular data in a text file? Then show us what you would want from that. We will then, in our various ways try to help you understand how to approach the problem. Note, we do not provide direct support for homework, but, as tutors, we are very happy to help you understand Python and how to make it do what you want. -Martin -- Martin A. Brown http://linux-ip.net/ From joel.goldstick at gmail.com Mon Oct 3 18:50:41 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 3 Oct 2011 12:50:41 -0400 Subject: [Tutor] Can't figure out the syntax error! In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 11:55 PM, Anthony Okutsu wrote: > I'm writing a program in which I input a number and the computer has to > guess it. Every time I try to run the program it highlights the 'while' at > the beginning of my loop and says 'invalid syntax' but I have no idea why. > I'll paste a copy of my program below. Why is there a syntax error in my > while loop? > > import random > > print("\tCan you beat the machine?\n\n") > > a = 0 > b = 101 > tries = 1 > guess = random.randint(a+1, b-1) > number = int(input("Choose a number between 1 and 100 for CPU to guess:") > > while guess != number: > if guess < number: > a = guess > else: > b = guess > print(guess) > tries += 1 > guess = random.randint(a+1, b-1) > > print("Your number is... ", guess, "!!!") > print("And it only took me", tries, "tries. Can you beat me?") > > input("\n\nPress enter key to exit.") > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I'm not sure from you email what is wrong with the while statement. You should actually copy the traceback and place it in your message so that we can see what is going wrong. But you have some other problems. You keep getting a new random number in your while loop. You should just get the random number at the beginning, and after each incorrect guess ask for your input again. So, fix that, then run the program and send us back your traceback with the code -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Oct 3 18:53:34 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 03 Oct 2011 12:53:34 -0400 Subject: [Tutor] Can't figure out the syntax error! In-Reply-To: References: Message-ID: <4E89E88E.6050203@gmail.com> On 9/30/2011 11:55 PM, Anthony Okutsu wrote: > I'm writing a program in which I input a number and the computer has > to guess it. Every time I try to run the program it highlights the > 'while' at the beginning of my loop and says 'invalid syntax' but I > have no idea why. I'll paste a copy of my program below. Why is there > a syntax error in my while loop? > > import random > > print("\tCan you beat the machine?\n\n") > > a = 0 > b = 101 > tries = 1 > guess = random.randint(a+1, b-1) > number = int(input("Choose a number between 1 and 100 for CPU to guess:") > Missing a ) at the end of the above line. > while guess != number: > if guess < number: > a = guess > else: > b = guess > print(guess) > tries += 1 > guess = random.randint(a+1, b-1) > > print("Your number is... ", guess, "!!!") > print("And it only took me", tries, "tries. Can you beat me?") > > input("\n\nPress enter key to exit.") > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Oct 3 18:56:20 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 3 Oct 2011 12:56:20 -0400 Subject: [Tutor] Can't figure out the syntax error! In-Reply-To: <4E89E88E.6050203@gmail.com> References: <4E89E88E.6050203@gmail.com> Message-ID: On Mon, Oct 3, 2011 at 12:53 PM, bob gailer wrote: > On 9/30/2011 11:55 PM, Anthony Okutsu wrote: > > I'm writing a program in which I input a number and the computer has to > guess it. Every time I try to run the program it highlights the 'while' at > the beginning of my loop and says 'invalid syntax' but I have no idea why. > I'll paste a copy of my program below. Why is there a syntax error in my > while loop? > > import random > > print("\tCan you beat the machine?\n\n") > > a = 0 > b = 101 > tries = 1 > guess = random.randint(a+1, b-1) > number = int(input("Choose a number between 1 and 100 for CPU to guess:") > > Missing a ) at the end of the above line. > > while guess != number: > if guess < number: > a = guess > else: > b = guess > print(guess) > tries += 1 > guess = random.randint(a+1, b-1) > > print("Your number is... ", guess, "!!!") > print("And it only took me", tries, "tries. Can you beat me?") > > input("\n\nPress enter key to exit.") > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor > > > > -- > Bob Gailer919-636-4239 > Chapel Hill NC > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Good catch Bob! -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Oct 3 20:04:09 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 3 Oct 2011 13:04:09 -0500 Subject: [Tutor] Fw: Issues With Map Reduce In-Reply-To: <1317056412.83537.YahooMailRC@web81608.mail.mud.yahoo.com> References: <1317056412.83537.YahooMailRC@web81608.mail.mud.yahoo.com> Message-ID: On Mon, Sep 26, 2011 at 12:00 PM, StevenJ Hennessy < stevenhennessy at sbcglobal.net> wrote: > > > Am I on the right track? > Of course we don't do homework here, and we're happy to give pointers in the right direction. I don't see anything completely wrong with your code, and it sounds like you'll probably end out with the correct count of palindromes. A different approach might involve the dict.get() method. You can find out more information through >>> help(dict.get) If you want to get the most benefit (and that's usually the point of homework assignments), I'd suggest writing two different functions - one doing it the way you suggested, with set, and the other using dict.get. HTH, Wayne (also, if you set your email program to send text-only messages, it might help. Many people on this list get annoyed when an HTML message comes down the pipe - especially since it usually mangles your Python code) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 3 22:36:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 03 Oct 2011 21:36:04 +0100 Subject: [Tutor] Fw: Issues With Map Reduce In-Reply-To: <1317056412.83537.YahooMailRC@web81608.mail.mud.yahoo.com> References: <1317056412.83537.YahooMailRC@web81608.mail.mud.yahoo.com> Message-ID: On 26/09/11 18:00, StevenJ Hennessy wrote: > Hello, > I am currently struggling with a homework assignment. I need to use Map > reduce to create a dictionary of palendromes -> number of palendrome > for example: the string "bab bab bab cab cac dad" would output: > bab 3 > cab 1 I assume this should be cac? > dad 1 > here is what I have so far > def palendrome(string): > palendromes = [] > for word in string.split(" "): > if (word == word[::-1]): > palendromes.append(word) > return palendromes This seems pretty fair > string = "abc abd bab tab cab tat yay uaefdfdu" And the purpose of this is? > print map(lambda x: palendrome(x), ["bab abc dab bab bab dad crap pap > pap "]) > #returns a list of lists [['bab', 'bab', 'bab', 'dad', 'pap', 'pap', '']] That last element seems odd... Why are you applying map() to a list containing just one element? > #Here is my attempt so far at the reduce section > > def p(lists): > for list in lists: > set_h = set(list) > return set_h The problem description mentioned using a dictionary. I don't see any dictionaries? > #with the p function I want to create a set of all palendromes found. > Then run a count of the palendroms on the list and make a dict #out of this > > print reduce(p, [['bab', 'bab', 'bab', 'dad', 'pap', 'pap', '']]) Again, reduce isn't really doing anything here, you are just applying the function to a single element in the list. > Am I on the right track? Sadly no. You are on track to produce a solution of sorts but not one that matches your original problem description/requirements statement. You need to use map/reduce/a dictionary. Now, I'm not sure the map/reduce/dictionary solution is a good idea, but it is the one you have been asked to write. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Oct 3 22:42:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 03 Oct 2011 21:42:17 +0100 Subject: [Tutor] Tables In-Reply-To: References: Message-ID: On 29/09/11 20:10, Anna Olofsson wrote: > I'm a beginner at Python and I have tried to read the Python manual, Are you also a beginner to programming? Or can you already program in another language? If so which? It will help us frame our reply at the right level. > still can't figure out how to extract columns from a table > and then create a new table by merge these extracted tables > together. 'table' is not a native concept in Python so I assume you are talking from the point of view of your problem domain. Can you tell us more about the nature of these tables? How are they constructed? Where do they live? - plain text? - an application file(eg Excel)? - a database(which?)? - a web page? - other? Can you give some sample input? What should the output look like? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From motoom at xs4all.nl Tue Oct 4 01:08:51 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 4 Oct 2011 01:08:51 +0200 Subject: [Tutor] Can't figure out the syntax error! In-Reply-To: References: Message-ID: On Oct 3, 2011, at 18:50, Joel Goldstick wrote: > But you have some other problems. You keep getting a new random number in your while loop. Maybe that gives an extra challenge? Guess the random number, which will change after each guess! ;-) Greetings, -- "A creative man is motivated by the desire to achieve, not by the desire to beat others." - Ayn Rand From alan.gauld at btinternet.com Tue Oct 4 02:29:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Oct 2011 01:29:49 +0100 Subject: [Tutor] old messages appearing Message-ID: Folks, I just approved a bunch of messages that had been stuck in the queue. I'm not sure what happened by the server stopped sending me mail prompts that there were messages waiting. I just happened to log in as admin today and saw them waiting. Just in case you wondered why they took so long to appear. -- Alan G Tutor list moderator. From bgailer at gmail.com Tue Oct 4 05:24:47 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 03 Oct 2011 23:24:47 -0400 Subject: [Tutor] Tables In-Reply-To: References: Message-ID: <4E8A7C7F.3030506@gmail.com> Anna: please post either to help at python.org or tutor at python.org Most of us follow both. Since there is a discussion running on help at python.org let's drop the tutor one. Alan: Anna has cross-posted this request here and python-help. There is a thread running on python-help. She has an excel spreadsheet. Sample: Mutation Accession number Mutation Prediction Mutation Score . . . . . . . . . . . . . . . A/G O32197 Damaging 1 A/T Q76392 Benign 0.74 C/T O37102 Damaging 1 She wants "to extract certain columns (or rows) from this table and merge the extracted columns together in an new table (spread sheet)." [snip] Let's drop the tutor discussion and work with help. -- Bob Gailer 919-636-4239 Chapel Hill NC From questions.anon at gmail.com Tue Oct 4 06:41:11 2011 From: questions.anon at gmail.com (questions anon) Date: Tue, 4 Oct 2011 15:41:11 +1100 Subject: [Tutor] memory errors with netCDF Message-ID: Hi Python Tutor, I keep receiving a memory error when processing many netcdf files. I assume it has something to do with how I loop things and maybe need to close things off properly.??? In the code below I am looping through a bunch of netcdf files (each file is hourly data for one month) and within each netcdf file I am outputting a *png file every three hours. This works for one netcdf file (therefore one month) but when it begins to process the next netcdf file I receive a memory error (see below). Since I have tidied some of my code up it seems to process partly into the second file but then I still receive the memory error. I have tried a few suggestions such as: -Combining the dataset using MFDataset (using NETCDF4) is not an option because the files do not have unlimited dimension. - gc.collect() but that just results in a *GEOS_ERROR: bad allocation error*. -only open LAT and LON once (which worked) System Details: Python 2.7.2 |EPD 7.1-2 (32-bit)| (default, Jul 3 2011, 15:13:59) [MSC v.1500 32 bit (Intel)] on win32 Any feedback will be greatly appreciated as I seem to keep ending up with memory errors when working with netcdf files this even happens if I am using a much better computer. Old error (before adding gc.collect() ) *Traceback (most recent call last): File "d:/plot_netcdf_merc_multiplot_across_multifolders__memoryerror.py", line 44, in TSFC=ncfile.variables['T_SFC'][1::3] File "netCDF4.pyx", line 2473, in netCDF4.Variable.__getitem__ (netCDF4.c:23094) MemoryError* from netCDF4 import Dataset import numpy as N import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from netcdftime import utime from datetime import datetime import os import gc shapefile1="E:/griddeddatasamples/GIS/DSE_REGIONS" MainFolder=r"E:/griddeddatasamples/GriddedData/InputsforValidation/T_SFC/" OutputFolder=r"E:/griddeddatasamples/GriddedData/OutputsforValidation" fileforlatlon=Dataset("E:/griddeddatasamples/GriddedData/InputsforValidation/T_SFC/TSFC_1974_01/IDZ00026_VIC_ADFD_T_SFC.nc", 'r+', 'NETCDF4') LAT=fileforlatlon.variables['latitude'][:] LON=fileforlatlon.variables['longitude'][:] for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: print dir path=path+'/' for ncfile in files: if ncfile[-3:]=='.nc': print "dealing with ncfiles:", ncfile ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') TSFC=ncfile.variables['T_SFC'][1::3] TIME=ncfile.variables['time'][1::3] ncfile.close() gc.collect() for TSFC, TIME in zip((TSFC[:]),(TIME[:])): cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(TIME) print ncfiletime timestr=str(ncfiletime) d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') date_string = d.strftime('%Y%m%d_%H%M') map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') x,y=map(*N.meshgrid(LON,LAT)) map.drawcoastlines(linewidth=0.5) map.readshapefile(shapefile1, 'DSE_REGIONS') map.drawstates() plt.title('Surface temperature at %s UTC'%ncfiletime) ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] CS = map.contourf(x,y,TSFC, ticks, cmap=plt.cm.jet) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h], ) cbar=plt.colorbar(CS, cax=cax, drawedges=True) plt.savefig((os.path.join(OutputFolder, 'TSFC'+date_string+'UTC.png'))) plt.close() gc.collect() -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue Oct 4 13:44:02 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 4 Oct 2011 19:44:02 +0800 Subject: [Tutor] arrary stastic Message-ID: Hi, For a file with aaE aEE EaE I want to statically get the concurence of E, such as for coloumn 1, I wish it print a[0]=1, a[1]=1,a[2]=3. Thanks for suggestions, -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Tue Oct 4 14:51:55 2011 From: eire1130 at gmail.com (eire1130 at gmail.com) Date: Tue, 4 Oct 2011 12:51:55 +0000 Subject: [Tutor] arrary stastic In-Reply-To: References: Message-ID: <2053259094-1317732717-cardhu_decombobulator_blackberry.rim.net-525238124-@b1.c28.bise6.blackberry> I don't understand what you want Mayybe give expected output as well Sent from my Verizon Wireless BlackBerry -----Original Message----- From: lina Sender: tutor-bounces+eire1130=gmail.com at python.org Date: Tue, 4 Oct 2011 19:44:02 To: tutor Subject: [Tutor] arrary stastic _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From lina.lastname at gmail.com Tue Oct 4 16:03:35 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 4 Oct 2011 22:03:35 +0800 Subject: [Tutor] arrary stastic In-Reply-To: <2053259094-1317732717-cardhu_decombobulator_blackberry.rim.net-525238124-@b1.c28.bise6.blackberry> References: <2053259094-1317732717-cardhu_decombobulator_blackberry.rim.net-525238124-@b1.c28.bise6.blackberry> Message-ID: On Tue, Oct 4, 2011 at 8:51 PM, wrote: > I don't understand what you want > > Mayybe give expected output as well > want to do a statistic of the concurrence of E, namely, how many times the E showed up, so the first column is 1, second column and then following. Thanks, I have one, which showed something like: tokens=['E'] result=[] filedata = open("try.xpm") text=filedata.readlines() for line in text: result.append({t:line.count(t) for t in tokens}) for index,r in enumerate(result): print(index,"-----",r) The error message is: result.append({t:line.count(t) for t in tokens}) ^ SyntaxError: invalid syntax > > Sent from my Verizon Wireless BlackBerry > > -----Original Message----- > From: lina > Sender: tutor-bounces+eire1130=gmail.com at python.org > Date: Tue, 4 Oct 2011 19:44:02 > To: tutor > Subject: [Tutor] arrary stastic > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue Oct 4 16:07:10 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 4 Oct 2011 22:07:10 +0800 Subject: [Tutor] arrary stastic In-Reply-To: References: <2053259094-1317732717-cardhu_decombobulator_blackberry.rim.net-525238124-@b1.c28.bise6.blackberry> Message-ID: On Tue, Oct 4, 2011 at 10:03 PM, lina wrote: > > > On Tue, Oct 4, 2011 at 8:51 PM, wrote: > >> I don't understand what you want >> >> Mayybe give expected output as well >> > > want to do a statistic of the concurrence of E, > namely, > how many times the E showed up, > > so the first column is 1, second column and then following. > > Thanks, > > I have one, which showed something like: > > > > tokens=['E'] > > result=[] > filedata = open("try.xpm") > text=filedata.readlines() > > for line in text: > result.append({t:line.count(t) for t in tokens}) > > for index,r in enumerate(result): > print(index,"-----",r) > > The error message is: > > > result.append({t:line.count(t) for t in tokens}) > ^ > SyntaxError: invalid syntax > I made a mistake, it used python3 I wonder: can someone help me anatomy this one to help me understand, > > > >> >> Sent from my Verizon Wireless BlackBerry >> >> -----Original Message----- >> From: lina >> Sender: tutor-bounces+eire1130=gmail.com at python.org >> Date: Tue, 4 Oct 2011 19:44:02 >> To: tutor >> Subject: [Tutor] arrary stastic >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > -- > Best Regards, > > lina > > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue Oct 4 16:26:46 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 4 Oct 2011 22:26:46 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E848E9D.3090901@davea.name> References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> Message-ID: On Thu, Sep 29, 2011 at 11:28 PM, Dave Angel wrote: > (Please don't top-post. Put your remarks AFTER the part you're quoting > from the previous message) > > > On 09/29/2011 10:55 AM, lina wrote: > >> import os.path >> >> tokens=['E'] >> result=[] >> >> for fileName in os.listdir("."): >> if os.path.isfile(fileName) and os.path.splitext(fileName)=="**xpm": >> filedata = open(fileName) >> text=filedata.readlines() >> for line in text: >> >> >> How can I read from line 24 and do further looking for "E". >> >> Thanks, >> >> >> > As I said in my earlier message, this was untested. It gave you the > building blocks, but was not correct. > > In particular, that if-test will always fail, so you're not seeing any > files. > > > import os.path > > tokens=['E'] > result=[] > > for fileName in os.listdir("."): > > if os.path.isfile(fileName) and os.path.splitext(fileName)[1]=** > =".xpm": > > filedata = open(fileName) > text=filedata.readlines() > for line in text: > print line > > > Once you've tested that, then you're ready to just look at line 24. > > text is a list, so you can refer to line 24 as text[24] > > Or you can get lines 24-28, with text[24, 29] (look up slices in the > Python doc) > > == > DaveA > > > Thanks for former help, but I wonder how to output (write) the final result in each respectively fileName with just different extension, such as original a.xpm write to a.txt Thanks, #!/bin/python import os.path tokens=['E'] result=[] for fileName in os.listdir("."): if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": filedata = open(fileName) text=filedata.readlines() for line in text[23:len(text)-1]: result.append({t:line.count(t) for t in tokens}) for index,r in enumerate(result): fileName.txt.write(index,"-----",r) ??? -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue Oct 4 17:48:01 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 4 Oct 2011 23:48:01 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8B25C8.3060005@ieee.org> References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> Message-ID: On Tue, Oct 4, 2011 at 11:27 PM, Dave Angel wrote: > On 10/04/2011 10:26 AM, lina wrote: > >> On Thu, Sep 29, 2011 at 11:28 PM, Dave Angel wrote: >> >> (Please don't top-post. Put your remarks AFTER the part you're quoting >>> from the previous message) >>> >>> >>> On 09/29/2011 10:55 AM, lina wrote: >>> >>> import os.path >>>> >>>> tokens=['E'] >>>> result=[] >>>> >>>> for fileName in os.listdir("."): >>>> if os.path.isfile(fileName) and os.path.splitext(fileName)=="*** >>>> *xpm": >>>> >>>> filedata = open(fileName) >>>> text=filedata.readlines() >>>> for line in text: >>>> >>>> >>>> How can I read from line 24 and do further looking for "E". >>>> >>>> Thanks, >>>> >>>> >>>> >>>> As I said in my earlier message, this was untested. It gave you the >>> building blocks, but was not correct. >>> >>> In particular, that if-test will always fail, so you're not seeing any >>> files. >>> >>> >>> import os.path >>> >>> tokens=['E'] >>> result=[] >>> >>> for fileName in os.listdir("."): >>> >>> if os.path.isfile(fileName) and os.path.splitext(fileName)[1]=**** >>> >>> =".xpm": >>> >>> filedata = open(fileName) >>> text=filedata.readlines() >>> for line in text: >>> print line >>> >>> >>> Once you've tested that, then you're ready to just look at line 24. >>> >>> text is a list, so you can refer to line 24 as text[24] >>> >>> Or you can get lines 24-28, with text[24, 29] (look up slices in the >>> Python doc) >>> >>> == >>> DaveA >>> >>> >>> Thanks for former help, >>> >> but I wonder how to output (write) the final result in each respectively >> fileName with just different extension, such as original a.xpm write to >> a.txt >> >> Thanks, >> >> #!/bin/python >> >> import os.path >> >> tokens=['E'] >> result=[] >> >> for fileName in os.listdir("."): >> if os.path.isfile(fileName) and os.path.splitext(fileName)[1]=** >> =".xpm": >> filedata = open(fileName) >> text=filedata.readlines() >> for line in text[23:len(text)-1]: >> result.append({t:line.count(t) for t in tokens}) >> for index,r in enumerate(result): >> fileName.txt.write(index,"----**-",r) >> ??? >> >> > for line in text[23:len(text)-1]: > > probably doesn't do what you expect. It'll start at the 24th line, but it > won't include the last line. slicing uses half-open intervals, same as > range. So you don't want the -1 on that line. > Yes. It starts from 24th line, the first 23 were irrelevant here for analysis. I made a mistake, it should be text[23:len(text)] > > Fortunately, all you have to do is use the default second parm, > > for line in text[23:]: > > Now I have no idea why you want such a complex structure in result, but > I'll ignore that for the moment. > You want to know how to write an output file. Just like an input file, you > first have to open it (in 'w' mode). > outfile = open(newfilename, "w") > will give you a file object, just like filedata did for the input file. > So you would then do outfile.write(somedata) as needed. Notice that if > you use write(), it does NOT put newlines in. That's up to you. > > Note also that opening a file with "w" deletes an existing file of the same > name. So you want to thoroughly test your transformation code before > running the actual command. > Yes, for fileName in os.listdir("."): result=[] if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": filedata = open(fileName) text=filedata.readlines() for line in text[0:]: result.append({t:line.strip().count(t) for t in tokens}) for index,r in enumerate(result): outfiledata=open("fileName.txt","w").write(index,"-----",r) I still have problem using the value of the fileName, here the output is fileName.txt, not $fileName.txt which is supposed to be 1.txt following input 1.xpm > > Now back to your result.append line. As it stands now, result contains the > results for all the files you've processed so far. In other words, as you > process multiple files, it'll get larger and larger. If you're writing the > data out to multiple files, that isn't likely what you want. > Thanks for reminding, now I put result=[] in the for loop for files. > > But I also thought you wanted to count the occurrences of each token by > column, and you're counting them by rows. That count method will return how > many are in that particular line. > Yes, but indeed I calculated it in each row. big mistake. can you tell me how to achieve this, transpose? > > Perhaps this would be clearer if your data wasn't square. if you had 10 > lines with 3 characters in each, it might be more obvious. I assume you > would then want 3 result counts. > It's n*n matrix. now I used this one as example: aaEbb aEEbb EaEbb EaEbE Thanks ahead for any further suggestions, > > DaveA > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Oct 4 18:01:27 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 04 Oct 2011 12:01:27 -0400 Subject: [Tutor] arrary stastic In-Reply-To: References: <2053259094-1317732717-cardhu_decombobulator_blackberry.rim.net-525238124-@b1.c28.bise6.blackberry> Message-ID: <4E8B2DD7.7080103@gmail.com> On 10/4/2011 10:07 AM, lina wrote: > want to do a statistic of the concurrence of E, > > namely, > how many times the E showed up, > > so the first column is 1, second column and then following. > > Thanks, > > I have one, which showed something like: > > > > tokens=['E'] > > result=[] > filedata = open("try.xpm") > text=filedata.readlines() > > for line in text: > result.append({t:line.count(t) for t in tokens}) > > for index,r in enumerate(result): > print(index,"-----",r) > > The error message is: > > > result.append({t:line.count(t) for t in tokens}) > ^ > SyntaxError: invalid syntax > You are tryng to use a list comrehensioin for the dictionary value, without the []. Try this: result.append({t:[line.count(t) for t in tokens]}) You should then see: 0, '-----', {'E': [1]}) (1, '-----', {'E': [2]}) (2, '-----', {'E': [2]}) which is not what you want! As requested before, show us the output you do want. Not a description but the actual output. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Oct 4 18:26:09 2011 From: d at davea.name (Dave Angel) Date: Tue, 04 Oct 2011 12:26:09 -0400 Subject: [Tutor] arrary stastic In-Reply-To: <4E8B2DD7.7080103@gmail.com> References: <2053259094-1317732717-cardhu_decombobulator_blackberry.rim.net-525238124-@b1.c28.bise6.blackberry> <4E8B2DD7.7080103@gmail.com> Message-ID: <4E8B33A1.4090401@davea.name> On 10/04/2011 12:01 PM, bob gailer wrote: > On 10/4/2011 10:07 AM, lina wrote: >> want to do a statistic of the concurrence of E, >> >> namely, >> how many times the E showed up, >> >> so the first column is 1, second column and then following. >> >> Thanks, >> >> I have one, which showed something like: >> >> >> >> tokens=['E'] >> >> result=[] >> filedata = open("try.xpm") >> text=filedata.readlines() >> >> for line in text: >> result.append({t:line.count(t) for t in tokens}) >> >> for index,r in enumerate(result): >> print(index,"-----",r) >> >> The error message is: >> >> >> result.append({t:line.count(t) for t in tokens}) >> ^ >> SyntaxError: invalid syntax >> > You are tryng to use a list comrehensioin for the dictionary value, > without the []. Try this: > > result.append({t:[line.count(t) for t in tokens]}) > > You should then see: > 0, '-----', {'E': [1]}) > (1, '-----', {'E': [2]}) > (2, '-----', {'E': [2]}) > > which is not what you want! > > As requested before, show us the output you do want. Not a description > but the actual output. > > -- Bob Gailer 919-636-4239 Chapel Hill NC > I'll second Bob's request, and go further: Move this discussion into the original thread, and repeat in one place your assumptions for input, requirements for output, the code you're using and how the output differs from what you expect. You also need to give your target python version, and if you're currently getting an exception the full stack trace. Finally, if it's relevant, the operating system as well. I think you've given almost all of this, except the python version and the expected file output. -- DaveA From davea at ieee.org Tue Oct 4 17:27:04 2011 From: davea at ieee.org (Dave Angel) Date: Tue, 04 Oct 2011 11:27:04 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> Message-ID: <4E8B25C8.3060005@ieee.org> On 10/04/2011 10:26 AM, lina wrote: > On Thu, Sep 29, 2011 at 11:28 PM, Dave Angel wrote: > >> (Please don't top-post. Put your remarks AFTER the part you're quoting >> from the previous message) >> >> >> On 09/29/2011 10:55 AM, lina wrote: >> >>> import os.path >>> >>> tokens=['E'] >>> result=[] >>> >>> for fileName in os.listdir("."): >>> if os.path.isfile(fileName) and os.path.splitext(fileName)=="**xpm": >>> filedata = open(fileName) >>> text=filedata.readlines() >>> for line in text: >>> >>> >>> How can I read from line 24 and do further looking for "E". >>> >>> Thanks, >>> >>> >>> >> As I said in my earlier message, this was untested. It gave you the >> building blocks, but was not correct. >> >> In particular, that if-test will always fail, so you're not seeing any >> files. >> >> >> import os.path >> >> tokens=['E'] >> result=[] >> >> for fileName in os.listdir("."): >> >> if os.path.isfile(fileName) and os.path.splitext(fileName)[1]=** >> =".xpm": >> >> filedata = open(fileName) >> text=filedata.readlines() >> for line in text: >> print line >> >> >> Once you've tested that, then you're ready to just look at line 24. >> >> text is a list, so you can refer to line 24 as text[24] >> >> Or you can get lines 24-28, with text[24, 29] (look up slices in the >> Python doc) >> >> == >> DaveA >> >> >> Thanks for former help, > but I wonder how to output (write) the final result in each respectively > fileName with just different extension, such as original a.xpm write to > a.txt > > Thanks, > > #!/bin/python > > import os.path > > tokens=['E'] > result=[] > > for fileName in os.listdir("."): > if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": > filedata = open(fileName) > text=filedata.readlines() > for line in text[23:len(text)-1]: > result.append({t:line.count(t) for t in tokens}) > for index,r in enumerate(result): > fileName.txt.write(index,"-----",r) > ??? > for line in text[23:len(text)-1]: probably doesn't do what you expect. It'll start at the 24th line, but it won't include the last line. slicing uses half-open intervals, same as range. So you don't want the -1 on that line. Fortunately, all you have to do is use the default second parm, for line in text[23:]: Now I have no idea why you want such a complex structure in result, but I'll ignore that for the moment. You want to know how to write an output file. Just like an input file, you first have to open it (in 'w' mode). outfile = open(newfilename, "w") will give you a file object, just like filedata did for the input file. So you would then do outfile.write(somedata) as needed. Notice that if you use write(), it does NOT put newlines in. That's up to you. Note also that opening a file with "w" deletes an existing file of the same name. So you want to thoroughly test your transformation code before running the actual command. Now back to your result.append line. As it stands now, result contains the results for all the files you've processed so far. In other words, as you process multiple files, it'll get larger and larger. If you're writing the data out to multiple files, that isn't likely what you want. But I also thought you wanted to count the occurrences of each token by column, and you're counting them by rows. That count method will return how many are in that particular line. Perhaps this would be clearer if your data wasn't square. if you had 10 lines with 3 characters in each, it might be more obvious. I assume you would then want 3 result counts. DaveA From lina.lastname at gmail.com Tue Oct 4 18:35:43 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 5 Oct 2011 00:35:43 +0800 Subject: [Tutor] arrary stastic In-Reply-To: <4E8B33A1.4090401@davea.name> References: <2053259094-1317732717-cardhu_decombobulator_blackberry.rim.net-525238124-@b1.c28.bise6.blackberry> <4E8B2DD7.7080103@gmail.com> <4E8B33A1.4090401@davea.name> Message-ID: On Wed, Oct 5, 2011 at 12:26 AM, Dave Angel wrote: > On 10/04/2011 12:01 PM, bob gailer wrote: > >> On 10/4/2011 10:07 AM, lina wrote: >> >>> want to do a statistic of the concurrence of E, >>> >>> namely, >>> how many times the E showed up, >>> >>> so the first column is 1, second column and then following. >>> >>> Thanks, >>> >>> I have one, which showed something like: >>> >>> >>> >>> tokens=['E'] >>> >>> result=[] >>> filedata = open("try.xpm") >>> text=filedata.readlines() >>> >>> for line in text: >>> result.append({t:line.count(t) for t in tokens}) >>> >>> for index,r in enumerate(result): >>> print(index,"-----",r) >>> >>> The error message is: >>> >>> >>> result.append({t:line.count(t) for t in tokens}) >>> ^ >>> SyntaxError: invalid syntax >>> >>> You are tryng to use a list comrehensioin for the dictionary value, >> without the []. Try this: >> >> result.append({t:[line.count(**t) for t in tokens]}) >> >> You should then see: >> 0, '-----', {'E': [1]}) >> (1, '-----', {'E': [2]}) >> (2, '-----', {'E': [2]}) >> >> which is not what you want! >> >> As requested before, show us the output you do want. Not a description but >> the actual output. >> >> -- Bob Gailer 919-636-4239 Chapel Hill NC >> >> I'll second Bob's request, and go further: Move this discussion into > the original thread, and repeat in one place your assumptions for input, > requirements for I will move back to the original thread. Thanks for your suggestions. > output, the code you're using and how the output differs from what you > expect. > > You also need to give your target python version, and if you're currently > getting an exception the full stack trace. Finally, if it's relevant, the > operating system as well. > > I think you've given almost all of this, except the python version and the > expected file output. > I guess mainly choose python3, the default python is $ python Python 2.6.7 (r267:88850, Jul 10 2011, 08:11:54) [GCC 4.6.1] on linux2 python python2.5 python2.6 python2.7 python3 python3.1 python3.2 python3.2mu > > -- > > DaveA > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue Oct 4 18:38:52 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 5 Oct 2011 00:38:52 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> Message-ID: For file: aaEbb aEEbb EaEbb EaEbE the expected output is 2 1 0 1 In the first column there is 2 E, so the output is 2 E, second column is 1 E. #!/bin/python import os.path tokens=['B','E'] for fileName in os.listdir("."): result=[] if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": filedata = open(fileName) text=filedata.readlines() for line in text[0:]: result.append({t:line.strip().count(t) for t in tokens}) for index,r in enumerate(result): outfiledata=open("fileName.txt","w") Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Oct 4 18:59:51 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 4 Oct 2011 09:59:51 -0700 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> Message-ID: On Tue, Oct 4, 2011 at 8:48 AM, lina wrote: > if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": > filedata = open(fileName) > text=filedata.readlines() > for line in text[0:]: > result.append({t:line.strip().count(t) for t in tokens}) > for index,r in enumerate(result): > outfiledata=open("fileName.txt","w").write(index,"-----",r) > I still have problem using the value of the fileName, > > here the output is fileName.txt, not $fileName.txt which is supposed to be > 1.txt following input 1.xpm > That's because in this line: > outfiledata=open("fileName.txt","w").write(index,"-----",r) > you put "fileName.txt" in quotes - which makes it a literal, not a variable. Try this: > outfiledata=open(os.path.splitext(fileName)[0] + > ".txt","w").write(index,"-----",r) > (in other words, split fileName, take just the first part, and add ".txt" to the end of it.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue Oct 4 19:07:01 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 5 Oct 2011 01:07:01 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> Message-ID: On Wed, Oct 5, 2011 at 12:59 AM, Marc Tompkins wrote: > On Tue, Oct 4, 2011 at 8:48 AM, lina wrote: > >> if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": >> filedata = open(fileName) >> text=filedata.readlines() >> for line in text[0:]: >> result.append({t:line.strip().count(t) for t in tokens}) >> for index,r in enumerate(result): >> outfiledata=open("fileName.txt","w").write(index,"-----",r) >> I still have problem using the value of the fileName, >> >> here the output is fileName.txt, not $fileName.txt which is supposed to be >> 1.txt following input 1.xpm >> > > That's because in this line: > >> outfiledata=open("fileName.txt","w").write(index,"-----",r) >> > you put "fileName.txt" in quotes - which makes it a literal, not a > variable. > > Try this: > >> outfiledata=open(os.path.splitext(fileName)[0] + >> ".txt","w").write(index,"-----",r) >> > Thanks, it works. I understand it now. > (in other words, split fileName, take just the first part, and add ".txt" > to the end of it.) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue Oct 4 19:09:12 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 5 Oct 2011 01:09:12 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> Message-ID: But I still don't know how to get the statistic result of each column, Thanks for further suggestions, Best regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue Oct 4 19:30:25 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 4 Oct 2011 13:30:25 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> >But I still don't know how to get the >statistic result of each column, try: cols = len( text[0] ) # Find out how many columns there are (assuming each row has the same number of columns) except IndexError: raise # This will make sure you can see the error while developing; # replace with whatever is appropriate for your application results = [] for idx in xrange( cols ): results.append( 0 ) # Initialize an array to zero value with the correct number of columns # results = [ 0, 0, 0 ] for 3 columns for line in text: # Check each row for col_idx, field in enumerate( line ): # check each column if token in field: # Or possibly if token==field, not sure exactly what kind of comparison you need. results[col_idx] += 1 # token found so increment count for that column This is a simple to understand, brute-force solution. It is not very efficient and might be slow for large amounts of data. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From d at davea.name Tue Oct 4 20:43:39 2011 From: d at davea.name (Dave Angel) Date: Tue, 04 Oct 2011 14:43:39 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> Message-ID: <4E8B53DB.6060008@davea.name> On 10/04/2011 01:09 PM, lina wrote: > But I still don't know how to get the > statistic result of each column, > > Thanks for further suggestions, > > Best regards, > > lina > As I said before, your current code counts across a line at a time, while you need to count vertically. That could be done by transposing the list of strings, but it's probably easier to just count them yourself. So set up a list of counters, all zero, and every time you see a desired character, increment the corresponding counter. Here's the existing code: #!/bin/python import os.path tokens=['B','E'] for fileName in os.listdir("."): result=[] if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": filedata = open(fileName) text=filedata.readlines() for line in text[0:]: result.append({t:line.strip().count(t) for t in tokens}) for index,r in enumerate(result): outfiledata=open("fileName.txt","w") Decide first on a reasonable data arrangement for the results. I'd suggest having a map of lists, rather than the other way around. So initialize it to having zeroes in all the right places. results = {} numcolumns = len(text[23].strip()) for ch in tokens: results[ch] = [0] * numcolumns and for line in text[23:]: for col, ch in enumerate(line): if ch in tokens: results[ch][col] += 1 (Untested) -- DaveA From egildon at gmail.com Tue Oct 4 23:06:06 2011 From: egildon at gmail.com (Earnest Gildon) Date: Tue, 4 Oct 2011 17:06:06 -0400 Subject: [Tutor] What is the difference between the now depreciated threading module and the multiprocessing module Message-ID: I was wondering if anyone could tell me why threading was depreciated; and give me a use case for the multiprocessing : Queue function in python 2.7. Thanks, -earnest -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue Oct 4 23:35:21 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 4 Oct 2011 17:35:21 -0400 Subject: [Tutor] What is the difference between the now depreciated threading module and the multiprocessing module In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21234AA7@EMARC112VS01.exchad.jpmchase.net> >I was wondering if anyone could tell me why threading was depreciated; and give me a use case for the >multiprocessing : Queue function in python 2.7. Threading was *not* deprecated Python 2.x or 3.x http://docs.python.org/dev/py3k/library/threading.html?highlight=threading#threading http://docs.python.org/library/threading.html Threading is for single process programs that want to emulate being multi-process while multiprocessing actually creates different processes. The multiprocessing module docs say: "[sic]multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. " You can read about the multiprocessing module here: http://docs.python.org/library/multiprocessing.html# Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From olofsson_anna585 at hotmail.com Tue Oct 4 22:00:05 2011 From: olofsson_anna585 at hotmail.com (Anna Olofsson) Date: Tue, 4 Oct 2011 22:00:05 +0200 Subject: [Tutor] extract information from txtfile Message-ID: Hi, I'm a beginner at Python and I'm trying to extract some information from a textfile where I have a lot of data. The table looks something like this, but with many more columns and rows: # chr Pos ID REF ALT . . . . . . . . . . . 1 13645 - C T . . . . . . . . . . I want to extract certain data from this table above and make it to a sentence looking something like this: chr1:13645 C/T I have created a pseudo code, just to get an overview of want I want to do, looking like this: import OS open vcf_file.vcf for each line words = split(line) # words[0] = 1 , words[1]=Pos , words[3]=REF , words[4]=ALT if(words[0] not "#"): #Sometimes the word starts with a hash and I don't want that to be included. str="chr" + words[0] + ":" + words[1] + "\t" + words[3] + "/" + words[4] score = OS.system(str) vcf_file.close() print result return score I'm not exactly sure how to proceed from here. Best, Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Oct 5 01:21:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 05 Oct 2011 00:21:00 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> Message-ID: On 04/10/11 17:38, lina wrote: > For file: > > aaEbb > aEEbb > EaEbb > EaEbE > > the expected output is > > 2 1 0 1 I expected 2 1 4 0 1 > In the first column there is 2 E, so the output is 2 E, second column is > 1 E. But the 3rd is all E so why miss out the 4? I'm still confused - and I thought I was getting it! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Oct 5 01:46:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 05 Oct 2011 00:46:30 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> Message-ID: On 04/10/11 18:09, lina wrote: > But I still don't know how to get the > statistic result of each column, Let's ignore the traversal of files issue for now. Let's look at processing one file: You want a list of totals of equal length to the number of columns. We can find that number using len(line.split()) And we can initialise a list to that many elements with: counts = [0] * numCols Now you want to iterate over each line and for each column increment the corresponding count if the value is equal to your token ('E' in the example). Lets try putting that together: def countTokenInColumn(aFileName,token): lines = open(aFileName).readlines() numCols = len( lines[0].split() ) #use 1st line as a template counts = [0] * numCols for line in lines: cols = line.split() for index in range(numCols): if cols[index] == token: counts[index] += 1 return counts Now that is untested but should be close to what you want. We could tighten it up a bit but I've tried to keep the algorithm clear. Does that help? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Wed Oct 5 02:07:49 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 04 Oct 2011 20:07:49 -0400 Subject: [Tutor] String switch In-Reply-To: References: <4E8948DA.50302@gmail.com> Message-ID: <4E8B9FD5.5070602@gmail.com> Please always reply-all so a copy goes to the list. I'm forwarding this one for you. Please answer ALL questions that we ask. You did not answer What do you mean by "all other strings"? On 10/4/2011 4:55 PM, Christopher King wrote: > > This is (to me) vague. What do you mean by "at the top" and "all > other strings"? > > It inserts code at the top of the target program. I was wondering what > that code at the top should be. Sorry - I absoultely do not understand. Can you explain it another way? What is the purpose of the inserted code? How will you execute it? The more detailled and explicit you are the easier it is to help you. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Wed Oct 5 04:22:05 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 5 Oct 2011 10:22:05 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Wed, Oct 5, 2011 at 1:30 AM, Prasad, Ramit wrote: > >But I still don't know how to get the > >statistic result of each column, > > Thanks. > > try: > cols = len( text[0] ) # Find out how many columns there are (assuming > each row has the same number of columns) > except IndexError: > raise # This will make sure you can see the error while developing; > This part: It's showed up: except IndexError: ^ SyntaxError: invalid syntax for fileName in os.listdir("."): if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": filedata = open(fileName) text=filedata.readlines() cols = len(text[0]) except IndexError: print ("Index Error.") result=[] for idx in xrange(cols): results.append(0) for line in text: for col_idx, field in enumerate(line): if token in field: results[col_idx]+=1 for index in col_idx: print results[index] it showed up: print results[] ^ SyntaxError: invalid syntax Sorry, I am still lack deep understanding about something basic. Thanks for your patience. > # replace with whatever is appropriate for your application > results = [] > for idx in xrange( cols ): > results.append( 0 ) # Initialize an array to zero value with the correct > number of columns > # results = [ 0, 0, 0 ] for 3 columns > for line in text: # Check each row > for col_idx, field in enumerate( line ): # check each column > if token in field: > # Or possibly if token==field, not sure exactly what kind of > comparison you need. > results[col_idx] += 1 # token found so increment count for that > column > > > This is a simple to understand, brute-force solution. It is not very > efficient and might be slow for large amounts of data. > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Oct 5 04:45:49 2011 From: d at davea.name (Dave Angel) Date: Tue, 04 Oct 2011 22:45:49 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E8BC4DD.4070806@davea.name> On 10/04/2011 10:22 PM, lina wrote: > On Wed, Oct 5, 2011 at 1:30 AM, Prasad, Ramitwrote: > >>> But I still don't know how to get the >>> statistic result of each column, >> Thanks. >> try: >> cols = len( text[0] ) # Find out how many columns there are (assuming >> each row has the same number of columns) >> except IndexError: >> raise # This will make sure you can see the error while developing; >> > This part: > > It's showed up: > > except IndexError: Best guess I can make is that the line "each row has..." needs a # in front of it. or maybe your code looks like the following, which has no try block at all. The except clause has to be the first line at the same indentation as the try line it's protecting. > ^ > SyntaxError: invalid syntax > > for fileName in os.listdir("."): > if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": > filedata = open(fileName) > text=filedata.readlines() > cols = len(text[0]) > except IndexError: > print ("Index Error.") > result=[] > for idx in xrange(cols): > results.append(0) > for line in text: > for col_idx, field in enumerate(line): > if token in field: > results[col_idx]+=1 > for index in col_idx: > print results[index] > > it showed up: > > print results[] > ^ > SyntaxError: invalid syntax > > Sorry, I am still lack deep understanding about something basic. Thanks for > your patience. > > Simplest answer here is you might have accidentally run this under Python 3.x. That would explain the syntax error on the print function. Pick a single version and stick to it. In fact, you might even put a version test at the beginning of the code to give an immediate error. But you do have many other problems with the code. One is that this no longer does anything useful with multiple tokens. (See my last email to see an approach that handles multiple tokens). Another is that you mix result and results. They're entirely distinct. So pick one spelling and stick to it. Another is that for the "for index" is indented wrong, and uses the wrong limit value. As it stands, it's trying to iterate over an integer. You probably want to replace the whole phrase with something like for item in results: print item This example illustrates one reason why it's a mistake to write all the code at top level. This code should probably be at least 4 functions, with each one handling one abstraction. Further, while you're developing, you should probably put the test data into a literal (probably a multiline literal using triplequotes), so you can experiment easily with changes to the data, and see how it results. -- DaveA From lina.lastname at gmail.com Wed Oct 5 05:13:01 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 5 Oct 2011 11:13:01 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8BC4DD.4070806@davea.name> References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> Message-ID: On Wed, Oct 5, 2011 at 10:45 AM, Dave Angel wrote: > On 10/04/2011 10:22 PM, lina wrote: > >> On Wed, Oct 5, 2011 at 1:30 AM, Prasad, Ramit >> >wrote: >> >> But I still don't know how to get the >>>> statistic result of each column, >>>> >>> Thanks. >>> try: >>> cols = len( text[0] ) # Find out how many columns there are (assuming >>> each row has the same number of columns) >>> except IndexError: >>> raise # This will make sure you can see the error while developing; >>> >>> This part: >> >> It's showed up: >> >> except IndexError: >> > Best guess I can make is that the line "each row has..." needs a # in > front of it. or maybe your code looks like the following, which has no try > block at all. > > The except clause has to be the first line at the same indentation as the > try line it's protecting. > > > ^ >> SyntaxError: invalid syntax >> >> for fileName in os.listdir("."): >> if os.path.isfile(fileName) and os.path.splitext(fileName)[1]=** >> =".xpm": >> filedata = open(fileName) >> text=filedata.readlines() >> cols = len(text[0]) >> except IndexError: >> print ("Index Error.") >> result=[] >> for idx in xrange(cols): >> results.append(0) >> for line in text: >> for col_idx, field in enumerate(line): >> if token in field: >> results[col_idx]+=1 >> for index in col_idx: >> print results[index] >> >> it showed up: >> >> print results[] >> ^ >> SyntaxError: invalid syntax >> >> Sorry, I am still lack deep understanding about something basic. Thanks >> for >> your patience. >> >> >> Simplest answer here is you might have accidentally run this under Python > 3.x. That would explain the syntax error on the print function. Pick a > single version and stick to it. In fact, you might even put a version test > at the beginning of the code to give an immediate error. > choose python3. > > But you do have many other problems with the code. One is that this no > longer does anything useful with multiple tokens. (See my last email to see > an approach that handles multiple tokens). Another is that you mix result > and results. They're entirely distinct. So pick one spelling and stick to > it. This is a very good suggestions, I choose results. > Another is that for the "for index" is indented wrong, and uses the wrong > limit value. As it stands, it's trying to iterate over an integer. You > probably want to replace the whole phrase with something like for item in > results: print item > > This example illustrates one reason why it's a mistake to write all the > code at top level. This code should probably be at least 4 functions, with > each one handling one abstraction. > It's frustrating. Seriously. (I think I need to read some good (relevant) codes first. > > Further, while you're developing, you should probably put the test data > into a literal (probably a multiline literal using triplequotes), so you can > experiment easily with changes to the data, and see how it results. > #!/bin/python import os.path tokens=['B','E'] for fileName in os.listdir("."): if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": filedata = open(fileName) text=filedata.readlines() results={} numcolumns=len(text.strip()) for ch in tokens: results[ch]=[0]*numcolumns for line in text: for col, ch in enumerate(line): if ch in tokens: results[ch][col]+=1 for item in results: print item $ python3 counter-vertically.py File "counter-vertically.py", line 20 print item ^ SyntaxError: invalid syntax > > -- > > DaveA > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Oct 5 07:42:15 2011 From: d at davea.name (Dave Angel) Date: Wed, 05 Oct 2011 01:42:15 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> Message-ID: <4E8BEE37.1050408@davea.name> On 10/04/2011 11:13 PM, lina wrote: > On Wed, Oct 5, 2011 at 10:45 AM, Dave Angel wrote: > >> On 10/04/2011 10:22 PM, lina wrote: >> >>> On Wed, Oct 5, 2011 at 1:30 AM, Prasad, Ramit >>>> w >> >>> SyntaxError: invalid syntax >>> >>> for fileName in os.listdir("."): >>> if os.path.isfile(fileName) and os.path.splitext(fileName)[1]=** >>> =".xpm": >>> filedata = open(fileName) >>> text=filedata.readlines() >>> cols = len(text[0]) >>> except IndexError: >>> print ("Index Error.") >>> result=[] >>> for idx in xrange(cols): >>> results.append(0) >>> for line in text: >>> for col_idx, field in enumerate(line): >>> if token in field: >>> results[col_idx]+=1 >>> for index in col_idx: >>> print results[index] >>> >>> it showed up: >>> >>> print results[] >>> ^ >>> SyntaxError: invalid syntax >>> >>> Sorry, I am still lack deep understanding about something basic. Thanks >>> for >>> your patience. >>> >>> >>> Simplest answer here is you might have accidentally run this under Python >> 3.x. That would explain the syntax error on the print function. Pick a >> single version and stick to it. In fact, you might even put a version test >> at the beginning of the code to give an immediate error. >> > choose python3. > Then change that last print to use parentheses. print() is a function call in Python 3.x, while it was a statement in earlier Python versions. > >> This example illustrates one reason why it's a mistake to write all the >> code at top level. This code should probably be at least 4 functions, with >> each one handling one abstraction. >> > It's frustrating. Seriously. (I think I need to read some good (relevant) > codes first. > Is Python your first programming language? It was approximately my 30th. I learned "programming" from a Fortran book in 1967. I had no access to a computer, though there was at least one in the state, at the Yale campus. I saw it in a field trip by the (advanced) students that were taking programming. They weren't allowed to take it till finishing 2nd year calculus, which I didn't do till I got to college. However, when I went to college the following year, I ran across another student who knew how to access the mainframe (via punch-cards), and could tell me how to do it. (Security was very light). For a few months, I hacked daily, and learned a lot. Then the following year, I actually took an electrical engineering class that introduced the concepts of programming, and I spent my time doing experiments that barely resembled the assignments. I ended up with an incomplete in the course, which I made up by writing a linear circuit analysis program. Punched card input, graphical output to a line printer using rows of asterisks. Point is, it takes a lot of time, and usually a one-on-one mentor to get the concepts nailed down. Seldom did anyone tell me "write these lines down, and it'll solve the problem." instead they told me where my problem was, and where in those manuals (chained to tables in the lab) to find more information. It wasn't till my fourth language that I found out about local variables, and how a function should encapsulate one concept. The first three didn't have such things. >> Further, while you're developing, you should probably put the test data >> into a literal (probably a multiline literal using triplequotes), so you can >> experiment easily with changes to the data, and see how it results. >> > > #!/bin/python > > import os.path > > tokens=['B','E'] > > for fileName in os.listdir("."): > if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": > filedata = open(fileName) > text=filedata.readlines() > results={} > numcolumns=len(text.strip()) > for ch in tokens: > results[ch]=[0]*numcolumns > for line in text: > for col, ch in enumerate(line): > if ch in tokens: > results[ch][col]+=1 > for item in results: > print item > > $ python3 counter-vertically.py > File "counter-vertically.py", line 20 > print item > ^ > SyntaxError: invalid syntax > As I said above, Python 3 needs parentheses around print's argument list. As for splitting into functions, consider: #these two are capitalized because they're intended to be constant TOKENS = "BE" LINESTOSKIP = 43 INFILEEXT = ".xpm" OUTFILEEXT = ".txt" def dofiles(topdirectory): for filename in os.listdr(topdirectory): processfile(filename) def processfile(infilename): base, ext =os.path.splitext(fileName) if ext == INFILEEXT: text = fetchonefiledata(infilename) numcolumns = len(text[0]) results = {} for ch in TOKENS: results[ch] = [0] * numcolumns for line in text: line = line.strip() for col, ch in enumerate(line): if ch in tokens: results[ch][col] += 1 writeonefiledata(base+OUTFILEEXT, results) def fetchonefiledata(inname): infile = open(inname) text = infile.readlines() return text[LINESTOSKIP:] def writeonefiledata(outname): outfile = open(outname, "w") ...process the results as appropriate... ....(since you didn't tell us how multiple tokens were to be displayed) if __name__ == "__main__": dofiles(".") #or get the top directory from the sys.argv variable, which is set from command line. Now this is totally untested. I just typed it without even trying any of it. But it gives you a simple refactoring that splits the logic so each can be visualized (and tested) independently. i'd also split up processfile(), once I realized how big it was. There are many shortcuts that can be applied. Some of them probably use language features you're not comfortable with, like perhaps generators. And if efficiency is important, there are optimizations to do, like using islice directly on the infile object. That one would eliminate having to have the whole file stored in memory at one time. Likewise there are further things that could be done to decouple the functions even more. But there's nothing in the above code which uses very advanced topics, so you should be able to understand it and fix whatever typos I've undoubtedly got. What are you using for debugging aids? Besides this group, I mean. print statements? An IDE ? which one? -- DaveA From andreas.perstinger at gmx.net Wed Oct 5 07:51:00 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Wed, 05 Oct 2011 07:51:00 +0200 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> Message-ID: On 2011-10-05 05:13, lina wrote: > $ python3 counter-vertically.py ^^^^^^^ > File "counter-vertically.py", line 20 > print item > ^ > SyntaxError: invalid syntax In Python 3 print is a function: print(item) In another message in this thread you've said: "Sorry, I am still lack deep understanding about something basic." IMHO you should take the time to read the tutorial (as others have already told you) before continuing your work: http://docs.python.org/py3k/tutorial/index.html Bye, Andreas From d at davea.name Wed Oct 5 08:15:49 2011 From: d at davea.name (Dave Angel) Date: Wed, 05 Oct 2011 02:15:49 -0400 Subject: [Tutor] fake defrag revisited In-Reply-To: <101169689560.20111001155333@columbus.rr.com> References: <145120072334.20111001020636@columbus.rr.com> <4E86FE05.8040608@davea.name> <150155273711.20111001115318@columbus.rr.com> <4E875600.4060400@davea.name> <101169689560.20111001155333@columbus.rr.com> Message-ID: <4E8BF615.8000806@davea.name> On 10/01/2011 03:53 PM, R. Alan Monroe wrote: > >> You missed the rest of the paragraph. Don't wait for the sort to >> finish, you do the swapping in the compare function. > > Either I'm too dumb to understand your answer, or explained my > original problem too poorly. > > Have you ever played the Rush Hour game where you're moving little > cars around a parking lot to let the goal car escape? > > http://www.thinkfun.com/sites/default/files/images/product_library/rushhour/new/RushH-5000-LoResSpill.jpg?1294204060 > > http://www.thinkfun.com/sites/default/files/images/product_howtoplay/rush-hour.jpg?1290652077 > > i.e. you can't move the goal car until another car is out of the way, > but you can't move THAT car until a third car is out of the way, etc. > > That's the problem I'm facing, and I don't think a sort will solve it. > I'm wondering now if it will have to be more of a recursive > backtracking thing, that will reject a sequence of moves that would > have overwritten an as-yet-unmoved piece. > > I'm using 2.x, and yeah, I have used cmp lambda functions before. It's > how I got the sorted-by-second-element list in my followup email. > > (requires pygame) > http://javajack.dynalias.net/defrag/defrag008.py > > Alan > I never saw this message, since you didn't CC it to the python-tutor group. Problem with recursive backtracking is that you have to be sure the maximum recursive depth is manageable. Don't use a lambda function, use a real def function. (Lambdas are just expressions, so they can't do real if statements). Your function will be called by the sort function to compare two items. And if they should be swapped, it'll swap them after you return. So you do the swap on your display to match what you know the sort is going to do. Since all the moves are swaps, it'll be guaranteed to be in a sequence that converges on the correct final order. Will it be the minimum number of moves? Definitely not. But that wasn't a requirement, and if it were, you wouldn't start by building that list of tuples. I believe producing a fake cmp-function callback is the minimum code to solve the problem, but not the minimum thinking. But if you have different constraints, tell us about them. If you want speed, just update the display to its final state. If you're trying to realistically simulate an actual defrag program, then design that program. But such a program might not have enough ram to build the table you're assuming, where you know before starting what the final ordering will be. If I were writing a real defragger, I'd have other costraints. It'd have to work with huge disks, and relatively small memory. And it would have the constraint that if it would crash part way through, at most one file or metafile would be in an invalid state, and that file would be readily recovered by a utility that you run afterwards. If you think that's too restrictive, because you should do a backup first, then my defragger is easy. Backup, erase the entire drive, and restore. Fast and easy. But notice it required 50% free space, since the backup media had to be big enough to hold it all. I can come up with several other algorithms, depending on assumptions. For example, you examine a pair of blocks, and if the abs-sum of the dstances they are from their targets will decrease by swapping, then do so. Otherwise, leave them alone, and pick a different pair. Independently keep track of the sum of all those distances. When that sum reaches zero, you're done. Now the only trick is systematically picking pairs to process. Another one, start by moving all files upwards, till all the free space is at the beginning. Then sort the files by size, reversed, and move them towards the beginning. As long as there is enough free space to store the biggest file, this will converge in one double pass. Otherwise, it must be repeated. Trick is that you define the disk as just a little smaller next pass, starting wherever the first file didn't fit. So after this next pass, about twice as much of that first file will be contiguous. So the number of passes is no more than max file size divided by free space. -- DaveA From lina.lastname at gmail.com Wed Oct 5 08:51:06 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 5 Oct 2011 14:51:06 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8BEE37.1050408@davea.name> References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> Message-ID: On Wed, Oct 5, 2011 at 1:42 PM, Dave Angel wrote: > On 10/04/2011 11:13 PM, lina wrote: > >> On Wed, Oct 5, 2011 at 10:45 AM, Dave Angel wrote: >> >> On 10/04/2011 10:22 PM, lina wrote: >>> >>> On Wed, Oct 5, 2011 at 1:30 AM, Prasad, Ramit>>> *com >>>> >>>>> w >>>>> >>>> >>> >>>> SyntaxError: invalid syntax >>>> >>>> for fileName in os.listdir("."): >>>> if os.path.isfile(fileName) and os.path.splitext(fileName)[1]=**** >>>> >>>> =".xpm": >>>> filedata = open(fileName) >>>> text=filedata.readlines() >>>> cols = len(text[0]) >>>> except IndexError: >>>> print ("Index Error.") >>>> result=[] >>>> for idx in xrange(cols): >>>> results.append(0) >>>> for line in text: >>>> for col_idx, field in enumerate(line): >>>> if token in field: >>>> results[col_idx]+=1 >>>> for index in col_idx: >>>> print results[index] >>>> >>>> it showed up: >>>> >>>> print results[] >>>> ^ >>>> SyntaxError: invalid syntax >>>> >>>> Sorry, I am still lack deep understanding about something basic. Thanks >>>> for >>>> your patience. >>>> >>>> >>>> Simplest answer here is you might have accidentally run this under >>>> Python >>>> >>> 3.x. That would explain the syntax error on the print function. Pick a >>> single version and stick to it. In fact, you might even put a version >>> test >>> at the beginning of the code to give an immediate error. >>> >>> choose python3. >> >> Then change that last print to use parentheses. print() is a function > call in Python 3.x, while it was a statement in earlier Python versions. > > >> >> This example illustrates one reason why it's a mistake to write all the >>> code at top level. This code should probably be at least 4 functions, >>> with >>> each one handling one abstraction. >>> >>> It's frustrating. Seriously. (I think I need to read some good >> (relevant) >> codes first. >> >> Is Python your first programming language? It was approximately my 30th. > Not exactly. Ha ... I don't know there are so many languages there. > > I learned "programming" from a Fortran book in 1967. I had no access to a > computer, though there was at least one in the state, at the Yale campus. I > saw it in a field trip by the (advanced) students that were taking > programming. They weren't allowed to take it till finishing 2nd year > calculus, which I didn't do till I got to college. However, when I went to > college the following year, I ran across another student who knew how to > access the mainframe (via punch-cards), and could tell me how to do it. > (Security was very light). For a few months, I hacked daily, and learned a > lot. Then the following year, I actually took an electrical engineering > class that introduced the concepts of programming, and I spent my time doing > experiments that barely resembled the assignments. I ended up with an > incomplete in the course, which I made up by writing a linear circuit > analysis program. Punched card input, graphical output to a line printer > using rows of asterisks. > How to start, I learned C 10 years ago, but for whole semester, I never wrote a serious program, but indeed attended every lecture. At that time, I was addicted literature staff. But later realized that lots of writers (especially the ones I like) ended up with committing suicide, something to heavy to handle, so I changed to something like physics, I noted lots of people doing physics living really long and happy (long living the physicist), then four years as (applied) physics, three years as (theoretical) physics, then (bio-) physics in the following years. (It's a joke). During those years used maple, matlab and some basic awk, bash. but all is very basic. shame...did not do something seriously. > > Point is, it takes a lot of time, and usually a one-on-one mentor to get > the concepts nailed down. Seldom did anyone tell me "write these lines > down, and it'll solve the problem." instead they told me where my problem > was, and where in those manuals (chained to tables in the lab) to find more > information. > > It wasn't till my fourth language that I found out about local variables, > and how a function should encapsulate one concept. The first three didn't > have such things. > > > > Further, while you're developing, you should probably put the test data >>> into a literal (probably a multiline literal using triplequotes), so you >>> can >>> experiment easily with changes to the data, and see how it results. >>> >>> >> #!/bin/python >> >> import os.path >> >> tokens=['B','E'] >> >> for fileName in os.listdir("."): >> if os.path.isfile(fileName) and os.path.splitext(fileName)[1]=** >> =".xpm": >> filedata = open(fileName) >> text=filedata.readlines() >> results={} >> numcolumns=len(text.strip()) >> for ch in tokens: >> results[ch]=[0]*numcolumns >> for line in text: >> for col, ch in enumerate(line): >> if ch in tokens: >> results[ch][col]+=1 >> for item in results: >> print item >> >> $ python3 counter-vertically.py >> File "counter-vertically.py", line 20 >> print item >> ^ >> SyntaxError: invalid syntax >> >> As I said above, Python 3 needs parentheses around print's argument list. > > As for splitting into functions, consider: > > > #these two are capitalized because they're intended to be constant > TOKENS = "BE" > LINESTOSKIP = 43 > INFILEEXT = ".xpm" > OUTFILEEXT = ".txt" > > def dofiles(topdirectory): > for filename in os.listdr(topdirectory): > processfile(filename) > > def processfile(infilename): > base, ext =os.path.splitext(fileName) > if ext == INFILEEXT: > text = fetchonefiledata(infilename) > numcolumns = len(text[0]) > results = {} > for ch in TOKENS: > > results[ch] = [0] * numcolumns > for line in text: > line = line.strip() > > for col, ch in enumerate(line): > if ch in tokens: > results[ch][col] += 1 > writeonefiledata(base+**OUTFILEEXT, results) > > def fetchonefiledata(inname): > infile = open(inname) > text = infile.readlines() > return text[LINESTOSKIP:] > > def writeonefiledata(outname): > outfile = open(outname, "w") > ...process the results as appropriate... > ....(since you didn't tell us how multiple tokens were to be displayed) > > if __name__ == "__main__": > dofiles(".") #or get the top directory from the sys.argv variable, > which is set from command line. > > > You dissect the former one you suggested before into 4 functions. a little question, why choose .ext? why the splitext is also ext here? > Now this is totally untested. I just typed it without even trying any of > it. import os.path TOKENS="E" LINESTOSKIP=0 INFILEEXT=".xpm" OUTFILEEXT=".txt" def dofiles(topdirectory): for filename in os.listdir(topdirectory): processfile(filename) def processfile(infilename): base, ext =os.path.splitext(infilename) if ext == INFILEEXT: text = fetchonefiledata(infilename) numcolumns=len(text[0]) results={} for ch in TOKENS: results[ch] = [0]*numcolumns for line in text: line = line.strip() for col, ch in enumerate(line): if ch in TOKENS: results[ch][col]+=1 writeonefiledata(base+OUTFILEEXT,results) def fetchonefiledata(inname): infile = open(inname) text = infile.readlines() return text[LINESTOSKIP:] def writeonefiledata(outname,results): outfile = open(outname,"w") for item in results: return outfile.write(item) if __name__=="__main__": dofiles(".") just the results is a bit unexpected. $ more try.txt E I might make a mistake in the writeonefiledata your left part. But it gives you a simple refactoring that splits the logic so each can be > visualized (and tested) independently. i'd also split up processfile(), > once I realized how big it was. > > There are many shortcuts that can be applied. Some of them probably use > language features you're not comfortable with, like perhaps generators. And > if efficiency is important, there are optimizations to do, like using > islice directly on the infile object. That one would eliminate having to > have the whole file stored in memory at one time. > > Likewise there are further things that could be done to decouple the > functions even more. > > But there's nothing in the above code which uses very advanced topics, so > you should be able to understand it and fix whatever typos I've undoubtedly > got. > > What are you using for debugging aids? Besides this group, I mean. print > statements? An IDE ? which one? > debugging aids? I just run python3 script.py it will pop up some hints, in the middle, probably try print. Thanks for your time, > -- > > DaveA > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikunjbadjatya at gmail.com Wed Oct 5 09:32:23 2011 From: nikunjbadjatya at gmail.com (Nikunj Badjatya) Date: Wed, 5 Oct 2011 13:02:23 +0530 Subject: [Tutor] Calling Python Functions from Powershell scripts In-Reply-To: References: Message-ID: Howdy All, To give an overview of the problem, I have an installer. It is used to install virtual machines at specific location. The installer is written in Powershell and Python. The topmost script is in Python ( install.py ) which internally calls other .py and .PS1 ( powershell ) scripts using popen() . I am working on having a file based logging mechanism for this installer. i.e both for .py and .PS1 scripts. Q1. I want to use python logging module. But then how do I integrate it with powershell scripts. ? One option would be to write into a .log file using logging module in all .py scripts. Use that ( .log ) file in powershell scripts by using its own logging module ( dnt knw if it exists ! ) Q2. Can we call / run .py from inside .PS1. ? Please suggest suitable methods for effective logging mechanism. Thanks Nikunj Bangalore -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Wed Oct 5 09:48:06 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Wed, 5 Oct 2011 07:48:06 +0000 Subject: [Tutor] Calling Python Functions from Powershell scripts In-Reply-To: References: Message-ID: <170329125-1317800889-cardhu_decombobulator_blackberry.rim.net-1267371284-@b26.c12.bise7.blackberry> You can run .py files from powershell, just like you would run any other command - 'python myfile.py' I don't have any experience of the logging modules, but what I do when using multiple languages is have them all write to the same plain text log file and just prepend [] to the beginning of each line - that way I can track execution order and follow error/info messages all in one file. That's just how I prefer to do it. Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: Nikunj Badjatya Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Wed, 5 Oct 2011 13:02:23 To: tutor Subject: [Tutor] Calling Python Functions from Powershell scripts _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From cwitts at compuscan.co.za Wed Oct 5 09:57:17 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 05 Oct 2011 09:57:17 +0200 Subject: [Tutor] Calling Python Functions from Powershell scripts In-Reply-To: References: Message-ID: <4E8C0DDD.3000302@compuscan.co.za> On 2011/10/05 09:32 AM, Nikunj Badjatya wrote: > > Howdy All, > > To give an overview of the problem, > I have an installer. It is used to install virtual machines at > specific location. > The installer is written in Powershell and Python. The topmost script > is in > Python ( install.py ) which internally calls other .py and .PS1 ( > powershell ) scripts using popen() . > I am working on having a file based logging mechanism for this > installer. i.e both for .py and .PS1 scripts. > > Q1. I want to use python logging module. But then how do I integrate > it with powershell scripts. ? > One option would be to write into a .log file using logging module in > all .py scripts. Use that ( .log ) file > in powershell scripts by using its own logging module ( dnt knw if it > exists ! ) > > Q2. Can we call / run .py from inside .PS1. ? > > Please suggest suitable methods for effective logging mechanism. > > Thanks > > Nikunj > Bangalore > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor PowerShell has built-in cmdlets for logging that use the verb "write". Running the command "get-command write*" will list those commands for you (and a couple of other ones). Each one is controlled by a shell variable that ends with "Preference". For example, to turn the warning messages up, then set the variable $WarningPreference to "Continue". Other options are Stop, Inquire, and SilentlyContinue. To turn down logging, set each of the $*Preference session variables to "SilentlyContinue". To turn up logging, then set them all to "Continue". Here are some references for automatic logging [1] and a script template with a logging function [2] [1] http://jdhitsolutions.com/blog/2011/03/powershell-automatic-logging/ [2] http://powershell.com/cs/media/p/3950.aspx -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From amonroe at columbus.rr.com Wed Oct 5 13:58:45 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 5 Oct 2011 07:58:45 -0400 Subject: [Tutor] fake defrag revisited In-Reply-To: <4E8BF615.8000806@davea.name> References: <145120072334.20111001020636@columbus.rr.com> <4E86FE05.8040608@davea.name> <150155273711.20111001115318@columbus.rr.com> <4E875600.4060400@davea.name> <101169689560.20111001155333@columbus.rr.com> <4E8BF615.8000806@davea.name> Message-ID: <15135188871.20111005075845@columbus.rr.com> > Since all the moves are swaps, it'll be guaranteed to be in a sequence > that converges on the correct final order. Will it be the minimum > number of moves? Definitely not. But that wasn't a requirement, and if > it were, you wouldn't start by building that list of tuples. I did get a semi-working version, but it was crazy inefficient because it regenerated the swap list after every move, and it bombed out with a IndexError about half the time. I found that moving a single block at a time lacked the aesthetic appeal I was hoping for, so I bagged it for now. I changed gears and wrote a similar program to randomize all the pixels in a photo and then restore them one by one, by using two shuffled arrays as large as the pixel count to swap/unswap known-but-seemingly-random pixel pairs, but that also lacked the aesthetic appeal I wanted. I think to capture visual interest, the pieces would have to visibly assemble themselves by travelling across the screen, rather that just being painted in their final poistion. I may be biting off more than I can chew here. Alan From d at davea.name Wed Oct 5 14:21:58 2011 From: d at davea.name (Dave Angel) Date: Wed, 05 Oct 2011 08:21:58 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> Message-ID: <4E8C4BE6.9040908@davea.name> On 10/05/2011 02:51 AM, lina wrote: > On Wed, Oct 5, 2011 at 1:42 PM, Dave Angel wrote: > >> On 10/04/2011 11:13 PM, lina wrote: >> >>> On Wed, Oct 5, 2011 at 10:45 AM, Dave Angel wrote: >>> >>> On 10/04/2011 10:22 PM, lina wrote: >>>> On Wed, Oct 5, 2011 at 1:30 AM, Prasad, Ramit>>>> *com >>>>> >>>>>> w >>>>>> >>>>> >>>>> SyntaxError: invalid syntax >>>>> >>>>> for fileName in os.listdir("."): >>>>> if os.path.isfile(fileName) and os.path.splitext(fileName)[1]=**** >>>>> >>>>> =".xpm": >>>>> filedata = open(fileName) >>>>> text=filedata.readlines() >>>>> cols = len(text[0]) >>>>> except IndexError: >>>>> print ("Index Error.") >>>>> result=[] >>>>> for idx in xrange(cols): >>>>> results.append(0) >>>>> for line in text: >>>>> for col_idx, field in enumerate(line): >>>>> if token in field: >>>>> results[col_idx]+=1 >>>>> for index in col_idx: >>>>> print results[index] >>>>> >>>>> it showed up: >>>>> >>>>> print results[] >>>>> ^ >>>>> SyntaxError: invalid syntax >>>>> >>>>> Sorry, I am still lack deep understanding about something basic. Thanks >>>>> for >>>>> your patience. >>>>> >>>>> >>>>> Simplest answer here is you might have accidentally run this under >>>>> Python >>>>> >>>> 3.x. That would explain the syntax error on the print function. Pick a >>>> single version and stick to it. In fact, you might even put a version >>>> test >>>> at the beginning of the code to give an immediate error. >>>> >>>> choose python3. >>> Then change that last print to use parentheses. print() is a function >> call in Python 3.x, while it was a statement in earlier Python versions. >> >> >>> This example illustrates one reason why it's a mistake to write all the >>>> code at top level. This code should probably be at least 4 functions, >>>> with >>>> each one handling one abstraction. >>>> >>>> It's frustrating. Seriously. (I think I need to read some good >>> (relevant) >>> codes first. >>> >>> Is Python your first programming language? It was approximately my 30th. > Not exactly. Ha ... I don't know there are so many languages there. > >> I learned "programming" from a Fortran book in 1967. I had no access to a >> computer, though there was at least one in the state, at the Yale campus. I >> saw it in a field trip by the (advanced) students that were taking >> programming. They weren't allowed to take it till finishing 2nd year >> calculus, which I didn't do till I got to college. However, when I went to >> college the following year, I ran across another student who knew how to >> access the mainframe (via punch-cards), and could tell me how to do it. >> (Security was very light). For a few months, I hacked daily, and learned a >> lot. Then the following year, I actually took an electrical engineering >> class that introduced the concepts of programming, and I spent my time doing >> experiments that barely resembled the assignments. I ended up with an >> incomplete in the course, which I made up by writing a linear circuit >> analysis program. Punched card input, graphical output to a line printer >> using rows of asterisks. >> > How to start, I learned C 10 years ago, but for whole semester, I never > wrote a serious program, but indeed attended every lecture. > At that time, I was addicted literature staff. But later realized that lots > of writers (especially the ones I like) ended up with committing suicide, > something to heavy to handle, so I changed to something like physics, I > noted lots of people doing physics living really long and happy (long living > the physicist), then four years as (applied) physics, three years as > (theoretical) physics, then (bio-) physics in the following years. (It's a > joke). > During those years used maple, matlab and some basic awk, bash. but all is > very basic. shame...did not do something seriously. > >> Point is, it takes a lot of time, and usually a one-on-one mentor to get >> the concepts nailed down. Seldom did anyone tell me "write these lines >> down, and it'll solve the problem." instead they told me where my problem >> was, and where in those manuals (chained to tables in the lab) to find more >> information. >> >> It wasn't till my fourth language that I found out about local variables, >> and how a function should encapsulate one concept. The first three didn't >> have such things. >> >> >> >> Further, while you're developing, you should probably put the test data >>>> into a literal (probably a multiline literal using triplequotes), so you >>>> can >>>> experiment easily with changes to the data, and see how it results. >>>> >>>> >>> #!/bin/python >>> >>> import os.path >>> >>> tokens=['B','E'] >>> >>> for fileName in os.listdir("."): >>> if os.path.isfile(fileName) and os.path.splitext(fileName)[1]=** >>> =".xpm": >>> filedata = open(fileName) >>> text=filedata.readlines() >>> results={} >>> numcolumns=len(text.strip()) >>> for ch in tokens: >>> results[ch]=[0]*numcolumns >>> for line in text: >>> for col, ch in enumerate(line): >>> if ch in tokens: >>> results[ch][col]+=1 >>> for item in results: >>> print item >>> >>> $ python3 counter-vertically.py >>> File "counter-vertically.py", line 20 >>> print item >>> ^ >>> SyntaxError: invalid syntax >>> >>> As I said above, Python 3 needs parentheses around print's argument list. >> As for splitting into functions, consider: >> >> >> #these two are capitalized because they're intended to be constant >> TOKENS = "BE" >> LINESTOSKIP = 43 >> INFILEEXT = ".xpm" >> OUTFILEEXT = ".txt" >> >> def dofiles(topdirectory): >> for filename in os.listdr(topdirectory): >> processfile(filename) >> >> def processfile(infilename): >> base, ext =os.path.splitext(fileName) >> if ext == INFILEEXT: >> text = fetchonefiledata(infilename) >> numcolumns = len(text[0]) >> results = {} >> for ch in TOKENS: >> >> results[ch] = [0] * numcolumns >> for line in text: >> line = line.strip() >> >> for col, ch in enumerate(line): >> if ch in tokens: >> results[ch][col] += 1 >> writeonefiledata(base+**OUTFILEEXT, results) >> >> def fetchonefiledata(inname): >> infile = open(inname) >> text = infile.readlines() >> return text[LINESTOSKIP:] >> >> def writeonefiledata(outname): >> outfile = open(outname, "w") >> ...process the results as appropriate... >> ....(since you didn't tell us how multiple tokens were to be displayed) >> >> if __name__ == "__main__": >> dofiles(".") #or get the top directory from the sys.argv variable, >> which is set from command line. >> >> >> You dissect the former one you suggested before into 4 functions. > a little question, why choose .ext? why the splitext is also ext here? > > > Try the following, perhaps in the interpreter: mytuple = ("one thing", "Another thing") base, extension = mytuple Now look and see what base and extension have for values. Previously we just needed the second element of the splitext return value. This time we'll need both, so might as well put them in variables that have useful names. >> Now this is totally untested. I just typed it without even trying any of >> it. > > > import os.path > > > TOKENS="E" > LINESTOSKIP=0 > INFILEEXT=".xpm" > OUTFILEEXT=".txt" > > def dofiles(topdirectory): > for filename in os.listdir(topdirectory): > processfile(filename) > > def processfile(infilename): > base, ext =os.path.splitext(infilename) > if ext == INFILEEXT: > text = fetchonefiledata(infilename) > numcolumns=len(text[0]) > results={} > for ch in TOKENS: > > results[ch] = [0]*numcolumns > for line in text: > line = line.strip() > > for col, ch in enumerate(line): > if ch in TOKENS: > results[ch][col]+=1 > writeonefiledata(base+OUTFILEEXT,results) > > def fetchonefiledata(inname): > infile = open(inname) > text = infile.readlines() > return text[LINESTOSKIP:] > > def writeonefiledata(outname,results): > outfile = open(outname,"w") > for item in results: > return outfile.write(item) > > > if __name__=="__main__": > dofiles(".") > > just the results is a bit unexpected. > > $ more try.txt > E > > I might make a mistake in the writeonefiledata your left part. > I'd be amazed if there weren't at least a couple of typos in my message. But this is where you sprinkle a couple of prints. What did results look like when you print it out? I hope you'll find that results is a dictionary, you might not want to just write() its keys. You probably want to write() its values instead, perhaps with a heading showing what key you're printing. > But it gives you a simple refactoring that splits the logic so each can be >> visualized (and tested) independently. i'd also split up processfile(), >> once I realized how big it was. >> >> There are many shortcuts that can be applied. Some of them probably use >> language features you're not comfortable with, like perhaps generators. And >> if efficiency is important, there are optimizations to do, like using >> islice directly on the infile object. That one would eliminate having to >> have the whole file stored in memory at one time. >> >> Likewise there are further things that could be done to decouple the >> functions even more. >> >> But there's nothing in the above code which uses very advanced topics, so >> you should be able to understand it and fix whatever typos I've undoubtedly >> got. >> >> What are you using for debugging aids? Besides this group, I mean. print >> statements? An IDE ? which one? >> > debugging aids? > I just run python3 script.py > it will pop up some hints, > in the middle, probably try print. > Once the code is refactored into small enough independent functions, you can do things like write multiple versions of a given function, for debugging purposes. For example, you could have another function called fetchonefiledata(), and have it return a list of strings. For example, it might be def fetchonefiledata(dummy): buf = """EEDC AAAC F145 CCCA """ return buf.split() and then you wouldn't be dependent on an actual file being available. Naturally, at that point, your top-level code would call processfiles() instead of dofile(). And remember the repr() and type() functions when trying to see just what type of thing something is. . > Thanks for your time, > You're certainly welcome. -- DaveA From lina.lastname at gmail.com Wed Oct 5 14:46:28 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 5 Oct 2011 20:46:28 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8C4BE6.9040908@davea.name> References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> Message-ID: On Wed, Oct 5, 2011 at 8:21 PM, Dave Angel wrote: > > >> >>> #these two are capitalized because they're intended to be constant >>> TOKENS = "BE" >>> LINESTOSKIP = 43 >>> INFILEEXT = ".xpm" >>> OUTFILEEXT = ".txt" >>> >>> def dofiles(topdirectory): >>> for filename in os.listdr(topdirectory): >>> >> Here your typo is listdir not listdr, > processfile(filename) >>> >>> def processfile(infilename): >>> base, ext =os.path.splitext(fileName) >>> >> Here I changed the fileName to infilename > if ext == INFILEEXT: >>> text = fetchonefiledata(infilename) >>> numcolumns = len(text[0]) >>> results = {} >>> for ch in TOKENS: >>> >>> results[ch] = [0] * numcolumns >>> for line in text: >>> line = line.strip() >>> >>> for col, ch in enumerate(line): >>> if ch in tokens: >>> >> Here I changed the tokens to TOKENS > results[ch][col] += 1 >>> writeonefiledata(base+**OUTFILEEXT, results) >>> >>> >>> def fetchonefiledata(inname): >>> infile = open(inname) >>> text = infile.readlines() >>> return text[LINESTOSKIP:] >>> >>> def writeonefiledata(outname): >>> outfile = open(outname, "w") >>> ...process the results as appropriate... >>> ....(since you didn't tell us how multiple tokens were to be >>> displayed) >>> >>> if __name__ == "__main__": >>> dofiles(".") #or get the top directory from the sys.argv variable, >>> which is set from command line. >>> >>> >>> You dissect the former one you suggested before into 4 functions. >>> >> >> a little question, why choose .ext? why the splitext is also ext here? >> >> >> >> Try the following, perhaps in the interpreter: > > mytuple = ("one thing", "Another thing") > base, extension = mytuple > > Now look and see what base and extension have for values. > > Previously we just needed the second element of the splitext return value. > This time we'll need both, so might as well put them in variables that have > useful names. Yes, thanks for reminding, I understand now. > > > >> >> import os.path >> >> >> TOKENS="E" >> LINESTOSKIP=0 >> INFILEEXT=".xpm" >> OUTFILEEXT=".txt" >> >> def dofiles(topdirectory): >> for filename in os.listdir(topdirectory): >> processfile(filename) >> >> def processfile(infilename): >> base, ext =os.path.splitext(infilename) >> if ext == INFILEEXT: >> text = fetchonefiledata(infilename) >> numcolumns=len(text[0]) >> results={} >> for ch in TOKENS: >> >> results[ch] = [0]*numcolumns >> for line in text: >> line = line.strip() >> >> for col, ch in enumerate(line): >> if ch in TOKENS: >> results[ch][col]+=1 >> writeonefiledata(base+**OUTFILEEXT,results) >> >> def fetchonefiledata(inname): >> infile = open(inname) >> text = infile.readlines() >> return text[LINESTOSKIP:] >> >> def writeonefiledata(outname,**results): >> outfile = open(outname,"w") >> for item in results: >> return outfile.write(item) >> >> >> if __name__=="__main__": >> dofiles(".") >> >> just the results is a bit unexpected. >> >> $ more try.txt >> E >> >> I might make a mistake in the writeonefiledata your left part. >> >> I'd be amazed if there weren't at least a couple of typos in my message. > But this is where you sprinkle a couple of prints. What did results look > like when you print it out? > Yes, you did keep some typos there. The result is kind of weird? only E there. def writeonefiledata(outname,results): outfile = open(outname,"w") for item in results: return outfile.write(item) This final part I made some mistakes? > > I hope you'll find that results is a dictionary, you might not want to just > write() its keys. You probably want to write() its values instead, perhaps > with a heading showing what key you're printing. Later I wish to get the value of B+E, the two tokens. so the final results of each columns is enough. I will use this data to proceed further in future. > > > But it gives you a simple refactoring that splits the logic so each can be >> >>> visualized (and tested) independently. i'd also split up processfile(), >>> once I realized how big it was. >>> >>> There are many shortcuts that can be applied. Some of them probably use >>> language features you're not comfortable with, like perhaps generators. >>> And >>> if efficiency is important, there are optimizations to do, like using >>> islice directly on the infile object. That one would eliminate having to >>> have the whole file stored in memory at one time. >>> >>> Likewise there are further things that could be done to decouple the >>> functions even more. >>> >>> But there's nothing in the above code which uses very advanced topics, so >>> you should be able to understand it and fix whatever typos I've >>> undoubtedly >>> got. >>> >>> What are you using for debugging aids? Besides this group, I mean. >>> print >>> statements? An IDE ? which one? >>> >>> debugging aids? >> I just run python3 script.py >> it will pop up some hints, >> in the middle, probably try print. >> >> Once the code is refactored into small enough independent functions, you > can do things like write multiple versions of a given function, for > debugging purposes. For example, you could have another function called > fetchonefiledata(), and have it return a list of strings. For example, it > might be > > def fetchonefiledata(dummy): > buf = """EEDC > AAAC > F145 > CCCA > """ > return buf.split() > > and then you wouldn't be dependent on an actual file being available. > > Naturally, at that point, your top-level code would call processfiles() > instead of dofile(). > > And remember the repr() and type() functions when trying to see just what > type of thing something is.y > I have not figured it out how to use the repr() and type() yet. another question, you know in linux, when use TAB, can automatically input something, so in python3, are there some way they can intelligent give some hints or fill the left. Thanks again, > . > >> Thanks for your time, >> >> > You're certainly welcome. > > > > -- > > DaveA > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Oct 5 15:18:23 2011 From: d at davea.name (Dave Angel) Date: Wed, 05 Oct 2011 09:18:23 -0400 Subject: [Tutor] fake defrag revisited In-Reply-To: <15135188871.20111005075845@columbus.rr.com> References: <145120072334.20111001020636@columbus.rr.com> <4E86FE05.8040608@davea.name> <150155273711.20111001115318@columbus.rr.com> <4E875600.4060400@davea.name> <101169689560.20111001155333@columbus.rr.com> <4E8BF615.8000806@davea.name> <15135188871.20111005075845@columbus.rr.com> Message-ID: <4E8C591F.6050703@davea.name> On 10/05/2011 07:58 AM, R. Alan Monroe wrote: >> Since all the moves are swaps, it'll be guaranteed to be in a sequence >> that converges on the correct final order. Will it be the minimum >> number of moves? Definitely not. But that wasn't a requirement, and if >> it were, you wouldn't start by building that list of tuples. > I did get a semi-working version, but it was crazy inefficient because > it regenerated the swap list after every move, and it bombed out with > a IndexError about half the time. I found that moving a single block > at a time lacked the aesthetic appeal I was hoping for, so I bagged it > for now. > > I changed gears and wrote a similar program to randomize all the > pixels in a photo and then restore them one by one, by using two > shuffled arrays as large as the pixel count to swap/unswap > known-but-seemingly-random pixel pairs, but that also lacked the > aesthetic appeal I wanted. > > I think to capture visual interest, the pieces would have to visibly > assemble themselves by travelling across the screen, rather that just > being painted in their final poistion. I may be biting off more than I > can chew here. > > Alan > > __ I still recommend using sort, but perhaps the bulit-in sort is too fast. Why not try a bubble sort first, where only adjacent pixels are swapped, and only if they're in the wrong order. Then once you have the mechanism (a compare function, and a swap function) in place, you can try other algorithms, some faster and some slower. I knew somebody who put together a demo sorting a random string of 2000 characters, simply doing the sort algorithm directly on the video hardware screen buffer. Processors were so slow (4mhz) that the display worked great, showing bubble sort traversing back and forth, and showring various other algorithms being faster. And the quicksort algorithm pretty much shimmered for a moment, then stopped with the characters in their final places. Anyway, you can slow it down drastically by alternating bubble passes with random passes, where in each case a random pair is swapped if they're out of order. DaveA -- DaveA From d at davea.name Wed Oct 5 15:38:34 2011 From: d at davea.name (Dave Angel) Date: Wed, 05 Oct 2011 09:38:34 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> Message-ID: <4E8C5DDA.4060906@davea.name> On 10/05/2011 08:46 AM, lina wrote: > On Wed, Oct 5, 2011 at 8:21 PM, Dave Angel wrote: > >> >>>> #these two are capitalized because they're intended to be constant >>>> TOKENS = "BE" >>>> LINESTOSKIP = 43 >>>> INFILEEXT = ".xpm" >>>> OUTFILEEXT = ".txt" >>>> >>>> def dofiles(topdirectory): >>>> for filename in os.listdr(topdirectory): >>>> >>> Here your typo is listdir not listdr, >> processfile(filename) >>>> def processfile(infilename): >>>> base, ext =os.path.splitext(fileName) >>>> >>> Here I changed the fileName to infilename >> if ext == INFILEEXT: >>>> text = fetchonefiledata(infilename) >>>> numcolumns = len(text[0]) >>>> results = {} >>>> for ch in TOKENS: >>>> >>>> results[ch] = [0] * numcolumns >>>> for line in text: >>>> line = line.strip() >>>> >>>> for col, ch in enumerate(line): >>>> if ch in tokens: >>>> >>> Here I changed the tokens to TOKENS >> results[ch][col] += 1 >>>> writeonefiledata(base+**OUTFILEEXT, results) >>>> >>>> >>>> def fetchonefiledata(inname): >>>> infile = open(inname) >>>> text = infile.readlines() >>>> return text[LINESTOSKIP:] >>>> >>>> def writeonefiledata(outname): >>>> outfile = open(outname, "w") >>>> ...process the results as appropriate... >>>> ....(since you didn't tell us how multiple tokens were to be >>>> displayed) >>>> >>>> if __name__ == "__main__": >>>> dofiles(".") #or get the top directory from the sys.argv variable, >>>> which is set from command line. >>>> >>>> >>>> You dissect the former one you suggested before into 4 functions. >>>> >>> a little question, why choose .ext? why the splitext is also ext here? >>> >>> >>> >>> Try the following, perhaps in the interpreter: >> mytuple = ("one thing", "Another thing") >> base, extension = mytuple >> >> Now look and see what base and extension have for values. >> >> Previously we just needed the second element of the splitext return value. >> This time we'll need both, so might as well put them in variables that have >> useful names. > Yes, thanks for reminding, I understand now. > >> >> >>> import os.path >>> >>> >>> TOKENS="E" >>> LINESTOSKIP=0 >>> INFILEEXT=".xpm" >>> OUTFILEEXT=".txt" >>> >>> def dofiles(topdirectory): >>> for filename in os.listdir(topdirectory): >>> processfile(filename) >>> >>> def processfile(infilename): >>> base, ext =os.path.splitext(infilename) >>> if ext == INFILEEXT: >>> text = fetchonefiledata(infilename) >>> numcolumns=len(text[0]) >>> results={} >>> for ch in TOKENS: >>> >>> results[ch] = [0]*numcolumns >>> for line in text: >>> line = line.strip() >>> >>> for col, ch in enumerate(line): >>> if ch in TOKENS: >>> results[ch][col]+=1 >>> writeonefiledata(base+**OUTFILEEXT,results) >>> >>> def fetchonefiledata(inname): >>> infile = open(inname) >>> text = infile.readlines() >>> return text[LINESTOSKIP:] >>> >>> def writeonefiledata(outname,**results): >>> outfile = open(outname,"w") >>> for item in results: >>> return outfile.write(item) >>> >>> >>> if __name__=="__main__": >>> dofiles(".") >>> >>> just the results is a bit unexpected. >>> >>> $ more try.txt >>> E >>> >>> I might make a mistake in the writeonefiledata your left part. >>> >>> I'd be amazed if there weren't at least a couple of typos in my message. >> But this is where you sprinkle a couple of prints. What did results look >> like when you print it out? >> > Yes, you did keep some typos there. > The result is kind of weird? only E there. > I ask again. What did results look like when you print it out. I'm referring to the argument to writeonefiledata(). > def writeonefiledata(outname,results): put the lines here: print ("results is: ", results) print("repr is:", repr(results)) > outfile = open(outname,"w") > for item in results: > return outfile.write(item) > > This final part I made some mistakes? > yes, you're iterating over the keys of a dictionary. Since it only has the key "E", that's what you get. Try printing dir(results) to see what methods might return something other than the key. Make the language work for you. >> I hope you'll find that results is a dictionary, you might not want to just >> write() its keys. You probably want to write() its values instead, perhaps >> with a heading showing what key you're printing. > Later I wish to get the value of B+E, the two tokens. so the final results > of each columns is enough. I will use this data to proceed further in > future. > the code to get multiple keys is already there. Only reason you're getting only E is that you only specified one token. Try changing it to TOKENS = "EA" >> >> But it gives you a simple refactoring that splits the logic so each can be >>>> visualized (and tested) independently. i'd also split up processfile(), >>>> once I realized how big it was. >>>> >>>> There are many shortcuts that can be applied. Some of them probably use >>>> language features you're not comfortable with, like perhaps generators. >>>> And >>>> if efficiency is important, there are optimizations to do, like using >>>> islice directly on the infile object. That one would eliminate having to >>>> have the whole file stored in memory at one time. >>>> >>>> Likewise there are further things that could be done to decouple the >>>> functions even more. >>>> >>>> But there's nothing in the above code which uses very advanced topics, so >>>> you should be able to understand it and fix whatever typos I've >>>> undoubtedly >>>> got. >>>> >>>> What are you using for debugging aids? Besides this group, I mean. >>>> print >>>> statements? An IDE ? which one? >>>> >>>> debugging aids? >>> I just run python3 script.py >>> it will pop up some hints, >>> in the middle, probably try print. >>> >>> Once the code is refactored into small enough independent functions, you >> can do things like write multiple versions of a given function, for >> debugging purposes. For example, you could have another function called >> fetchonefiledata(), and have it return a list of strings. For example, it >> might be >> >> def fetchonefiledata(dummy): >> buf = """EEDC >> AAAC >> F145 >> CCCA >> """ >> return buf.split() >> >> and then you wouldn't be dependent on an actual file being available. >> >> Naturally, at that point, your top-level code would call processfiles() >> instead of dofile(). >> >> And remember the repr() and type() functions when trying to see just what >> type of thing something is.y >> > I have not figured it out how to use the repr() and type() yet. So try them. repr() shows you a lot more information about an object than str() does, and the latter is what you're getting when you print something directly. And type() shows you the type of something. And dir() shows you the attributes of something. Usually what you're interested in is the list of methods. Anyway. once you find an interesting one you can do help() on it. For example, try help( {}.iteritems ) > another question, you know in linux, when use TAB, can automatically input > something, > so in python3, are there some way they can intelligent give some hints or > fill the left. > Sure, that's the job of the IDE. If you just want auto-indentation, emacs can do that with the python macros. But if you want full method expansion and such, look into one of a dozen IDEs. I happen to use Komodo, but there are others free, and non-free. And there's Ipython. And I think there's something included in CPython, but I never looked into it. -- DaveA From bgailer at gmail.com Wed Oct 5 15:42:56 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 05 Oct 2011 09:42:56 -0400 Subject: [Tutor] extract information from txtfile In-Reply-To: References: Message-ID: <4E8C5EE0.1000609@gmail.com> On 10/4/2011 4:00 PM, Anna Olofsson wrote: > Hi, > I'm a beginner at Python and I'm trying to extract some information > from a textfile where I have a lot of data. > > The table looks something like this, but with many more columns and rows: > > # chr Pos ID REF ALT . . . . . . . . . . . > 1 13645 - C T > . . . . . > . . . . . > > I want to extract certain data from this table above and make it to a > sentence looking something like this: chr1:13645 C/T > > I have created a pseudo code, just to get an overview of want I want > to do, looking like this: > > import OS > open vcf_file.vcf > for each line > words = > split(line) > # words[0] = 1 , words[1]=Pos , words[3]=REF , words[4]=ALT > if(words[0] not > "#"): > #Sometimes the word starts with a hash and I don't want that to be > included. > str="chr" + words[0] + ":" + words[1] + "\t" + words[3] + > "/" + words[4] > score = OS.system(str) > vcf_file.close() > > print result > > return score > > > I'm not exactly sure how to proceed from here. I suggest you convert the pseudo-code into a Pythin program, then run it. If that gives you grief then tackle it one task at a time. For example, open, read, print, close a file. Then add another level of complication, for example open, read, split, print, close a file. The part that makes no sense to me is score = OS.system(str). What will str be and what do you want system to return? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Oct 5 15:50:36 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 5 Oct 2011 08:50:36 -0500 Subject: [Tutor] fake defrag revisited In-Reply-To: <4E8C591F.6050703@davea.name> References: <145120072334.20111001020636@columbus.rr.com> <4E86FE05.8040608@davea.name> <150155273711.20111001115318@columbus.rr.com> <4E875600.4060400@davea.name> <101169689560.20111001155333@columbus.rr.com> <4E8BF615.8000806@davea.name> <15135188871.20111005075845@columbus.rr.com> <4E8C591F.6050703@davea.name> Message-ID: On Wed, Oct 5, 2011 at 8:18 AM, Dave Angel wrote: > Anyway, you can slow it down drastically by alternating bubble passes with > random passes, where in each case a random pair is swapped if they're out of > order. > You can also slow it down by adding a time.sleep(1) (sleeps for 1 second). Use 0.1 for a tenth if one second is too slow. Or time.sleep(random.random()) if you want a variable (0-1 second) sleep time. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Wed Oct 5 16:15:08 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 5 Oct 2011 22:15:08 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8C5DDA.4060906@davea.name> References: <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> Message-ID: > I ask again. What did results look like when you print it out. I'm > referring to the argument to writeonefiledata(). > >> def writeonefiledata(outname,**results): >> > put the lines here: > print ("results is: ", results) > print("repr is:", repr(results)) $ python3 counter-vertically-v2.py results is: {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]} repr is: {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]} > > outfile = open(outname,"w") >> for item in results: >> return outfile.write(item) >> >> This final part I made some mistakes? >> >> yes, you're iterating over the keys of a dictionary. Since it only has > the key "E", that's what you get. Try printing dir(results) to see what > methods might return something other than the key. Make the language work > for you. Sorry I am not smart. value? > > > DaveA > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Oct 5 20:01:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 05 Oct 2011 19:01:04 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> Message-ID: On 05/10/11 13:46, lina wrote: > another question, you know in linux, when use TAB, can automatically > input something, > so in python3, are there some way they can intelligent give some hints > or fill the left. What development tool are you using? If you use IDLE, the standard IDE that comes with Python, you should find that hitting tab (or pausing briefly) in a file editor will bring up a pick list of options. Similarly typing a function name and an open paren will give a tooltip for the functions parameters. IPython will do some similar things for you as a replacement for the standard Python interpreter (plus a bunch of extras). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Oct 5 20:09:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 05 Oct 2011 19:09:08 +0100 Subject: [Tutor] extract information from txtfile In-Reply-To: References: Message-ID: On 04/10/11 21:00, Anna Olofsson wrote: > The table looks something like this, but with many more columns and rows: > > # chr Pos ID REF ALT . . . . . . . . . . . > 1 13645 - C T > . . . . . > > I want to extract certain data from this table above and make it to a > sentence looking something like this: chr1:13645 C/T > > import OS > open vcf_file.vcf > for each line > words = split(line) # words[0] = 1 , words[1]=Pos , words[3]=REF , > words[4]=ALT > if(words[0] not "#"): #Sometimes the word starts with a hash and I don't > str="chr" + words[0] + ":" + words[1] + "\t" + words[3] + "/" + words[4] > score = OS.system(str) So basically you are trying to construct an OS command from the file data and then execute it and store the result? You are pretty close. Some things to note when you try to convert it to real code: 1) the module is os not OS (but see below...). 2) you can say for line in open(filename): 3) Python uses the object.method style so split(line) become line.split() 4) use != rather than not in the if test 5) str is a builtin type so to avoid hiding it use another name (command maybe?) 6) os.system only returns the error code, to capture the output you should look at the subprocess module(see the documentation for examples) Other than that the translation should be pretty close to what you have. Try it and come back if you get stuck. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From nozarm at triumf.ca Wed Oct 5 20:12:00 2011 From: nozarm at triumf.ca (Mina Nozar) Date: Wed, 05 Oct 2011 11:12:00 -0700 Subject: [Tutor] regex and parsing through a semi-csv file In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> Message-ID: <4E8C9DF0.8040805@triumf.ca> Hi everyone, I am post processing data from the output of simulation of activities for various radionuclide produced in a reaction at different times. I have already combined the information from 13 files (containing calculated activities and errors for 13 different times). The format of this combined, semi-csv file is the following: A line with an element's name, its isotope number, and its atomic number, followed by 13 lines containing activation time 1, activation 1, error in activation time 1 ... ... So here what the input file looks for two isotopes: AC,225,89 3.6000e+03,1.6625e-07,2.4555e-09 8.6400e+04,0.0000e+00,-1.1455e-23 2.5920e+05,3.1615e-07,4.6695e-09 8.6400e+05,3.6457e-05,5.3847e-07 1.8000e+06,5.5137e-04,8.1437e-06 1.8036e+06,5.5047e-04,8.1304e-06 1.8864e+06,5.3279e-04,7.8693e-06 2.6640e+06,6.9672e-04,1.0291e-05 4.3920e+06,3.2737e-03,4.8353e-05 1.0440e+07,2.3830e-02,3.5197e-04 2.7720e+07,9.2184e-02,1.3616e-03 8.8200e+07,9.2184e-02,1.3616e-03 1.7460e+08,6.7440e-01,9.9609e-03 AG,111,47 3.6000e+03,1.7936e+07,3.1191e+05 8.6400e+04,7.9538e+08,1.3800e+07 2.5920e+05,2.2201e+09,3.8519e+07 8.6400e+05,5.5546e+09,9.6372e+07 1.8000e+06,7.8612e+09,1.3639e+08 1.8036e+06,7.8484e+09,1.3617e+08 1.8864e+06,7.1836e+09,1.2464e+08 2.6640e+06,3.1095e+09,5.3950e+07 4.3920e+06,4.8368e+08,8.3918e+06 1.0440e+07,7.1793e+05,1.2456e+04 2.7720e+07,5.9531e-03,1.0329e-04 8.8200e+07,5.9531e-03,1.0329e-04 1.7460e+08,0.0000e+00,0.0000e+00 Now, I would like to parse through this code and fill out 3 lists: 1) activity_time, 2) activity, 3) error, and plot the activities as a function of time using matplotlip. My question specifically is on how to parse through the lines containing the data (activity time, activity, error) for a given isotope, stopping before reaching the next isotope's info. The test I am trying in the following snippet is not working. found_isotope = False activity_time = [] activity = [] activity_err = [] f = open(args.fname, 'r') for line in f.readlines(): line = line.strip() if isotope_name in line and isotope_A in line: print isotope_name, isotope_A found_isotope = True continue if found_isotope: print line found = re.search(r'(\d+\.[eE][\+\-]\d+),(\d+\.[eE][\+\-]\d+),(\d+\.[eE][\+\-]\d+)', line, re.I) print found if found: print found.group(1), found.group(2), found.group(3) activity_time.append(found.group(1)) activity.append(found.group(2)) activity_err.append(found.group(3)) continue else: break f.close() If I run the code for isotope_name: AC and isotope_A: 225, I get the following: AC 225 3.6000e+03,1.6625e-07,2.4555e-09 None Note that the size of the lists will change depending on the number of activities for a given run of the simulation so I don't want to hard code '13' as the number of lines to read in followed by the line containing isotope_name, etc. If there is a more graceful way of doing this, please let me know as well. I am new to python... Thank you very much, Mina From waynejwerner at gmail.com Wed Oct 5 22:24:05 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 5 Oct 2011 15:24:05 -0500 Subject: [Tutor] regex and parsing through a semi-csv file In-Reply-To: <4E8C9DF0.8040805@triumf.ca> References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C9DF0.8040805@triumf.ca> Message-ID: On Wed, Oct 5, 2011 at 1:12 PM, Mina Nozar wrote: > > If there is a more graceful way of doing this, please let me know as well. > I am new to python... > I just glanced through your email, but my initial thought would be to just use regex to collect the entire segment that you're looking for, and then string methods to split it up: pat = re.compile('({name},{number}.*?)[A-Z]{{1,2}}'.format(name='AC', number='225'), re.DOTALL) raw_data = re.search(pat, f.read()) if raw_data is None: # we didn't find the isotope, so take appropriate actions, quit or tell the user else: raw_data = raw_data.string.strip().split('\n') Then it depends on how you want to process your data, but you could easily use list comprehensions/generator expressions. The most terse syntax I know of: data = [[float(x) for x in d.split(',')] for d in raw_data if d[0].isdigit()] Which is basically the equivalent of: data = [] for d in raw_data: if d[0].isdigit(): floats = [] for x in d.split(','): floats.append(x) data.append(floats) data will then contain a list of 3-element lists of floating point values. If you want to "rotate" the list, you can do data = list(zip(*data)). To illustrate: >>> d = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']] >>> d = list(zip(*d)) >>> d [('a', 'a', 'a', 'a'), ('b', 'b', 'b', 'b'), ('c', 'c', 'c', 'c')] HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Wed Oct 5 22:33:47 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 5 Oct 2011 16:33:47 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> >>yes, you're iterating over the keys of a dictionary. Since it only has the key "E", that's what you get. Try printing dir(results) to see what methods might return something other than the key. Make the language work for you. >Sorry I am not smart. value? Dictionaries {} are containers for key/value based pairs like { key : value, another_key : value(can be same or repeated) } For example: {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]} The keys here are 'B' and 'E'. The values here are [0, 0, 0, 0, 0, 0] (for key 'B') and [2, 1, 4, 0, 1, 0] (for key 'E') You can get the value of a dictionary by doing: value = dictionary[key] You can set the value of a dictionary by doing: dictionary[key] = value You will get an exception if you try to get a value for a key that is not in the dictionary. >>> dictionary = {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]} >>> dictionary['F'] KeyError: 'F' You can iterate over dictionaries in a couple ways 1- for key in dictionary: # also the same as # for key in dictionary.keys() value = dictionary[ key ] 2- for key, value in dictionary.iteritems(): < do something here with > Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From olofsson_anna585 at hotmail.com Wed Oct 5 21:29:04 2011 From: olofsson_anna585 at hotmail.com (Anna Olofsson) Date: Wed, 5 Oct 2011 21:29:04 +0200 Subject: [Tutor] vcf_files and strings Message-ID: Hi, I'm a beginner at Python and would really like some help in how to extract information from a vcf file. The attached file consists of a lot of information on mutations, this one though is just 2 rows and 10 columns (the real one has a lot more rows). I want to extract the mRNA ID only if the mutation is missense. These two rows (mutations) that I have attached happens to be missense but how do I say that I'm not interested in the mutations that's not missense (they might be e.g. synonymous). Also, how do I say that if a mutation starts with a # symbol I don't want to include it (sometimes the chr starts with a hash). vcf file: 2 rows, 10 columns. col 0 col 1 col 2 col 3 col 4 col5 col6 col7 col8 col9 chromosome position . Reference ALT position . some statistics and the ID:s not important not important The important column is 7 where the ID is, i.e. refseq.functionalClass=missense. It's a missense mutation, so then I want to extract refseq.name=NM_003137492, or I want to extract only the ID, which in this case is NM_003137492. Then I want to do exactly the same thing for all the other mutations, but only for the missense mutations not the other ones. How do I accomplish that? Where do I start? Best, Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: vcf_file.vcf Type: text/directory Size: 1368 bytes Desc: not available URL: From g.nius.ck at gmail.com Wed Oct 5 23:51:35 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Wed, 5 Oct 2011 17:51:35 -0400 Subject: [Tutor] String switch In-Reply-To: <4E8B9FD5.5070602@gmail.com> References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> Message-ID: There is a program that will open another program, write code at the top of the program. The code at the top will cause the program to print all strings afterwards in swap case. -------------- next part -------------- An HTML attachment was scrubbed... URL: From liam at steelsky.co.nz Thu Oct 6 00:21:17 2011 From: liam at steelsky.co.nz (Liam Clarke) Date: Thu, 6 Oct 2011 11:21:17 +1300 Subject: [Tutor] Mac IDE In-Reply-To: References: <61310E38B60C8F4AB59757E88A3C967723F3021237@UMDAC-CCR2.ad.umu.se> Message-ID: <94FCE344-F9C6-4214-890A-B2C93FEEEB93@steelsky.co.nz> I second the recommendation of PyCharm, it's the best Python IDE I've used. Alan - OS X has Vim by default? At least, I've always used it and never installed it, but I started from 10.5. Regards, Liam Clarke On 30/09/2011, at 3:43 AM, Tom Tucker wrote: > > Another IDE to consider that supports the MAC OS is PyCharm from JetBrains. > > On Thu, Sep 29, 2011 at 7:50 AM, Wayne Werner wrote: > On Thu, Sep 29, 2011 at 5:50 AM, Walter Prins wrote: > On 29 September 2011 10:42, Robert Johansson wrote: > Hi, > > > > I know that there is a lot to read about different IDEs on the net but I have tried a couple and I?m still not pleased. My demands are not that high, when I?m under Windows I?m happy with IDLE (an interactive shell and debug) but the problem is with Mac (Python >= 2.7 and OS 10.7). IDLE had serious problems and TextWrangler had no interactive shell. There?s a lot of other stuff to try and I would be grateful if someone could spare me some time on this. > > > > > Well, if you're prepared to spend a bit of money, I've heard very good things about Wingware, which is also available on Mac (Note, not a user myself currently, but has seen it before and been favourably impressed, enough to suggest it here despite not currently actively using it myself.) Link: http://wingware.com/ > > I'll second that. If you're really into IDEs, Wingware is a great one - they also have a student/open source license that may be right up your alley. > > My personal favorite? > > Two terminal windows - one with Vim, editing my Python scripts, and another with an interactive interpreter. Since you can map keys in Vim, I have mapped to save and run current file. If you're in the habit of editing multiple files you could set it up to map to ask which file you want to set as your main .py file. And since you mentioned debug, I usually just use pdb if I need debugging. You could easily map a key such as to insert a new line and type 'pdb.set_trace()'. Vim has a fairly steep learning curve, but if you spend 30 minutes with the vimtutor you'll be fine. With newer versions of Vim you can also write plugins for them in Python. > > Of course these capabilities (and many many more) are available with Emacs. > > I personally recommend that you learn one (or both) of these editors. They will highly improve the speed at which you are able to edit your code. > > HTH, > Wayne > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Oct 6 05:16:32 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 05 Oct 2011 23:16:32 -0400 Subject: [Tutor] String switch In-Reply-To: References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> Message-ID: <4E8D1D90.1030101@gmail.com> On 10/5/2011 5:51 PM, Christopher King wrote: > There is a program that will open another program, write code at the > top of the program. The code at the top will cause the program to > print all strings afterwards in swap case. Please provide a sample program that you wish to modify. -- Bob Gailer 919-636-4239 Chapel Hill NC From lina.lastname at gmail.com Thu Oct 6 05:46:48 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 6 Oct 2011 11:46:48 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> References: <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Thu, Oct 6, 2011 at 4:33 AM, Prasad, Ramit wrote: > >>yes, you're iterating over the keys of a dictionary. Since it only has > the key "E", that's what you get. Try printing dir(results) to see what > methods might return something other than the key. Make the language work > for you. > > >Sorry I am not smart. value? > > Dictionaries {} are containers for key/value based pairs like { key : > value, another_key : value(can be same or repeated) } > > For example: > {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]} > The keys here are 'B' and 'E'. The values here are [0, 0, 0, 0, 0, 0] (for > key 'B') and [2, 1, 4, 0, 1, 0] (for key 'E') > > You can get the value of a dictionary by doing: value = dictionary[key] > You can set the value of a dictionary by doing: dictionary[key] = value > > You will get an exception if you try to get a value for a key that is not > in the dictionary. > >>> dictionary = {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]} > >>> dictionary['F'] > KeyError: 'F' > I feel I started to understand what's the keys and values, but still confused in real practice. > > You can iterate over dictionaries in a couple ways > 1- > for key in dictionary: # also the same as > # for key in dictionary.keys() > value = dictionary[ key ] > def writeonefiledata(outname,results): outfile = open(outname,"w") for key in results: return outfile.write(results[key]) $ python3 counter-vertically-v2.py Traceback (most recent call last): File "counter-vertically-v2.py", line 43, in dofiles(".") File "counter-vertically-v2.py", line 12, in dofiles processfile(filename) File "counter-vertically-v2.py", line 29, in processfile writeonefiledata(base+OUTFILEEXT,results) File "counter-vertically-v2.py", line 39, in writeonefiledata return outfile.write(results[key]) TypeError: must be str, not list 2- > for key, value in dictionary.iteritems(): > < do something here with > > def writeonefiledata(outname,results): outfile = open(outname,"w") for key, value in results.iteritems(): return outfile.write(key) $ python3 counter-vertically-v2.py Traceback (most recent call last): File "counter-vertically-v2.py", line 43, in dofiles(".") File "counter-vertically-v2.py", line 12, in dofiles processfile(filename) File "counter-vertically-v2.py", line 29, in processfile writeonefiledata(base+OUTFILEEXT,results) File "counter-vertically-v2.py", line 38, in writeonefiledata for key, value in results.iteritems(): AttributeError: 'dict' object has no attribute 'iteritems' I don't know how to fix above problem. Thanks for your patience. > > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Oct 6 05:54:18 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 6 Oct 2011 11:54:18 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> Message-ID: On Thu, Oct 6, 2011 at 2:01 AM, Alan Gauld wrote: > On 05/10/11 13:46, lina wrote: > > another question, you know in linux, when use TAB, can automatically >> input something, >> so in python3, are there some way they can intelligent give some hints >> or fill the left. >> > > What development tool are you using? > Ha... I used gedit. > If you use IDLE, the standard IDE that comes with Python, you should find > that hitting tab (or pausing briefly) in a file editor will bring up a pick > list of options. > > Just tried the idle-python2.6, Q1: Is it bound with certain python version, such as for python3, do I need get idle-python3 ? Q2: how to use the last command I input, such as I typed something wrong and I wanna correct in the next step. seems no much difference with using terminal directly. I might be wrong here. Thanks, > Similarly typing a function name and an open paren will give a tooltip > for the functions parameters. > > IPython will do some similar things for you as a replacement for the > standard Python interpreter (plus a bunch of extras). > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From mnickey at gmail.com Thu Oct 6 07:09:57 2011 From: mnickey at gmail.com (Mike Nickey) Date: Wed, 5 Oct 2011 22:09:57 -0700 Subject: [Tutor] declaring a blank interger Message-ID: <29AA892A-55AC-47E0-BFFB-A5A6C4400BF6@gmail.com> Hey all, I'm sorry for such a silly question but I want to declare a blank integer for x. What I have is a base for a program that I'm working on for fun. Yes, for fun. The long term goal is to create a way to log items that are currently being done via pencil & paper and make this easier for me and my team. What I am running into though is how can I declare a variable to use that is blank at start but then gets populated later on. Here is what I have so far. Thanks in advance import string #Variable declarations UserName = string integer x def getUserName(): UserName = raw_input("Enter your name: ") return UserName def getUserNumber(x): x = input("Enter a number:") #This will be the users unique ID number return x getUserName() getUserNumber(x) print UserName, x Best, Mike Nickey mnickey at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Thu Oct 6 07:39:17 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 06 Oct 2011 07:39:17 +0200 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> Message-ID: On 2011-10-06 05:46, lina wrote: > On Thu, Oct 6, 2011 at 4:33 AM, Prasad, Ramitwrote: >> Dictionaries {} are containers for key/value based pairs like { key : >> value, another_key : value(can be same or repeated) } >> >> For example: >> {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]} >> The keys here are 'B' and 'E'. The values here are [0, 0, 0, 0, 0, 0] (for ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >> key 'B') and [2, 1, 4, 0, 1, 0] (for key 'E') > > def writeonefiledata(outname,results): > outfile = open(outname,"w") > for key in results: > return outfile.write(results[key]) > > $ python3 counter-vertically-v2.py > Traceback (most recent call last): > File "counter-vertically-v2.py", line 43, in > dofiles(".") > File "counter-vertically-v2.py", line 12, in dofiles > processfile(filename) > File "counter-vertically-v2.py", line 29, in processfile > writeonefiledata(base+OUTFILEEXT,results) > File "counter-vertically-v2.py", line 39, in writeonefiledata > return outfile.write(results[key]) > TypeError: must be str, not list ^^^^^^^^^^^^^^^^^^^^^ The error message tells you, that "results[key]" is a list but "write" just excepts a string. (see Ramit's explanation above). You have to convert the list values to a string. BTW: You shouldn't return the write operation because that will exit your function after the first iteration. > def writeonefiledata(outname,results): > outfile = open(outname,"w") > for key, value in results.iteritems(): > return outfile.write(key) > > $ python3 counter-vertically-v2.py > Traceback (most recent call last): > File "counter-vertically-v2.py", line 43, in > dofiles(".") > File "counter-vertically-v2.py", line 12, in dofiles > processfile(filename) > File "counter-vertically-v2.py", line 29, in processfile > writeonefiledata(base+OUTFILEEXT,results) > File "counter-vertically-v2.py", line 38, in writeonefiledata > for key, value in results.iteritems(): > AttributeError: 'dict' object has no attribute 'iteritems' In Python 3 there is no "dict.iteritems()" any more: http://docs.python.org/py3k/whatsnew/3.0.html#views-and-iterators-instead-of-lists Use "dict.items()" instead Bye, Andreas From andreas.perstinger at gmx.net Thu Oct 6 07:47:33 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 06 Oct 2011 07:47:33 +0200 Subject: [Tutor] vcf_files and strings In-Reply-To: References: Message-ID: On 2011-10-05 21:29, Anna Olofsson wrote: > vcf file: 2 rows, 10 columns. > > The important column is 7 where the ID is, i.e. > refseq.functionalClass=missense. It's a missense mutation, so then I > want to extract refseq.name=NM_003137492, or I want to extract only > the ID, which in this case is NM_003137492. > > Then I want to do exactly the same thing for all the other mutations, > but only for the missense mutations not the other ones. How do I > accomplish that? Where do I start? I would split the rows into the columns (analyze your file to find the seperator), then look for "missense" in the 7th column in every row and if found regex for the name/ID. Are you able to code that yourself or do you need more hints? Bye, Andreas From c2praveen30jun at gmail.com Thu Oct 6 09:15:00 2011 From: c2praveen30jun at gmail.com (Praveen Singh) Date: Thu, 6 Oct 2011 12:45:00 +0530 Subject: [Tutor] Help me in this programme In-Reply-To: References: Message-ID: this is one of the problem based on list which i found at pyschool. CountWords("google") [('e',1),('g',2),('l',1),('o',2)] by the level of this question you can easily understand i am new in python.the problem i am facing is how to make set of word and count(e,1) and add this to list?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Thu Oct 6 10:03:53 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 6 Oct 2011 10:03:53 +0200 Subject: [Tutor] declaring a blank interger In-Reply-To: <29AA892A-55AC-47E0-BFFB-A5A6C4400BF6@gmail.com> References: <29AA892A-55AC-47E0-BFFB-A5A6C4400BF6@gmail.com> Message-ID: On Thu, Oct 6, 2011 at 7:09 AM, Mike Nickey wrote: > Hey all, > I'm sorry for such a silly question but I want to declare a blank integer > for x. ?What I have is a base for a program that I'm working on for fun. > Yes, for fun. 1) no question is silly 2) Programming is fun, many people have it as a hobby! That's not weird at all. > The long term goal is to create a way to log items that are currently being > done via pencil & paper and make this easier for me and my team. > What I am running into though is how can I declare a variable to use that is > blank at start but then gets populated later on. > Here is what I have so far. > Thanks in advance The question you need to ask yourself is "why?" If the variable has no value, why would you declare it at all? Why not just wait until you have a value for it? It is common for languages such as C to declare all your variables beforehand, but in python there is really no need to do that. For one, variables in python don't have a type. Values do, but variables do not. So there is no need to tell python beforehand what types your variables will have. You can easily get rid of both of the variable declarations at the top of that program, and assign them when you have a value for them: def get_username(): return raw_input("Enter your name: ") def get_usernumber(): return raw_input("Enter a number: ") username = get_username() x = get_usernumber() Note that raw_input, as a function, returns a value of type str (that's a string). But for a number, it would make more sense to have a value with type int. So we should adapt our get_usernumber function to convert our str value into an int value: def get_usernumber(): return int(raw_input("Enter a number: ")) very simple, right? Now, the next problem you will run into, is what happens when the user doesn't actually enter a number? I suggest you try it. the int() function won't be very happy about it and raise an exception. You'll have to catch that exception, print out some error message, and ask for another number, until the user gets it right. But I'll leave that part up to you. HTH, Hugo From alan.gauld at btinternet.com Thu Oct 6 10:56:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Oct 2011 09:56:55 +0100 Subject: [Tutor] String switch In-Reply-To: References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> Message-ID: On 05/10/11 22:51, Christopher King wrote: > There is a program that will open another program, write code at the top > of the program. The code at the top will cause the program to print all > strings afterwards in swap case. If I understand this correctly you have mainprog.py and subprog.py. And you want mainprog.py to modify subprog.py such that when you run subprog.py it swaps case of the output? An easier way to achieve that would be to write a program that simply translates its input into a swapcased output. Then you can redirect the output of subprog.py into that program: python subprog.py | python swapcase.py Now, the fact that these are two python scripts rather than executables complicates things slightly so you probably need to experiment with the shell syntax to make it work, but that would be my approach. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Oct 6 11:01:52 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Oct 2011 10:01:52 +0100 Subject: [Tutor] Help me in this programme In-Reply-To: References: Message-ID: On 06/10/11 08:15, Praveen Singh wrote: > CountWords("google") > [('e',1),('g',2),('l',1),('o',2)] > > by the level of this question you can easily understand i am new in > python.the problem i am facing is how to make set of word and count(e,1) > and add this to list?? Some clues: a for loop will iterate over a string: for letter in "google": print letter A dictionary holds a value against a key. A key can be a letter. The corresponding value can be a number. Does that help? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Oct 6 11:18:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Oct 2011 10:18:17 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> Message-ID: On 06/10/11 04:54, lina wrote: > If you use IDLE, the standard IDE that comes with Python, you should > find that hitting tab (or pausing briefly) in a file editor will > bring up a pick list of options. > > Just tried the idle-python2.6, > Q1: Is it bound with certain python version, such as for python3, do I > need get idle-python3 ? Yes, you need IDLE for V3. IDLE is a python program itself so in theory you could run earlier versions but the version for V3 uses V3 syntax so you need to match the versions. If you are using Linux your package manager should have an IDLE v3 package available. > Q2: how to use the last command I input, such as I typed something wrong > and I wanna correct in the next step. Use Alt-p(previous) to go back through history Use Alt-n(next) to go forward. You can also cursor up to the command you want(or use the mouse) and hit return to bring it into the prompt. > seems no much difference with using terminal directly. I might be wrong > here. You get syntax colouring and auto indentation as well as the tool tips. There is a slight "bug" in the interactive window in that the alignment is off for some statements(*) but if typing code into a file it all works fine. (*) >>> if True: x = 42 else: y = 42 Notice the else is out of line with if because of the >>> Other features of IDLE are a graphical debugger that allows you to step through your code line by line, A syntax checker, a class browser(for when you get into objects). There is also a "code context" option but I have no idea what it does! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Thu Oct 6 12:04:07 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 6 Oct 2011 18:04:07 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> Message-ID: On Thu, Oct 6, 2011 at 5:18 PM, Alan Gauld wrote: > On 06/10/11 04:54, lina wrote: > > If you use IDLE, the standard IDE that comes with Python, you should >> find that hitting tab (or pausing briefly) in a file editor will >> bring up a pick list of options. >> >> Just tried the idle-python2.6, >> Q1: Is it bound with certain python version, such as for python3, do I >> need get idle-python3 ? >> > > Yes, you need IDLE for V3. > IDLE is a python program itself so in theory you could run earlier versions > but the version for V3 uses V3 syntax so you need to match the versions. If > you are using Linux your package manager should have an IDLE v3 package > available. > > > > Q2: how to use the last command I input, such as I typed something wrong >> and I wanna correct in the next step. >> > > Use Alt-p(previous) to go back through history > Use Alt-n(next) to go forward. > You can also cursor up to the command you want(or use the mouse) and hit > return to bring it into the prompt. Thanks, this is helpful. ^_^ > > > seems no much difference with using terminal directly. I might be wrong >> here. >> > > You get syntax colouring and auto indentation as well as the tool tips. > There is a slight "bug" in the interactive window in that the alignment is > off for some statements(*) but if typing code into a file it all works fine. > > > (*) > >>> if True: > x = 42 > else: > y = 42 > > > Notice the else is out of line with if because of the >>> > > > Other features of IDLE are a graphical debugger that allows you to step > through your code line by line, A syntax checker, a class browser(for when > you get into objects). There is also a "code context" option but I have no > idea what it does! Thanks for your time. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Oct 6 16:11:32 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 6 Oct 2011 22:11:32 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Thu, Oct 6, 2011 at 1:39 PM, Andreas Perstinger < andreas.perstinger at gmx.net> wrote: > On 2011-10-06 05:46, lina wrote: > >> On Thu, Oct 6, 2011 at 4:33 AM, Prasad, Ramit >> >wrote: >> >>> Dictionaries {} are containers for key/value based pairs like { key : >>> >>> value, another_key : value(can be same or repeated) } >>> >>> For example: >>> {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]} >>> The keys here are 'B' and 'E'. The values here are [0, 0, 0, 0, 0, 0] >>> (for >>> >> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^**^^^ > >> key 'B') and [2, 1, 4, 0, 1, 0] (for key 'E') >>> >> >> def writeonefiledata(outname,**results): >> outfile = open(outname,"w") >> for key in results: >> return outfile.write(results[key]) >> >> $ python3 counter-vertically-v2.py >> Traceback (most recent call last): >> File "counter-vertically-v2.py", line 43, in >> dofiles(".") >> File "counter-vertically-v2.py", line 12, in dofiles >> processfile(filename) >> File "counter-vertically-v2.py", line 29, in processfile >> writeonefiledata(base+**OUTFILEEXT,results) >> File "counter-vertically-v2.py", line 39, in writeonefiledata >> return outfile.write(results[key]) >> TypeError: must be str, not list >> > ^^^^^^^^^^^^^^^^^^^^^ > The error message tells you, that "results[key]" is a list but "write" just > excepts a string. (see Ramit's explanation above). > You have to convert the list values to a string. > I still don't know how to (standard) convert the list values to a string. def writeonefiledata(outname,results): outfile = open(outname,"w") for key, value in results.items(): print(value) outfile.write(str(results[key])) Is it a wrong way? Thanks all for the help. > BTW: You shouldn't return the write operation because that will exit your > function after the first iteration. > > > def writeonefiledata(outname,**results): >> outfile = open(outname,"w") >> for key, value in results.iteritems(): >> return outfile.write(key) >> >> $ python3 counter-vertically-v2.py >> Traceback (most recent call last): >> File "counter-vertically-v2.py", line 43, in >> dofiles(".") >> File "counter-vertically-v2.py", line 12, in dofiles >> processfile(filename) >> File "counter-vertically-v2.py", line 29, in processfile >> writeonefiledata(base+**OUTFILEEXT,results) >> File "counter-vertically-v2.py", line 38, in writeonefiledata >> for key, value in results.iteritems(): >> AttributeError: 'dict' object has no attribute 'iteritems' >> > > In Python 3 there is no "dict.iteritems()" any more: > http://docs.python.org/py3k/**whatsnew/3.0.html#views-and-** > iterators-instead-of-lists > Use "dict.items()" instead > > Bye, Andreas > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu Oct 6 16:48:33 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 6 Oct 2011 10:48:33 -0400 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> >I attached the two files. Although I will help you, I will not do the work for you. If you are still having errors, please include your script, python version, and the problem (if you are getting an error include the full error). Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From lina.lastname at gmail.com Thu Oct 6 17:05:08 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 6 Oct 2011 23:05:08 +0800 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Thu, Oct 6, 2011 at 10:48 PM, Prasad, Ramit wrote: > >I attached the two files. > > Although I will help you, I will not do the work for you. If you are still > having errors, please include your script, python version, and the problem > (if you are getting an error include the full error). > Thanks for your help. Actually this one was solved by a clumsy bash script long time ago, attached the clumsy script just to prove what I said is true. and at present I want to "push" myself on the way of using python. so I can actually learn something. For this one, the python programming I will come back later, just put it aside for a short while. #for i in 3 4 5 6 7 8 9 10 #2 #do # sed ' # /H01/ d # /H02/ d # /H03/ d # /H04/ d' < proAB_processed_$i.pdb > proAB_processed.pdb #awk '{ # if($4 == "CUR") # a[i++] = $0 #} #END{ # print a[6] # print a[7] # print a[8] # print a[9] # print a[5] # print a[13] # print a[33] # print a[34] # print a[12] # print a[2] # print a[11] # print a[1] # print a[10] # print a[14] # print a[15] # print a[16] # print a[17] # print a[18] # print a[19] # print a[20] # print a[21] # print a[22] # print a[23] # print a[24] # print a[4] # print a[28] # print a[0] # print a[27] # print a[3] # print a[26] # print a[31] # print a[32] # print a[25] # print a[29] # print a[30] #}' proAB_processed.pdb > try.pdb > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Oct 6 17:38:52 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 06 Oct 2011 11:38:52 -0400 Subject: [Tutor] String switch In-Reply-To: References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> Message-ID: <4E8DCB8C.6090301@gmail.com> On 10/5/2011 5:51 PM, Christopher King wrote: > There is a program that will open another program, write code at the > top of the program. The code at the top will cause the program to > print all strings afterwards in swap case. What you've told us so far may make total sense to you, but it is not enough information for us to act on. We need (at least) an example of a program that you want to modify. From that we /might /be able to tell what you mean by "print" and "all strings". I can hear you now "what's the matter with these guys - what part of print and strings do they not understand?". Humor us. It is not a lack of understanding. "print and strings" have(to me) multiple meanings. Currently we are guessing, as Alan has done, and we may be way off the mark. Guessing takes extra time and energy. Having said that I will offer an alternative guess: assuming you are using Python 3 and you are using the built-in print function to "print strings", then you could redefine print by ading (at the top) (untested): def print(something, **args): __builtins__.print(something.swapcase(), **args) You can't do this with Python 2, as print is a statement and can't be redefined. You could alter the program - find all occurrences of "print" used as a statement, and replace them with a function call. So print "asdf" would become swapprint("asdf") and at the top you'd add (untested): def swapprint(something): print something.swapcase() -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Oct 6 17:40:29 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 6 Oct 2011 23:40:29 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> References: <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Thu, Oct 6, 2011 at 4:33 AM, Prasad, Ramit wrote: > >>yes, you're iterating over the keys of a dictionary. Since it only has > the key "E", that's what you get. Try printing dir(results) to see what > methods might return something other than the key. Make the language work > for you. > > >Sorry I am not smart. value? > > Dictionaries {} are containers for key/value based pairs like { key : > value, another_key : value(can be same or repeated) } > > For example: > {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]} > The keys here are 'B' and 'E'. The values here are [0, 0, 0, 0, 0, 0] (for > key 'B') and [2, 1, 4, 0, 1, 0] (for key 'E') > > You can get the value of a dictionary by doing: value = dictionary[key] > You can set the value of a dictionary by doing: dictionary[key] = value > > You will get an exception if you try to get a value for a key that is not > in the dictionary. > >>> dictionary = {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]} > >>> dictionary['F'] > KeyError: 'F' > > You can iterate over dictionaries in a couple ways > 1- > for key in dictionary: # also the same as > # for key in dictionary.keys() > value = dictionary[ key ] > 2- > for key, value in dictionary.iteritems(): > < do something here with > > Now finally figure out what's the string, list and dictionary. May I ask a further question: >>> a {'B': [4, 5, 6], 'E': {1, 2, 3}} How can I get the value of set(a['E'])+set(a['B']) I mean, get a new dict 'B+E':[5,7,9] Thanks, > > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Thu Oct 6 18:13:06 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 06 Oct 2011 18:13:06 +0200 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> Message-ID: On 2011-10-06 16:11, lina wrote: > I still don't know how to (standard) convert the list values to a string. > > def writeonefiledata(outname,results): > outfile = open(outname,"w") > for key, value in results.items(): > print(value) > outfile.write(str(results[key])) > Is it a wrong way? There isn't really a wrong way because it's completely up to you how the list (or its elements) should be represented. As you will have noticed, "str(list)" just gives you the standard representation in Python (all list elements separated by a comma inside square brackets): >>> str([1, 2, 3, 4]) '[1, 2, 3, 4]' But I think you want something else because earlier you wrote: On 2011-10-04 18:38, lina wrote: > For file: > > aaEbb > aEEbb > EaEbb > EaEbE > > the expected output is > > 2 1 0 1 (Although I suppose, as Alan already noticed, that you've forgotten to mention the third column and the output should be: 2 1 4 0 1) So you have to build your own string. You could use the join method. It takes a list and concatenates the list elements to a string separated by the given string object: >>> "".join(["1", "2", "3"]) '123' >>> "-".join(["1", "2", "3"]) '1-2-3' The problem now is that "join" will only join the list elements if they are strings but in your case the list elements are integers. You have to convert them before you can concatenate them. In Python that's usually the job of a list comprehension but I'm not sure if you already know what that is. So for a start you can also use a for-loop: >>> l = [] >>> for number in [1, 2, 3]: ... l.append(str(number)) ... >>> l ["1", "2", "3"] You must also be aware that when you write your new strings into a file that "write" doesn't append a newline ("\n") to each string (in contrast to "print"). So you have to do it manually if you don't want to write just a long list of numbers. Bye, Andreas From ramit.prasad at jpmorgan.com Thu Oct 6 18:20:59 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 6 Oct 2011 12:20:59 -0400 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E90A2@EMARC112VS01.exchad.jpmchase.net> >attached the clumsy script just to prove what I said is true. and at present I want to "push" myself on the way of >using python. so I can actually learn something. I think you were close to the solution. It seemed like all you needed to do was write the output to file correctly (which you are learning in one of your other threads) >For this one, the python programming I will come back later, just put it aside for a short while. Just do not forget to come back to it. Coming back often gets forgotten ;) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From lina.lastname at gmail.com Thu Oct 6 18:21:16 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 00:21:16 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8BEE37.1050408@davea.name> References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> Message-ID: > > > As for splitting into functions, consider: > > #these two are capitalized because they're intended to be constant > TOKENS = "BE" > LINESTOSKIP = 43 > INFILEEXT = ".xpm" > OUTFILEEXT = ".txt" > > def dofiles(topdirectory): > for filename in os.listdr(topdirectory): > processfile(filename) > > def processfile(infilename): > base, ext =os.path.splitext(fileName) > if ext == INFILEEXT: > text = fetchonefiledata(infilename) > numcolumns = len(text[0]) > results = {} > for ch in TOKENS: > > results[ch] = [0] * numcolumns > for line in text: > line = line.strip() > > for col, ch in enumerate(line): > if ch in tokens: > results[ch][col] += 1 > I still have trouble understanding the results[ch][col] part. Thanks ahead, > writeonefiledata(base+**OUTFILEEXT, results) > > def fetchonefiledata(inname): > infile = open(inname) > text = infile.readlines() > return text[LINESTOSKIP:] > > def writeonefiledata(outname): > outfile = open(outname, "w") > ...process the results as appropriate... > ....(since you didn't tell us how multiple tokens were to be displayed) > > if __name__ == "__main__": > dofiles(".") #or get the top directory from the sys.argv variable, > which is set from command line. > > > > -- > > DaveA > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Fri Oct 7 00:11:37 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 6 Oct 2011 22:11:37 +0000 Subject: [Tutor] basic problem Message-ID: Hi all, can someone spell out to me in (simply if possible) what this programme is doing. i understand the concept of the "for" loop and what its doing with the message the user enters. i just cant understand the VOWELS and how it keeps adding 1 letter to the message. thanks for looking A # this programme will adding something to everything the user #types by using a for loop #set values new_message=" " VOWELS="AEIOU" message=raw_input ("Enter a message: ") for letter in message: if letter.lower() not in VOWELS: new_message = new_message+letter print new_message -------------- next part -------------- An HTML attachment was scrubbed... URL: From quasipedia at gmail.com Fri Oct 7 00:37:18 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 7 Oct 2011 00:37:18 +0200 Subject: [Tutor] basic problem In-Reply-To: References: Message-ID: <20111007003718.75d4fe03@jabbar> On Thu, 6 Oct 2011 22:11:37 +0000 ADRIAN KELLY wrote: > can someone spell out to me in (simply if possible) what this > programme is doing. i understand the concept of the "for" loop and > what its doing with the message the user enters. i just cant > understand the VOWELS and how it keeps adding 1 letter to the > message. thanks for looking A > > > # this programme will adding something to everything the user > #types by using a for loop This program might have been intended to to so, but it actually does not. Have you tried running it? > #set values > new_message=" " > VOWELS="AEIOU" This last line defines what vowels are. It defines it as a string, but keep in mind that strings in python can be both handled like individual object like in "print(text)" or like an ordered collection of letters, like in "for letter in message" (more on this in a moment). > message=raw_input ("Enter a message: ") > for letter in message: This is an example of the second way of handling strings (the proper name for what is going on here is "iteration"): the last line will instruct python to take one letter at a time, from left to right, from the message, and do with it whatever is indented here below. > if letter.lower() not in VOWELS: This is still an example of handling strings as ordered collections of letters: basically it says to check if any letter in "VOWELS" is the same as the letter being processed, in lower case. Actually this is also an example of pointless operation: VOWELS has been defined as "AEIOU" which are all capital letters. Since the comparison is done between a letter from the user input in lower case ("letter.lower()") the condition will always be True, so this line might well not be there. > new_message = new_message+letter The idea behind this line is that you keep adding the letter to the end of the message. The line works, but it's not an example of good python code. An improvement might be to use: new_message += letter which is more common and more readable. But in python one seldom does this kind of operation because strings are "immutable objects". In other words even if the logic behind is to "add a character" what is really going on behind the scenes is that the old version of "new_message" is destroyed, and a new one will take its place. While this is not a problem in this simple example, it is an expensive process, so often it is preferable to store the various "additions" in a list and merge them together only once, at the very end. The syntax is: ''.join(['a', 'b', 'c']) so in your program you would probably initialise an empty list first, and then append the letters at each loop: pool = [] for letter in message: pool.append(letter) print ''.join(pool) HTH! /mac From alan.gauld at btinternet.com Fri Oct 7 01:59:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Oct 2011 00:59:02 +0100 Subject: [Tutor] basic problem In-Reply-To: References: Message-ID: On 06/10/11 23:11, ADRIAN KELLY wrote: > can someone spell out to me in (simply if possible) what this programme > is doing. Mac has done that pretty well. However, let me add a couple of comments: > # this programme will adding something to everything the user > #types by using a for loop This comment does not describe what the program actually does. In fact the program simply echoes what the user types in. Well. Ok I suppose it adds a space at the front, but it goes about it in a very long winded way! > #set values > new_message=" " > VOWELS="AEIOU" > message=raw_input ("Enter a message: ") > for letter in message: > if letter.lower() not in VOWELS: > new_message = new_message+letter > print new_message In Python = is not a test or statement as it is in math. For that we use ==. A single = sign is an assignment. So x = 42 means that x takes on the value 42. x = 42 + 1 means x takes on the value 42+1, or 43 (Some other languages use another symbol for this which in my opinion is better, but sadly Python doesn't ) So new_message = new_message+letter means new_message becomes the old value of new_message plus the value of letter(which changes on each cycle through the for loop) This is such a common idiom that, as Mac said, Python provides a shorthand way of expressing it: new_message += letter HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Fri Oct 7 03:38:29 2011 From: d at davea.name (Dave Angel) Date: Thu, 06 Oct 2011 21:38:29 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> Message-ID: <4E8E5815.1000804@davea.name> On 10/06/2011 12:21 PM, lina wrote: > > >> >> As for splitting into functions, consider: >> >> #these two are capitalized because they're intended to be constant >> TOKENS = "BE" >> LINESTOSKIP = 43 >> INFILEEXT = ".xpm" >> OUTFILEEXT = ".txt" >> >> def dofiles(topdirectory): >> for filename in os.listdr(topdirectory): >> processfile(filename) >> >> def processfile(infilename): >> base, ext =os.path.splitext(fileName) >> if ext == INFILEEXT: >> text = fetchonefiledata(infilename) >> numcolumns = len(text[0]) >> results = {} >> for ch in TOKENS: >> >> results[ch] = [0] * numcolumns >> for line in text: >> line = line.strip() >> >> for col, ch in enumerate(line): >> if ch in tokens: >> results[ch][col] += 1 >> > I still have trouble understanding the results[ch][col] part. > > Thanks ahead, > > First ask yourself what results consists of. It's a dictionary, which is a aggregate of pairs of key/value items. In each case the key is a character, and the the value is a list of numbers. So results[ch] is a particular value, in other words a list. And results[ch] [col] is a particular item of the list, in other words, and integer If we use += 1 on that integer, we increment it by 1 Is that clear? if not, write a separate program to build such as structure, and try printing out each level of item print results["E"] should display a list print results["E"][0] should display an integer print results["E"][1] print results["E"][2] Does this help? -- DaveA From steve at pearwood.info Fri Oct 7 03:50:37 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 07 Oct 2011 12:50:37 +1100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E8E5AED.8050207@pearwood.info> lina wrote: > May I ask a further question: > >>>> a > {'B': [4, 5, 6], 'E': {1, 2, 3}} Why is a['B'] a list and a['E'] a set? > How can I get the value of > set(a['E'])+set(a['B']) > > I mean, get a new dict 'B+E':[5,7,9] You are confusing different things into one question, as if I had asked: "How do I make a hard boiled egg? I mean, get a potato salad." You must ask a clear question to get a clear answer. To answer your first question, what do you mean by adding two sets? I can take the *union* of two sets (anything in either one OR the other): >>> a['E'] | set(a['B']) # one is already a set, no need to convert {1, 2, 3, 4, 5, 6} or I can take the *intersection* of the two sets (anything in both one AND the other): >>> a['E'] & set(a['B']) set() There are no items in common between the two, so nothing in the intersection. To get the result you are asking for: [5, 7, 9] makes no sense. How do you expect to get a *list* by combining two *sets*? They are different things. Lists have order, sets do not: >>> [1, 2, 3] == [3, 2, 1] False >>> {1, 2, 3} == {3, 2, 1} True A list is a sequence of values in order, a set is like a jumble of values tossed in a bag. My *guess* is that you don't care about sets at all, you want two lists: [1, 2, 3] [4, 5, 6] and you want to add them item by item to get another list: [5, 7, 9] Have I guessed correctly? If so, here's the hard way to do it: first_list = [1, 2, 3] second_list = [4, 5, 6] result = [] for i in range(3): a = first_list[i] b = second_list[i] result.append(a + b) print(result) Walking along two lists in lock-step like that is so common that Python has a dedicated function specially for it: zip. result = [] for a,b in zip(first_list, second_list): result.append(a+b) which can be simplified further to a list comprehension: result = [a+b for a,b in zip(first_list, second_list)] -- Steven From mehgcap at gmail.com Fri Oct 7 04:15:39 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 6 Oct 2011 22:15:39 -0400 Subject: [Tutor] force imports from site-packages? Message-ID: Hi all, I have managed to get a couple of packages in site-packages which share names with some folders in the same directory as a program, or at least a subdir somewhere below has the same name. Is there a way to force my script to look in lib/site-packages before the script's folder? I can't rename these folders since Git will get confused if I do. In other words, I have a package called LRSignature installed, but in a subdir of my script's directory is another LRSignature folder which is not an actual Python package. Python sees this non-package folder first and so, quite rightly, throws an exception that the class of the package I want, LRSignature.Sign, does not exist. It exists in the site-packages copy, but Python won't overlook the nearer copy. How do I make it do this? Thanks. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Fri Oct 7 04:54:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 07 Oct 2011 13:54:48 +1100 Subject: [Tutor] force imports from site-packages? In-Reply-To: References: Message-ID: <4E8E69F8.6060307@pearwood.info> Alex Hall wrote: > Hi all, > I have managed to get a couple of packages in site-packages which > share names with some folders in the same directory as a program, or > at least a subdir somewhere below has the same name. Is there a way to > force my script to look in lib/site-packages before the script's > folder? I can't rename these folders since Git will get confused if I > do. > In other words, I have a package called LRSignature installed, but in > a subdir of my script's directory is another LRSignature folder which > is not an actual Python package. Python sees this non-package folder It shouldn't. Python doesn't look into nested folders unless you explicitly add them to the search path. Here's an example: [steve at sylar ~]$ mkdir math [steve at sylar ~]$ echo "print('spam')" > math/module.py [steve at sylar ~]$ python Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import math # Can we still see the standard math module? >>> math.sin(1) 0.8414709848078965 >>> import module # How about the other module? Traceback (most recent call last): File "", line 1, in ImportError: No module named module So as you can see, the math subdirectory and its content is ignored by Python because it isn't explicitly part of the search path. So I don't understand why you are seeing this problem unless you are cd'ing into the LRSignature folder first. > first and so, quite rightly, throws an exception that the class of the > package I want, LRSignature.Sign, does not exist. It exists in the > site-packages copy, but Python won't overlook the nearer copy. How do > I make it do this? Thanks. The *right* solution is to fix the name clash, which may or may not involve changing the name of something. But I can't tell what, since I don't understand why you are having this problem. But if you can't fix the problem, you can cover it up by manipulating the import search path. It is exposed as sys.path, and it is just a list of places to look in the specific order given. -- Steven From mehgcap at gmail.com Fri Oct 7 05:12:04 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 6 Oct 2011 23:12:04 -0400 Subject: [Tutor] force imports from site-packages? In-Reply-To: <4E8E69F8.6060307@pearwood.info> References: <4E8E69F8.6060307@pearwood.info> Message-ID: Thanks, it is now working properly. It turned out to be something in the __all__ list that didn'tmake much sense, but now that I know what to use it is working. On 10/6/11, Steven D'Aprano wrote: > Alex Hall wrote: >> Hi all, >> I have managed to get a couple of packages in site-packages which >> share names with some folders in the same directory as a program, or >> at least a subdir somewhere below has the same name. Is there a way to >> force my script to look in lib/site-packages before the script's >> folder? I can't rename these folders since Git will get confused if I >> do. >> In other words, I have a package called LRSignature installed, but in >> a subdir of my script's directory is another LRSignature folder which >> is not an actual Python package. Python sees this non-package folder > > It shouldn't. Python doesn't look into nested folders unless you > explicitly add them to the search path. Here's an example: > > > [steve at sylar ~]$ mkdir math > [steve at sylar ~]$ echo "print('spam')" > math/module.py > [steve at sylar ~]$ python > Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import math # Can we still see the standard math module? > >>> math.sin(1) > 0.8414709848078965 > >>> import module # How about the other module? > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named module > > > So as you can see, the math subdirectory and its content is ignored by > Python because it isn't explicitly part of the search path. So I don't > understand why you are seeing this problem unless you are cd'ing into > the LRSignature folder first. > > >> first and so, quite rightly, throws an exception that the class of the >> package I want, LRSignature.Sign, does not exist. It exists in the >> site-packages copy, but Python won't overlook the nearer copy. How do >> I make it do this? Thanks. > > > The *right* solution is to fix the name clash, which may or may not > involve changing the name of something. But I can't tell what, since I > don't understand why you are having this problem. > > But if you can't fix the problem, you can cover it up by manipulating > the import search path. It is exposed as sys.path, and it is just a list > of places to look in the specific order given. > > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From johan at accesstel.com.au Fri Oct 7 07:44:59 2011 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Fri, 7 Oct 2011 16:44:59 +1100 Subject: [Tutor] urllib2 sslerror Message-ID: <02da01cc84b4$4082dec0$c1889c40$@com.au> Hi everybody, Almost weekend, hang in there. I need some advice and hope somebody can help me. I have the follow piece of code that I use to get some data from a https webpage. ------------------------------------------------------- < some other stuff up here> try: return_object = urllib2.urlopen(theurl) html_content = return_object.read() now = time.strftime("%Y%m%d%H%M%S") img_file = "%s_%s.jpg"% (location, now) f = open(img_file, 'wb') f.write(html_content) f.close() file = img_file except Exception, e: print e ------------------------------------------------------- Sometimes I get the following error and I don't know why. It occurs very randomly and is hard or nearly impossible to reproduce (maybe there is somebody who knows how to create it). ------------------------------------------------------- Traceback (most recent call last): File "/var/ai-muse/jail/pkgdb/camimage/getimage.py", line 74, in run return_object = urllib2.urlopen(self.theurl) File "/usr/lib/python2.2/urllib2.py", line 138, in urlopen File "/usr/lib/python2.2/urllib2.py", line 322, in open File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain File "/usr/lib/python2.2/urllib2.py", line 792, in https_open File "/usr/lib/python2.2/urllib2.py", line 779, in do_open File "/usr/lib/python2.2/urllib2.py", line 342, in error File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain File "/usr/lib/python2.2/urllib2.py", line 611, in http_error_401 File "/usr/lib/python2.2/urllib2.py", line 590, in http_error_auth_reqed File "/usr/lib/python2.2/urllib2.py", line 600, in retry_http_basic_auth File "/usr/lib/python2.2/urllib2.py", line 322, in open File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain File "/usr/lib/python2.2/urllib2.py", line 792, in https_open File "/usr/lib/python2.2/urllib2.py", line 774, in do_open File "/usr/lib/python2.2/httplib.py", line 752, in getreply File "/usr/lib/python2.2/httplib.py", line 593, in getresponse File "/usr/lib/python2.2/httplib.py", line 99, in __init__ File "/usr/lib/python2.2/httplib.py", line 628, in makefile sslerror: (5, 'EOF occurred in violation of protocol') ------------------------------------------------------------ Any idea why it happens randomly and how I can check the cause? I read on a Google search page that one guy had the same issue and traced it back to some characters in the data he was receiving. Could that cause it? Thanks in advance ? Johan From lina.lastname at gmail.com Fri Oct 7 09:09:30 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 15:09:30 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8E5815.1000804@davea.name> References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8E5815.1000804@davea.name> Message-ID: On Fri, Oct 7, 2011 at 9:38 AM, Dave Angel wrote: > On 10/06/2011 12:21 PM, lina wrote: > >> >> >> >>> As for splitting into functions, consider: >>> >>> #these two are capitalized because they're intended to be constant >>> TOKENS = "BE" >>> LINESTOSKIP = 43 >>> INFILEEXT = ".xpm" >>> OUTFILEEXT = ".txt" >>> >>> def dofiles(topdirectory): >>> for filename in os.listdr(topdirectory): >>> processfile(filename) >>> >>> def processfile(infilename): >>> base, ext =os.path.splitext(fileName) >>> if ext == INFILEEXT: >>> text = fetchonefiledata(infilename) >>> numcolumns = len(text[0]) >>> results = {} >>> for ch in TOKENS: >>> >>> results[ch] = [0] * numcolumns >>> for line in text: >>> line = line.strip() >>> >>> for col, ch in enumerate(line): >>> if ch in tokens: >>> results[ch][col] += 1 >>> >>> I still have trouble understanding the results[ch][col] part. >> >> Thanks ahead, >> >> >> First ask yourself what results consists of. It's a dictionary, which is > a aggregate of pairs of key/value items. In each case the key is a > character, and the the value is a list of numbers. > > So results[ch] is a particular value, in other words a list. > > And results[ch] [col] is a particular item of the list, in other words, and > integer > > If we use += 1 on that integer, we increment it by 1 > > Is that clear? if not, write a separate program to build such as > structure, and try printing out each level of item > print results["E"] > should display a list > print results["E"][0] > should display an integer > print results["E"][1] > print results["E"][2] > Yes. I understand this part now. But how can I print a list consists of the value of key B + E. For {'B': [4, 5, 6], 'E': [1, 2, 3]} I wanna get the summary of B and E in each column, namely [5, 7, 9] > > > Does this help? > > -- > > DaveA > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Oct 7 09:39:30 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 15:39:30 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8E5AED.8050207@pearwood.info> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> Message-ID: On Fri, Oct 7, 2011 at 9:50 AM, Steven D'Aprano wrote: > lina wrote: > > May I ask a further question: >> >> a >>>>> >>>> {'B': [4, 5, 6], 'E': {1, 2, 3}} >> > > Why is a['B'] a list and a['E'] a set? > > > > > How can I get the value of >> set(a['E'])+set(a['B']) >> >> I mean, get a new dict 'B+E':[5,7,9] >> > > > You are confusing different things into one question, as if I had asked: > > "How do I make a hard boiled egg? I mean, get a potato salad." > > You must ask a clear question to get a clear answer. > > > > To answer your first question, what do you mean by adding two sets? I can > take the *union* of two sets (anything in either one OR the other): > > >>> a['E'] | set(a['B']) # one is already a set, no need to convert > {1, 2, 3, 4, 5, 6} > > > or I can take the *intersection* of the two sets (anything in both one AND > the other): > > >>> a['E'] & set(a['B']) > set() > > There are no items in common between the two, so nothing in the > intersection. > > > To get the result you are asking for: > > [5, 7, 9] > > makes no sense. How do you expect to get a *list* by combining two *sets*? > They are different things. Lists have order, sets do not: > > >>> [1, 2, 3] == [3, 2, 1] > False > >>> {1, 2, 3} == {3, 2, 1} > True > > > A list is a sequence of values in order, a set is like a jumble of values > tossed in a bag. > > My *guess* is that you don't care about sets at all, you want two lists: > Thanks, I did not realize the great differences between the list and sets. I was not so sensitive about the concepts before. > > > [1, 2, 3] > [4, 5, 6] > > > and you want to add them item by item to get another list: > > [5, 7, 9] > > > Have I guessed correctly? > > > If so, here's the hard way to do it: > > > first_list = [1, 2, 3] > second_list = [4, 5, 6] > result = [] > for i in range(3): > a = first_list[i] > b = second_list[i] > result.append(a + b) > > print(result) > > > Walking along two lists in lock-step like that is so common that Python has > a dedicated function specially for it: zip. > > result = [] > for a,b in zip(first_list, second_list): > result.append(a+b) > > > which can be simplified further to a list comprehension: > > result = [a+b for a,b in zip(first_list, second_list)] > > Thanks, just why the output it's something double, more than I want. #!/bin/python3 import os.path TOKENS="BE" LINESTOSKIP=0 INFILEEXT=".xpm" OUTFILEEXT=".txt" def dofiles(topdirectory): for filename in os.listdir(topdirectory): processfile(filename) def processfile(infilename): results={} base, ext =os.path.splitext(infilename) if ext == INFILEEXT: text = fetchonefiledata(infilename) numcolumns=len(text[0]) for ch in TOKENS: results[ch] = [0]*numcolumns for line in text: line = line.strip() for col, ch in enumerate(line): if ch in TOKENS: results[ch][col]+=1 for k,v in results.items(): print(results) summary=[] for a,b in zip(results['E'],results['B']): summary.append(a+b) writeonefiledata(base+OUTFILEEXT,summary) def fetchonefiledata(inname): infile = open(inname) text = infile.readlines() return text[LINESTOSKIP:] def writeonefiledata(outname,summary): outfile = open(outname,"w") for elem in summary: outfile.write(str(summary)) if __name__=="__main__": dofiles(".") $ python3 counter-vertically-v2.py {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} $ more try.txt [1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, 0][1, 0, 1 , 0, 1, 0][1, 0, 1, 0, 1, 0] $ more try.xpm aaEbb aEEbb EaEbb EaEbE Thanks, > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Oct 7 10:08:38 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 16:08:38 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> Message-ID: On Fri, Oct 7, 2011 at 3:39 PM, lina wrote: > > > On Fri, Oct 7, 2011 at 9:50 AM, Steven D'Aprano wrote: > >> lina wrote: >> >> May I ask a further question: >>> >>> a >>>>>> >>>>> {'B': [4, 5, 6], 'E': {1, 2, 3}} >>> >> >> Why is a['B'] a list and a['E'] a set? >> >> >> >> >> How can I get the value of >>> set(a['E'])+set(a['B']) >>> >>> I mean, get a new dict 'B+E':[5,7,9] >>> >> >> >> You are confusing different things into one question, as if I had asked: >> >> "How do I make a hard boiled egg? I mean, get a potato salad." >> >> You must ask a clear question to get a clear answer. >> >> >> >> To answer your first question, what do you mean by adding two sets? I can >> take the *union* of two sets (anything in either one OR the other): >> >> >>> a['E'] | set(a['B']) # one is already a set, no need to convert >> {1, 2, 3, 4, 5, 6} >> >> >> or I can take the *intersection* of the two sets (anything in both one AND >> the other): >> >> >>> a['E'] & set(a['B']) >> set() >> >> There are no items in common between the two, so nothing in the >> intersection. >> >> >> To get the result you are asking for: >> >> [5, 7, 9] >> >> makes no sense. How do you expect to get a *list* by combining two *sets*? >> They are different things. Lists have order, sets do not: >> >> >>> [1, 2, 3] == [3, 2, 1] >> False >> >>> {1, 2, 3} == {3, 2, 1} >> True >> >> >> A list is a sequence of values in order, a set is like a jumble of values >> tossed in a bag. >> >> My *guess* is that you don't care about sets at all, you want two lists: >> > > Thanks, I did not realize the great differences between the list and sets. > I was not so sensitive about the concepts before. > >> >> >> [1, 2, 3] >> [4, 5, 6] >> >> >> and you want to add them item by item to get another list: >> >> [5, 7, 9] >> >> >> Have I guessed correctly? >> >> >> If so, here's the hard way to do it: >> >> >> first_list = [1, 2, 3] >> second_list = [4, 5, 6] >> result = [] >> for i in range(3): >> a = first_list[i] >> b = second_list[i] >> result.append(a + b) >> >> print(result) >> >> >> Walking along two lists in lock-step like that is so common that Python >> has a dedicated function specially for it: zip. >> >> result = [] >> for a,b in zip(first_list, second_list): >> result.append(a+b) >> >> >> which can be simplified further to a list comprehension: >> >> result = [a+b for a,b in zip(first_list, second_list)] >> >> > Thanks, just why the output it's something double, more than I want. > > #!/bin/python3 > > import os.path > > TOKENS="BE" > > LINESTOSKIP=0 > INFILEEXT=".xpm" > OUTFILEEXT=".txt" > > def dofiles(topdirectory): > for filename in os.listdir(topdirectory): > processfile(filename) > > def processfile(infilename): > results={} > > base, ext =os.path.splitext(infilename) > if ext == INFILEEXT: > text = fetchonefiledata(infilename) > numcolumns=len(text[0]) > for ch in TOKENS: > results[ch] = [0]*numcolumns > for line in text: > line = line.strip() > for col, ch in enumerate(line): > if ch in TOKENS: > results[ch][col]+=1 > for k,v in results.items(): > print(results) > summary=[] > for a,b in zip(results['E'],results['B']): > summary.append(a+b) > writeonefiledata(base+OUTFILEEXT,summary) > > > def fetchonefiledata(inname): > infile = open(inname) > text = infile.readlines() > return text[LINESTOSKIP:] > > def writeonefiledata(outname,summary): > > outfile = open(outname,"w") > for elem in summary: > outfile.write(str(summary)) > > > > if __name__=="__main__": > dofiles(".") > > > $ python3 counter-vertically-v2.py > {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} > {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} > > $ more try.txt > [1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, 0][1, > 0, 1 > , 0, 1, 0][1, 0, 1, 0, 1, 0] > > $ more try.xpm > aaEbb > aEEbb > EaEbb > EaEbE > > Thanks, > I thought it might be some loop reason made it double output the results, so I made an adjustation in indent, now it showed: $ python3 counter-vertically-v2.py {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} [1, 0, 1, 0, 1, 0] Traceback (most recent call last): File "counter-vertically-v2.py", line 48, in dofiles(".") File "counter-vertically-v2.py", line 13, in dofiles processfile(filename) File "counter-vertically-v2.py", line 31, in processfile for a,b in zip(results['E'],results['B']): KeyError: 'E' still two results, but the summary is correct, with a KeyError which I don't know how to fix the key error here. #!/bin/python3 import os.path TOKENS="BE" LINESTOSKIP=0 INFILEEXT=".xpm" OUTFILEEXT=".txt" def dofiles(topdirectory): for filename in os.listdir(topdirectory): processfile(filename) def processfile(infilename): results={} base, ext =os.path.splitext(infilename) if ext == INFILEEXT: text = fetchonefiledata(infilename) numcolumns=len(text[0]) for ch in TOKENS: results[ch] = [0]*numcolumns for line in text: line = line.strip() for col, ch in enumerate(line): if ch in TOKENS: results[ch][col]+=1 for k,v in results.items(): print(results) summary=[] for a,b in zip(results['E'],results['B']): summary.append(a+b) print(summary) writeonefiledata(base+OUTFILEEXT,summary) def fetchonefiledata(inname): infile = open(inname) text = infile.readlines() return text[LINESTOSKIP:] def writeonefiledata(outname,summary): outfile = open(outname,"w") for elem in summary: outfile.write(str(summary)) if __name__=="__main__": dofiles(".") Thanks all for your time, > >> >> -- >> Steven >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > > -- > Best Regards, > > lina > > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Oct 7 12:06:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Oct 2011 11:06:11 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> Message-ID: On 07/10/11 09:08, lina wrote: > TOKENS="BE" > LINESTOSKIP=0 > INFILEEXT=".xpm" > OUTFILEEXT=".txt" > > def dofiles(topdirectory): > for filename in os.listdir(topdirectory): > processfile(filename) > > def processfile(infilename): > results={} > base, ext =os.path.splitext(infilename) > if ext == INFILEEXT: > text = fetchonefiledata(infilename) > numcolumns=len(text[0]) > for ch in TOKENS: > results[ch] = [0]*numcolumns > for line in text: > line = line.strip() > for col, ch in enumerate(line): > if ch in TOKENS: > results[ch][col]+=1 It would be easier to read(and debug) if you put that chunk into a function. Using the naming style below it could be called processOneFileData() for example... Make it return the results dictionary. > for k,v in results.items(): > print(results) This prints the same thing (results) for as many items are in results. I'm pretty sure you don't want that. Just printing results once should be sufficient. > summary=[] > for a,b in zip(results['E'],results['B']): > summary.append(a+b) I don't know why this gives a key error on 'E' (which basically means that there is no key 'E') since the code above should guarantee that it exists. Odd. I'm also not sure why the error occurs after it prints summary. Are you sure the output is in the sequence you showed in your message? > print(summary) > writeonefiledata(base+OUTFILEEXT,summary) > > def fetchonefiledata(inname): > infile = open(inname) > text = infile.readlines() > return text[LINESTOSKIP:] > > def writeonefiledata(outname,summary): > outfile = open(outname,"w") > for elem in summary: > outfile.write(str(summary)) > > > if __name__=="__main__": > dofiles(".") HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Fri Oct 7 12:21:33 2011 From: d at davea.name (Dave Angel) Date: Fri, 07 Oct 2011 06:21:33 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> Message-ID: <4E8ED2AD.9020004@davea.name> On 10/07/2011 04:08 AM, lina wrote: > > I thought it might be some loop reason made it double output the results, so > I made an adjustation in indent, now it showed: > $ python3 counter-vertically-v2.py > {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} > {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} > [1, 0, 1, 0, 1, 0] > Traceback (most recent call last): > File "counter-vertically-v2.py", line 48, in > dofiles(".") > File "counter-vertically-v2.py", line 13, in dofiles > processfile(filename) > File "counter-vertically-v2.py", line 31, in processfile > for a,b in zip(results['E'],results['B']): > KeyError: 'E' > > still two results, but the summary is correct, with a KeyError which I don't > know how to fix the key error here. > > #!/bin/python3 > > import os.path > > > TOKENS="BE" > LINESTOSKIP=0 > INFILEEXT=".xpm" > OUTFILEEXT=".txt" > > def dofiles(topdirectory): > for filename in os.listdir(topdirectory): > processfile(filename) > > def processfile(infilename): > results={} > base, ext =os.path.splitext(infilename) > if ext == INFILEEXT: > text = fetchonefiledata(infilename) > numcolumns=len(text[0]) > for ch in TOKENS: > results[ch] = [0]*numcolumns > for line in text: > line = line.strip() > for col, ch in enumerate(line): > if ch in TOKENS: > results[ch][col]+=1 > for k,v in results.items(): > print(results) That'll print the whole map for each item in it. Since you apparently have two items, "E" and "B", you get the whole thing printed out twice. I have no idea what you really wanted to print, but it probably was k and v > summary=[] > for a,b in zip(results['E'],results['B']): > summary.append(a+b) > print(summary) > writeonefiledata(base+OUTFILEEXT,summary) > > def fetchonefiledata(inname): > infile = open(inname) > text = infile.readlines() > return text[LINESTOSKIP:] > > def writeonefiledata(outname,summary): > outfile = open(outname,"w") > for elem in summary: > outfile.write(str(summary)) > > > if __name__=="__main__": > dofiles(".") > > Thanks all for your time, > > As for the reason you got the exception, it probably was because the NEXT file had no E's in it. One of the reasons to break this stuff into separate functions is so you can test them separately. You probably should be calling processfile() directly in your top-level code, till it all comes out correctly. Or at least add a print of the filename it's working on. Anyway, it's probably a mistake to ever reference "E" and "B" explicitly, but instead loop through the TOKENS. That way it'll still work when you add more or different tokens. Further, if it's considered valid for an input file not to have samples of all the tokens, then you have to loop through the ones you actually have. That might mean looping through the keys of results. Or, for the particular use case in that line, there's undoubtedly a method of results that will give you all the values in a list. That list would make an even better argument to zip(). Once again, I remind you of the dir() function, to see available methods. -- DaveA From d at davea.name Fri Oct 7 12:25:12 2011 From: d at davea.name (Dave Angel) Date: Fri, 07 Oct 2011 06:25:12 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> Message-ID: <4E8ED388.2040305@davea.name> On 10/07/2011 06:06 AM, Alan Gauld wrote: > On 07/10/11 09:08, lina wrote: > >> summary=[] >> for a,b in zip(results['E'],results['B']): >> summary.append(a+b) > > I don't know why this gives a key error on 'E' (which basically means > that there is no key 'E') since the code above should guarantee that > it exists. Odd. I'm also not sure why the error occurs after it prints > summary. Are you sure the output is in the sequence you showed in your > message? > One simple explanation: it continued on to the next file, which has neither "E" nor "B" in it. -- DaveA From lina.lastname at gmail.com Fri Oct 7 14:19:27 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 20:19:27 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8ED388.2040305@davea.name> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On Fri, Oct 7, 2011 at 6:25 PM, Dave Angel wrote: > On 10/07/2011 06:06 AM, Alan Gauld wrote: > >> On 07/10/11 09:08, lina wrote: >> >> >> summary=[] >>> for a,b in zip(results['E'],results['B'])**: >>> summary.append(a+b) >>> >> >> I don't know why this gives a key error on 'E' (which basically means that >> there is no key 'E') since the code above should guarantee that it exists. >> Odd. I'm also not sure why the error occurs after it prints summary. Are you >> sure the output is in the sequence you showed in your message? >> >> One simple explanation: it continued on to the next file, which has > neither "E" nor "B" in it. > > > > The final results got "6" summary out, which I only expect one. and how can I output the summary, in the wrong situation, let it \n ? $ more try.txt [1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, 0][1, 0, 1 , 0, 1, 0][1, 0, 1, 0, 1, 0] > -- > > DaveA > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Oct 7 14:21:01 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 20:21:01 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8ED388.2040305@davea.name> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On Fri, Oct 7, 2011 at 6:25 PM, Dave Angel wrote: > On 10/07/2011 06:06 AM, Alan Gauld wrote: > >> On 07/10/11 09:08, lina wrote: >> >> >> summary=[] >>> for a,b in zip(results['E'],results['B'])**: >>> summary.append(a+b) >>> >> >> I don't know why this gives a key error on 'E' (which basically means that >> there is no key 'E') since the code above should guarantee that it exists. >> Odd. I'm also not sure why the error occurs after it prints summary. Are you >> sure the output is in the sequence you showed in your message? >> >> One simple explanation: it continued on to the next file, which has > neither "E" nor "B" in it. > In this directory, I only kept one file. try.xpm $ more try.xpm aaEbb aEEbb EaEbb EaEbE $ ls counter-vertically-v2.py try.xpm counter-vertically.py try.txt > > > -- > > DaveA > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Oct 7 14:52:40 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 20:52:40 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: When I put it into a real case, it showed me all as 0 0 0 s The python code and the real one file can be accessed from below link: https://docs.google.com/leaf?id=0B93SVRfpVVg3MjQ0YzEzOWUtYWU0MC00YzAwLWJiYTctY2E5YTEzY2U0NGI3&hl=en_GB https://docs.google.com/leaf?id=0B93SVRfpVVg3MWMxZDg0MmItOTNiMi00NGZkLWEzMGEtZDU5NzI1YjRlZjU3&hl=en_GB Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Fri Oct 7 15:08:00 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Fri, 07 Oct 2011 15:08:00 +0200 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On 2011-10-07 14:21, lina wrote: >>> I don't know why this gives a key error on 'E' (which basically means that >>> there is no key 'E') since the code above should guarantee that it exists. >>> Odd. I'm also not sure why the error occurs after it prints summary. Are you >>> sure the output is in the sequence you showed in your message? >>> >>> One simple explanation: it continued on to the next file, which has >> neither "E" nor "B" in it. >> > In this directory, I only kept one file. try.xpm That's wrong. > $ more try.xpm > aaEbb > aEEbb > EaEbb > EaEbE > > $ ls > counter-vertically-v2.py try.xpm > counter-vertically.py try.txt As "ls" proves, you have *4* files in the directory. You start your script with "dofiles(".")". This function gets a list of *all* files in the directory in an *arbitrary* order and processes each of it. In your function "processfile" you first create an empty dictionary ("results = {}") and then you put values into the dictionary *only* for xpm-files ("if ext == INFILEEXT:"). *But* you print the summary for *every* file because the indentation at the end of the function is outside the if-branch where you check for the file extension. So for every file which isn't a xpm-file, "results" is an empty dictionary (see first line of the function) and therefore "zip(results['E'], results['B'])" will throw an exception. How to solve it? I personally would check for the file extension in the function "dofiles" and would only continue with xpm-files (in other words move the if-statement from "processfile" to "dofiles".) Bye, Andreas From lina.lastname at gmail.com Fri Oct 7 15:58:36 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 21:58:36 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On Fri, Oct 7, 2011 at 9:08 PM, Andreas Perstinger < andreas.perstinger at gmx.net> wrote: > On 2011-10-07 14:21, lina wrote: > >> I don't know why this gives a key error on 'E' (which basically means >>>> that >>>> there is no key 'E') since the code above should guarantee that it >>>> exists. >>>> Odd. I'm also not sure why the error occurs after it prints summary. >>>> Are you >>>> sure the output is in the sequence you showed in your message? >>>> >>>> One simple explanation: it continued on to the next file, which has >>>> >>> neither "E" nor "B" in it. >>> >>> In this directory, I only kept one file. try.xpm >> > > That's wrong. > > > $ more try.xpm >> aaEbb >> aEEbb >> EaEbb >> EaEbE >> >> $ ls >> counter-vertically-v2.py try.xpm >> counter-vertically.py try.txt >> > > As "ls" proves, you have *4* files in the directory. > > You start your script with "dofiles(".")". This function gets a list of > *all* files in the directory in an *arbitrary* order and processes each of > it. > > In your function "processfile" you first create an empty dictionary > ("results = {}") and then you put values into the dictionary *only* for > xpm-files ("if ext == INFILEEXT:"). *But* you print the summary for *every* > file because the indentation at the end of the function is outside the > if-branch where you check for the file extension. So for every file which > isn't a xpm-file, "results" is an empty dictionary (see first line of the > function) and therefore "zip(results['E'], results['B'])" will throw an > exception. > > How to solve it? I personally would check for the file extension in the > function "dofiles" and would only continue with xpm-files (in other words > move the if-statement from "processfile" to "dofiles".) > def processfile(infilename): results={} base, ext =os.path.splitext(infilename) if ext == INFILEEXT: text = fetchonefiledata(infilename) numcolumns=len(text[0]) for ch in TOKENS: results[ch] = [0]*numcolumns for line in text: line = line.strip() for col, ch in enumerate(line): if ch in TOKENS: results[ch][col]+=1 for k,v in results.items(): print(results) summary=[] for a,b in zip(results['E'],results['B']): summary.append(a+b) writeonefiledata(base+OUTFILEEXT,summary) else: os.sys.exit() This part has already given the indentation. if moved it a bit further, it would show more like: $ python3 counter-vertically-v2.py {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 0, 0, 0, 0]} {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 0, 0, 0, 0]} {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 0, 0, 0, 0]} {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 0, 0, 0, 0]} {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 0, 0]} {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 0, 0]} {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 0, 0]} {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 0, 0]} {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} Thanks again, > > Bye, Andreas > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Oct 7 16:18:29 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 22:18:29 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> Message-ID: On Fri, Oct 7, 2011 at 4:08 PM, lina wrote: > > > On Fri, Oct 7, 2011 at 3:39 PM, lina wrote: > >> >> >> On Fri, Oct 7, 2011 at 9:50 AM, Steven D'Aprano wrote: >> >>> lina wrote: >>> >>> May I ask a further question: >>>> >>>> a >>>>>>> >>>>>> {'B': [4, 5, 6], 'E': {1, 2, 3}} >>>> >>> >>> Why is a['B'] a list and a['E'] a set? >>> >>> >>> >>> >>> How can I get the value of >>>> set(a['E'])+set(a['B']) >>>> >>>> I mean, get a new dict 'B+E':[5,7,9] >>>> >>> >>> >>> You are confusing different things into one question, as if I had asked: >>> >>> "How do I make a hard boiled egg? I mean, get a potato salad." >>> >>> You must ask a clear question to get a clear answer. >>> >>> >>> >>> To answer your first question, what do you mean by adding two sets? I can >>> take the *union* of two sets (anything in either one OR the other): >>> >>> >>> a['E'] | set(a['B']) # one is already a set, no need to convert >>> {1, 2, 3, 4, 5, 6} >>> >>> >>> or I can take the *intersection* of the two sets (anything in both one >>> AND the other): >>> >>> >>> a['E'] & set(a['B']) >>> set() >>> >>> There are no items in common between the two, so nothing in the >>> intersection. >>> >>> >>> To get the result you are asking for: >>> >>> [5, 7, 9] >>> >>> makes no sense. How do you expect to get a *list* by combining two >>> *sets*? They are different things. Lists have order, sets do not: >>> >>> >>> [1, 2, 3] == [3, 2, 1] >>> False >>> >>> {1, 2, 3} == {3, 2, 1} >>> True >>> >>> >>> A list is a sequence of values in order, a set is like a jumble of values >>> tossed in a bag. >>> >>> My *guess* is that you don't care about sets at all, you want two lists: >>> >> >> Thanks, I did not realize the great differences between the list and sets. >> I was not so sensitive about the concepts before. >> >>> >>> >>> [1, 2, 3] >>> [4, 5, 6] >>> >>> >>> and you want to add them item by item to get another list: >>> >>> [5, 7, 9] >>> >>> >>> Have I guessed correctly? >>> >>> >>> If so, here's the hard way to do it: >>> >>> >>> first_list = [1, 2, 3] >>> second_list = [4, 5, 6] >>> result = [] >>> for i in range(3): >>> a = first_list[i] >>> b = second_list[i] >>> result.append(a + b) >>> >>> print(result) >>> >>> >>> Walking along two lists in lock-step like that is so common that Python >>> has a dedicated function specially for it: zip. >>> >>> result = [] >>> for a,b in zip(first_list, second_list): >>> result.append(a+b) >>> >>> >>> which can be simplified further to a list comprehension: >>> >>> result = [a+b for a,b in zip(first_list, second_list)] >>> >>> >> Thanks, just why the output it's something double, more than I want. >> >> #!/bin/python3 >> >> import os.path >> >> TOKENS="BE" >> >> LINESTOSKIP=0 >> INFILEEXT=".xpm" >> OUTFILEEXT=".txt" >> >> def dofiles(topdirectory): >> for filename in os.listdir(topdirectory): >> processfile(filename) >> >> def processfile(infilename): >> results={} >> >> base, ext =os.path.splitext(infilename) >> if ext == INFILEEXT: >> text = fetchonefiledata(infilename) >> numcolumns=len(text[0]) >> for ch in TOKENS: >> results[ch] = [0]*numcolumns >> for line in text: >> line = line.strip() >> for col, ch in enumerate(line): >> if ch in TOKENS: >> results[ch][col]+=1 >> for k,v in results.items(): >> > My mistake, here should remove the "for k,v in results.items()" > print(results) >> summary=[] >> for a,b in zip(results['E'],results['B']): >> summary.append(a+b) >> writeonefiledata(base+OUTFILEEXT,summary) >> >> >> def fetchonefiledata(inname): >> infile = open(inname) >> text = infile.readlines() >> return text[LINESTOSKIP:] >> >> def writeonefiledata(outname,summary): >> >> outfile = open(outname,"w") >> for elem in summary: >> > another mistake here, I shouldn't have used "for elem in summary" > outfile.write(str(summary)) >> >> >> >> if __name__=="__main__": >> dofiles(".") >> >> >> $ python3 counter-vertically-v2.py >> {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} >> {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} >> >> $ more try.txt >> [1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, 0][1, 0, 1, 0, 1, >> 0][1, 0, 1 >> , 0, 1, 0][1, 0, 1, 0, 1, 0] >> >> $ more try.xpm >> aaEbb >> aEEbb >> EaEbb >> EaEbE >> >> Thanks, >> > > I thought it might be some loop reason made it double output the results, > so I made an adjustation in indent, now it showed: > > $ python3 counter-vertically-v2.py > {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} > {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} > [1, 0, 1, 0, 1, 0] > Traceback (most recent call last): > File "counter-vertically-v2.py", line 48, in > dofiles(".") > File "counter-vertically-v2.py", line 13, in dofiles > processfile(filename) > File "counter-vertically-v2.py", line 31, in processfile > > for a,b in zip(results['E'],results['B']): > KeyError: 'E' > > still two results, but the summary is correct, with a KeyError which I > don't know how to fix the key error here. > > > Now fixed the excessive output. Thanks, but in another case, seems there is a problem, for the line actually is: "EEEEEEEEEEESEEEEEEEEEEEEEEEE~EEEEEEEEEEEE~EEEEEE~EEEEEEEEEE~EEEEEE~EEEEEEEEEEEE EEEEEEEEEEEEEEEEEEEEE~EEEEEEEEEEEEEEEEEEEEEEEE~EEE~EEEEEEEEEEEEEEEEEEEEEEEEEEEEE EEEEEEEEEEEEEEEEEEEEEE~EEEEEEEEEEEEEEEEEE~", not naked EEEor whatever. it's already in "" let me think think, and also welcome advice, actually debugging is enjoyment after the frustration. > #!/bin/python3 > > import os.path > > > TOKENS="BE" > LINESTOSKIP=0 > INFILEEXT=".xpm" > OUTFILEEXT=".txt" > > def dofiles(topdirectory): > for filename in os.listdir(topdirectory): > processfile(filename) > > def processfile(infilename): > results={} > base, ext =os.path.splitext(infilename) > if ext == INFILEEXT: > text = fetchonefiledata(infilename) > numcolumns=len(text[0]) > for ch in TOKENS: > results[ch] = [0]*numcolumns > for line in text: > line = line.strip() > for col, ch in enumerate(line): > if ch in TOKENS: > results[ch][col]+=1 > for k,v in results.items(): > print(results) > summary=[] > for a,b in zip(results['E'],results['B']): > summary.append(a+b) > print(summary) > writeonefiledata(base+OUTFILEEXT,summary) > > def fetchonefiledata(inname): > infile = open(inname) > text = infile.readlines() > return text[LINESTOSKIP:] > > def writeonefiledata(outname,summary): > outfile = open(outname,"w") > for elem in summary: > outfile.write(str(summary)) > > > if __name__=="__main__": > dofiles(".") > > Thanks all for your time, > > >> >>> >>> -- >>> Steven >>> >>> ______________________________**_________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/**mailman/listinfo/tutor >>> >> >> >> >> -- >> Best Regards, >> >> lina >> >> >> > > > -- > Best Regards, > > lina > > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Oct 7 16:41:06 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 22:41:06 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> Message-ID: > > Now fixed the excessive output. > > Thanks, > > but in another case, seems there is a problem, for the line actually is: > > "EEEEEEEEEEESEEEEEEEEEEEEEEEE~EEEEEEEEEEEE~EEEEEE~EEEEEEEEEE~EEEEEE~EEEEEEEEEEEE > > EEEEEEEEEEEEEEEEEEEEE~EEEEEEEEEEEEEEEEEEEEEEEE~EEE~EEEEEEEEEEEEEEEEEEEEEEEEEEEEE > EEEEEEEEEEEEEEEEEEEEEE~EEEEEEEEEEEEEEEEEE~", > > not naked EEEor whatever. it's already in "" > They treated " " as char, but I don't understand why the output is so many zeros ? and only zero for my case because each line ends up with , ? print(text) showed: SSST",\n', '"~~~~E Thanks for any hint, -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Oct 7 17:00:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Oct 2011 16:00:42 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8ED388.2040305@davea.name> References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.in fo> <4E8ED388.2040305@davea.name> Message-ID: On 07/10/11 11:25, Dave Angel wrote: >>> for a,b in zip(results['E'],results['B']): >>> summary.append(a+b) >> >> I don't know why this gives a key error on 'E' (which basically means >> that there is no key 'E') since the code above should guarantee that >> it exists. Odd. I'm also not sure why the error occurs after it prints >> summary. Are you sure the output is in the sequence you showed in your >> message? >> > One simple explanation: it continued on to the next file, which has > neither "E" nor "B" in it. But even then this bit of code should ensure that a list of zeros exists: def processfile(infilename): results={} base, ext =os.path.splitext(infilename) if ext == INFILEEXT: text = fetchonefiledata(infilename) numcolumns=len(text[0]) for ch in TOKENS: results[ch] = [0]*numcolumns Unless of course the second file doesn't have the right file extension! In that case it would jump to process the summary with no results data. for k,v in results.items(): print(results) summary=[] for a,b in zip(results['E'],results['B']): summary.append(a+b) Yep, that would do it! Lina, it looks like you need to either move the initialisation of results above the extension check, or else move the summary check inside the if block. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Oct 7 17:03:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Oct 2011 16:03:26 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On 07/10/11 13:21, lina wrote: > One simple explanation: it continued on to the next file, which has > neither "E" nor "B" in it. > > In this directory, I only kept one file. try.xpm > > $ more try.xpm > aaEbb > aEEbb > EaEbb > EaEbE > > $ ls > counter-vertically-v2.py try.xpm > counter-vertically.py try.txt That's 4 files. And your code will try to process all of them, including the Python scripts. I think that's a fundamental problem, you should use glob.glob() to ensure you only process the files you are interested in. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Fri Oct 7 17:22:38 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 23:22:38 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On Fri, Oct 7, 2011 at 11:03 PM, Alan Gauld wrote: > On 07/10/11 13:21, lina wrote: > > One simple explanation: it continued on to the next file, which has >> neither "E" nor "B" in it. >> >> In this directory, I only kept one file. try.xpm >> >> $ more try.xpm >> aaEbb >> aEEbb >> EaEbb >> EaEbE >> >> $ ls >> counter-vertically-v2.py try.xpm >> counter-vertically.py try.txt >> > > That's 4 files. > And your code will try to process all of them, including the Python > scripts. > #!/usr/bin/python3 import os.path import glob TOKENS="BE" LINESTOSKIP=0 INFILEEXT=".xpm" OUTFILEEXT=".txt" if __name__=="__main__": for fileName in glob.glob('*.xpm'): base, ext =os.path.splitext(fileName) text=open(fileName).readlines() text=text[LINESTOSKIP:] numcolumns=len(text[0]) results={} for ch in TOKENS: results[ch] = [0]*numcolumns for line in text: line = line.strip() for col, ch in enumerate(line): if ch in TOKENS: results[ch][col]+=1 print(results) summary=[] for a,b in zip(results['E'],results['B']): summary.append(a+b) print(summary) open(base+OUTFILEEXT,"w").write(str(summary)) $ more try.xpm aaEbb aEEbb EaEbb EaEbE $ python3 counter-vertically-v4.py {'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]} [1, 0, 1, 0, 1, 0] Huge unexpected problems, it's only output 1 or 0, the summary results is not correct. > > I think that's a fundamental problem, you should use glob.glob() to ensure > you only process the files you are interested in. > > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Oct 7 17:40:01 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 7 Oct 2011 23:40:01 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: what does the for col, ch in enumerate(line): enumerate(line) mean, I used idle3 test enumerate, it always showed me: >>> a 'abcde' >>> enumerate(a) I don't have a deep understanding. Thanks all of you, for your kindness of giving advice and your patience in explaination. also another question, sometimes in my life, I made lots of blind choice, today I was kinda of happy telling a friend that I feel I finally started on the road of learning or potentially using python in future. As I mentioned before, I really did learn it on and off, study one week and then give up, never give it a deep understanding. but today I was also discouraged, I was told that you should not have learned python, you should focus on C or bash, or D, cause python is going to be obsolete, and I defensed that I saw lots people/apps using python, and it's always good to learn a language well, it's helpful for you to understand another language. I was further told that fortran is obsolete, but still lots of fortran guys using it. I don't know much, since I started and wanted to learn, actually I wish to hear some encouraging words, not some words discouraging, but on another hands, it's always good to have an open mind, so I want to hear your opinion and perspective, I am not knowledgable about this. Thanks again for all your time and guide, Best regards, -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Oct 7 18:35:07 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 00:35:07 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: #!/usr/bin/python3 import os.path import glob TOKENS="BE" LINESTOSKIP=0 INFILEEXT=".xpm" OUTFILEEXT=".txt" if __name__=="__main__": for fileName in glob.glob('*.xpm'): base, ext =os.path.splitext(fileName) text=open(fileName).readlines() text=text[LINESTOSKIP:] numcolumns=len(text[0]) results={} for ch in TOKENS: results[ch] = [0]*numcolumns for line in text: line = line.strip() for col, ch in enumerate(line): if ch in TOKENS: results[ch][col]+=1 summary=[] for a,b in zip(results['E'],results['B']): summary.append(a+b) print(summary) open(base+OUTFILEEXT,"w").write(str(summary)) I test it, it finally works. (I was not so sensitive about indentation also) If you have time or interest, hope to help polish the code, and warmly welcome to make above one a bit sophisticated. better not easy-readable for me at first sight. Thanks again, -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Oct 7 18:39:49 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 7 Oct 2011 12:39:49 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21444181@EMARC112VS01.exchad.jpmchase.net> > open(base+OUTFILEEXT,"w").write(str(summary)) Unless Python3 is different with respect to files, I would really change this to explicitly close the file. In general, I think explicitly closing resources (database connections, files, etc) are a Good Thing. with open(base+OUTFILEEXT,"w") as f: f.write(str(summary)) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Fri Oct 7 18:33:53 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 7 Oct 2011 12:33:53 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21444160@EMARC112VS01.exchad.jpmchase.net> >what does the > > for col, ch in enumerate(line): > I highly recommend looking at web documentation when you can. It is not that I have any problems answering any questions, but I know I get frustrated when I am forced to learn things in 5 minute increments while waiting on people to respond. Reading the documentation will give a better idea of Python because there is *so* much more information there and the Python docs are actually quite well written. Please read the following link and then ask us about any questions you have. http://docs.python.org/dev/library/functions.html#enumerate >but today I was also discouraged, I was told that you should not have learned python, you should focus on C or bash, or D, cause python is going to be obsolete, and I defensed that I saw lots people/apps using python, and it's always good to learn a language well, it's helpful for you to understand another language. I was further told that fortran is obsolete, but still lots of fortran guys using it. >I don't know much, since I started and wanted to learn, actually I wish to hear some encouraging words, not some words discouraging, but on another hands, it's always good to have an open mind, so I want to hear your opinion and >perspective, I am not knowledgable about this. Language choice is an often debated subject. People are always proclaiming that a certain language is the "best" and this list probably considers Python the "best". The truth is there is no "best" language! The "best" language (in my not-so-humble opinion) is the language that allows you to effectively, quickly, and easily solve a specific problem. Use the best tool (i.e. language) for the problem; just because you know how to use a hammer does not mean that you should use it for cooking! :) As for encouraging words, well...that is not really something I am good at. When you get stuck or bogged down in frustration, remember that learning occurs most often by making mistakes first and then learning to avoid those mistakes. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From lina.lastname at gmail.com Fri Oct 7 19:50:30 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 01:50:30 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21444160@EMARC112VS01.exchad.jpmchase.net> References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21444160@EMARC112VS01.exchad.jpmchase.net> Message-ID: <28449370-10E2-4EEF-89AA-BE98D6CDD2DB@gmail.com> On Oct 8, 2011, at 0:33, "Prasad, Ramit" wrote: >> what does the >> >> for col, ch in enumerate(line): >> > > I highly recommend looking at web documentation when you can. It is not that I have any problems answering any questions, but I know I get frustrated when I am forced to learn things in 5 minute increments while waiting on people to respond. Reading the documentation will give a better idea of Python because there is *so* much more information there and the Python docs are actually quite well written. > > Please read the following link and then ask us about any questions you have. http://docs.python.org/dev/library/functions.html#enumerate > Actually before I asked the question. I did some basic check before. here is another way/channel of looking for answers. Later I also checked online. And learned what the enumerate mean, But at that time, when I asked on list, I did really don't understand. Sometimes the question I asked here is also the question I asked to myself. But thanks for your suggestion. When I saw soneone asked some very simple question on another list which I know that staff long. I also felt that way and wanna suggest them to google or use manual. > > >> but today I was also discouraged, I was told that you should not have learned python, you should focus on C or bash, or D, cause python is going to be obsolete, and I defensed that I saw lots people/apps using python, and it's always good to learn a language well, it's helpful for you to understand another language. I was further told that fortran is obsolete, but still lots of fortran guys using it. >> I don't know much, since I started and wanted to learn, actually I wish to hear some encouraging words, not some words discouraging, but on another hands, it's always good to have an open mind, so I want to hear your opinion and >perspective, I am not knowledgable about this. > > Language choice is an often debated subject. People are always proclaiming that a certain language is the "best" and this list probably considers Python the "best". The truth is there is no "best" language! The "best" language (in my not-so-humble opinion) is the language that allows you to effectively, quickly, and easily solve a specific problem. Use the best tool (i.e. language) for the problem; just because you know how to use a hammer does not mean that you should use it for cooking! :) ^_^ good point. > > As for encouraging words, well...that is not really something I am good at. When you get stuck or bogged down in frustration, remember that learning occurs most often by making mistakes first and then learning to avoid those mistakes. Thanks. > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From lina.lastname at gmail.com Fri Oct 7 19:56:13 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 01:56:13 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21444181@EMARC112VS01.exchad.jpmchase.net> References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21444181@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Oct 8, 2011, at 0:39, "Prasad, Ramit" wrote: >> open(base+OUTFILEEXT,"w").write(str(summary)) > Unless Python3 is different with respect to files, I would really change this to explicitly close the file. In general, I think explicitly closing resources (database connections, files, etc) are a Good Thing. > > with open(base+OUTFILEEXT,"w") as f: > f.write(str(summary)) > Btw, I do notice lots of suggestions of closing file. Does your above sentence close the file here? Implicitly ? Sorry, I don't see "close" And how do I know it's safely closed already? I will check further later. Now reading email on phone. Thanks with best regards, > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From wtfwhoami at gmail.com Fri Oct 7 20:19:07 2011 From: wtfwhoami at gmail.com (Guess?!?) Date: Fri, 7 Oct 2011 11:19:07 -0700 Subject: [Tutor] Runtime error while Test data creation Message-ID: Hello all, I am trying to create some test data for a search module that I am building. Since I dont want to hit performance related issues late in the game, I decided to create half a million records in the DB. My approach is create a csv file with valid UUIDs which I already have. Read each record from csv and generate random data and do DB insert as long the csv file has records in them. This crashes near 100000 record insertions. The problem is that my program eventually fails with this error. Any ideas what I can improve to make it go all the way? Runtime Error! Program: C:\Python27\pythonw.exe This app has requested the Runtime to terminate it in an unusual way. Please contact application support team Here is the code that I wrote to do this. ======================================================================= import pyodbc, random, datetime, uuid #INT conn = pyodbc.connect('DRIVER={SQL Server};SERVER=SERVERNAME\INT_FOUNDATIONS;DATABASE=membership_service;UID=int_usr;PWD=blah') c = conn.cursor() # "enterprise_person_id" TEXT NOT NULL, # read file f = open('C:\\Users\\garora\\Desktop\\INTPPLHALFMIL.csv','r') # Hardcoded valid seed values # INT programId = 50801 packageId = 46101 pkg_optionId = 40301 seed_data = "TEST_DATA" numberPrePend = "AAAA-" create_dt = datetime.datetime.now(); modified_dt = datetime.datetime.now(); i = 0 for each in f: if (i == 0): i = i + 1 continue; (id, entrpid,) = each.split(',') print id id = id.replace('\n', '') print id id = uuid.UUID(id) #enterprise_person_id print entrpid entrpid = entrpid.replace('\n', '') print entrpid entrpid = uuid.UUID(entrpid) #random values for few columns statusRandom = random.randint(1,4) sourceRandom = random.randint(1,7) inputChannelRandom = random.randint(1,5) marketRandom= random.randint(1,10) trialRandom = random.randint(0,1) monthRandom = random.randint(3,12) # prevent month of feb dateRandom = random.randint(1,30) # prevent 31st on invalid month yearRandom = random.randint(2007,2010) member_start_dt = datetime.datetime(yearRandom, monthRandom, dateRandom,0,0,0) current_term_start_dt = datetime.datetime(yearRandom, monthRandom, dateRandom,0,0,0) print "id: " + str(i) print " programId: " + str(programId) print " packageId: " + str(packageId) print " pkgoptionId: " + str(pkg_optionId) print " status id: " + str(statusRandom) print " source id: " + str(sourceRandom) print " input channel id: " + str(inputChannelRandom) print " market id: " + str(marketRandom) print " person id: " + str(id) print "membership id: " + numberPrePend + str(i) print " member_start_dt " + str(member_start_dt) print " current_term_start_dt " + str(current_term_start_dt) print " started_as_trial " + str(trialRandom) print " enterprise_person_id " + str(entrpid) record = (i, programId, packageId, pkg_optionId, statusRandom, sourceRandom, inputChannelRandom, marketRandom, str(id), numberPrePend + str(i), member_start_dt, current_term_start_dt, trialRandom ,seed_data, seed_data, create_dt, modified_dt, str(entrpid)) print record c.execute("""insert into Members(id, membership_program_id, membership_package_id, membership_pkg_option_id, membership_status_id, membership_source_id, src_input_channel_id, src_market_id, person_id_ref, membership_id, member_start_dt, current_term_start_dt, started_as_trial, created_by, modified_by, create_dt, modified_dt, enterprise_person_id) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", record) conn.commit() i = i + 1 c.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From rmntcverses at aol.com Fri Oct 7 18:32:13 2011 From: rmntcverses at aol.com (rmntcverses at aol.com) Date: Fri, 7 Oct 2011 12:32:13 -0400 (EDT) Subject: [Tutor] Help! Message-ID: <8CE5325CD7B62C2-958-35B86@webmail-m005.sysops.aol.com> I need serious help with this Rock, Paper, Scissors program. The program runs smoothly but I can't get the score to print. Please help me with this one aspect! Here is my code right now: import random def computerrockPaperScissors(): selection = random.randint(0, 2) if selection == 0: y = 'r' if selection == 1: y = 's' if selection == 2: y = 'p' return y def humanrockPaperScissors(): x = input("Make your selection: r (rock), p (paper), s (scissors), q (quit)") return x humanWins= 0 computerWins= 0 ties= 0 def compareSelection(x, y): if x == 'r' and y == 'r': print("You picked rock, I picked rock. We tied!") ties+= 1 elif x == 'r' and y == 's': print("You picked rock, I picked scissors. You won!") humanWins+= 1 elif x == 'r' and y == 'p': print("You picked rock, I picked paper. I won!") computerWins+= 1 elif x == 's' and y == 's': print("You picked scissors, I picked scissors. We tied!") ties+= 1 elif x == 's' and y == 'r': print("You picked scissors, I picked rock. I won!") computerWins+= 1 elif x == 's' and y == 'p': print("You picked scissors, I picked paper. You won!") humanWins+= 1 elif x == 'p' and y == 'p': print("You picked paper, I picked paper. We tied!") ties+= 1 elif x == 'p' and y == 's': print("You picked paper, I picked scissors. I won!") computerWins+= 1 elif x == 'p' and y == 'r': print("You picked paper, I picked rock. You won!") humanWins+= 1 elif x == 'q': print("Game over.") print(humanWins, computerWins, ties) def rockPaperScissors(): print("Let's play Rock Paper Scissors. Rock beats scissors, scissors beats paper and paper beats rock.") for i in range(999): computerSelection = computerrockPaperScissors() humanSelection = humanrockPaperScissors() result = compareSelection(humanSelection, computerSelection) -------------- next part -------------- An HTML attachment was scrubbed... URL: From olofsson_anna585 at hotmail.com Fri Oct 7 18:12:21 2011 From: olofsson_anna585 at hotmail.com (Anna Olofsson) Date: Fri, 7 Oct 2011 18:12:21 +0200 Subject: [Tutor] vcf_files and strings In-Reply-To: References: Message-ID: Hi, I'm a beginner at Python and would really appreciate some help in how to extract information from a vcf file. The attached file consists of a lot of information on mutations, this one though is just 2 rows and 10 columns (the real one has a lot more rows). I want to extract the mRNA ID only if the mutation is missense. These two rows (mutations) that I have attached happens to be missense but how do I say that I'm not interested in the mutations that's not missense (they might be e.g. synonymous). Also, how do I say that if a mutation starts with a # symbol I don't want to include it (sometimes the chr starts with a hash). vcf file: 2 rows, 10 columns. col 0 col 1 col 2 col 3 col 4 col5 col6 col7 col8 col9 chromosome position . Reference ALT position . some statistics and the ID:s not important not important The important column is 7 where the ID is, i.e. refseq.functionalClass=missense. It's a missense mutation, so then I want to extract refseq.name=NM_003137492, or I want to extract only the ID, which in this case is NM_003137492. Then I want to do exactly the same thing for all the other mutations, but only for the missense mutations not the other ones. How do I accomplish that? Where do I start? Best, Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: vcf_file.vcf Type: text/directory Size: 1368 bytes Desc: not available URL: From mehgcap at gmail.com Fri Oct 7 20:37:11 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 7 Oct 2011 14:37:11 -0400 Subject: [Tutor] Help! In-Reply-To: <8CE5325CD7B62C2-958-35B86@webmail-m005.sysops.aol.com> References: <8CE5325CD7B62C2-958-35B86@webmail-m005.sysops.aol.com> Message-ID: On 10/7/11, rmntcverses at aol.com wrote: > I need serious help with this Rock, Paper, Scissors program. The program > runs smoothly but I can't get the score to print. Please help me with this > one aspect! Here is my code right now: > > > > import random > > > def computerrockPaperScissors(): > selection = random.randint(0, 2) > if selection == 0: > y = 'r' > if selection == 1: > y = 's' > if selection == 2: > y = 'p' > return y > > > def humanrockPaperScissors(): > x = input("Make your selection: r (rock), p (paper), s (scissors), q > (quit)") > return x > > > humanWins= 0 > computerWins= 0 > ties= 0 > > > def compareSelection(x, y): > if x == 'r' and y == 'r': > print("You picked rock, I picked rock. We tied!") > ties+= 1 > elif x == 'r' and y == 's': > print("You picked rock, I picked scissors. You won!") > humanWins+= 1 > elif x == 'r' and y == 'p': > print("You picked rock, I picked paper. I won!") > computerWins+= 1 > elif x == 's' and y == 's': > print("You picked scissors, I picked scissors. We tied!") > ties+= 1 > elif x == 's' and y == 'r': > print("You picked scissors, I picked rock. I won!") > computerWins+= 1 > elif x == 's' and y == 'p': > print("You picked scissors, I picked paper. You won!") > humanWins+= 1 > elif x == 'p' and y == 'p': > print("You picked paper, I picked paper. We tied!") > ties+= 1 > elif x == 'p' and y == 's': > print("You picked paper, I picked scissors. I won!") > computerWins+= 1 > elif x == 'p' and y == 'r': > print("You picked paper, I picked rock. You won!") > humanWins+= 1 > elif x == 'q': > print("Game over.") > print(humanWins, computerWins, ties) This only prints when the user enters 'q', not when the below for loop ends. > > > def rockPaperScissors(): > print("Let's play Rock Paper Scissors. Rock beats scissors, scissors > beats paper and paper beats rock.") > for i in range(999): > computerSelection = computerrockPaperScissors() > humanSelection = humanrockPaperScissors() > result = compareSelection(humanSelection, computerSelection) Now, after the loop, print the win statistics since they will only print once the loop exits. If you do that, and the user hits q, the stats will print twice. I would change your for loop to: while 1: ... #your code if humanSelection=='q': break printStats() #print win/loss numbers, you must make that function if you want This way, the player can go as many times as they want, even over 1000, and the stats will always print. > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From alan.gauld at btinternet.com Fri Oct 7 20:55:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Oct 2011 19:55:05 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On 07/10/11 16:40, lina wrote: > but today I was also discouraged, I was told that you should not have > learned python, you should focus on C or bash, or D, cause python is > going to be obsolete, C is a great language for writing Operating Systems and other "near the metal" code. But its not the best language for busiess apps, artificial intelligence and a host of other things. Bash is a good user shell, but its not even the best Unix shell for scripting (Thats probably ksh). D? Who actually uses D? I think your informant was not well informed. AS fopr Python becoming obsolete? Maybe someday, but not soon. And even if it does the principles it teaches are alive and well in many other languages - eg, Ruby, Lua both openly borrow from Python. Just as Python borrows from Lisp and Haskell and Smalltalk and Perl. > I was further told that fortran is obsolete, but still lots of > fortran guys using it. Absolutely and Lisp and COBOL ghave both been predicted to die for decades but are still marching on. It is very difficult to kill a popular language because the thing that made it popular keeps it alive. Ignore rumours and focus on programming. Don't worry about languages, once you know one you'll usually pick up another very quickly. They come and go in fashion but the concepts remain constant. Most programmers work in multiple languages, often even in a single project. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Oct 7 21:00:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Oct 2011 20:00:02 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21444181@EMARC112VS01.exchad.jpmchase.net> Message-ID: On 07/10/11 18:56, lina wrote: > On Oct 8, 2011, at 0:39, "Prasad, Ramit" wrote: > I would really change this to explicitly close the file. >> >> with open(base+OUTFILEEXT,"w") as f: >> f.write(str(summary)) >> > Btw, I do notice lots of suggestions of closing file. > Does your above sentence close the file here? Implicitly ? > Sorry, I don't see "close" The 'with' syntax above implicitly closes the file for you at the end of the block. If you use the f = open(...) style you are expected to explicitly close the file when you are finished with it. This is especially important when writing to a file because that will guarantee that the OS writes the data to the file on disk. Without a close its possible for your data to get held in a buffer that doesn't get written to disk. Rare, but possible. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ilhs_hs at yahoo.com Fri Oct 7 22:17:07 2011 From: ilhs_hs at yahoo.com (Hs Hs) Date: Fri, 7 Oct 2011 13:17:07 -0700 (PDT) Subject: [Tutor] vcf_files and strings In-Reply-To: References: Message-ID: <1318018627.43378.YahooMailNeo@web111215.mail.gq1.yahoo.com> if col[x] == 'missense': ??? print col[withRefSeqID] hth ________________________________ From: Anna Olofsson To: tutor at python.org Sent: Friday, October 7, 2011 12:12 PM Subject: [Tutor] vcf_files and strings Hi, I'm a beginner at Python and would really appreciate some help in how to extract information from a vcf file. The attached file consists of a lot of information on mutations, this one though is just 2 rows and 10 columns (the real one has a lot more rows). I want to extract the mRNA ID only if the mutation is missense. These two rows (mutations) that I have attached happens to be missense but how do I say that I'm not interested in the mutations that's not missense (they might be e.g. synonymous). Also, how do I say that if a mutation starts with a # symbol I don't want to include it (sometimes the chr starts with a hash). vcf file: 2 rows, 10 columns. ?? col 0 ??????????????????????? col 1 ?????????? col 2 ? ? ? ? ? ? ? ?? col 3 ???????????? col 4????? col5??????????? col6?????????????????????? col7???????????????????????????????????? col8???????????????????? col9 chromosome????????? position???? ? ? ? .? ? ? ? ? ? ? ? ? Reference?????? ALT????? position? ? ? ? ? .? ??????? some statistics and the ID:s???????? not important?????? not important The important column is 7 where the ID is, i.e. refseq.functionalClass=missense. It's a missense mutation, so then I want to extract refseq.name=NM_003137492, or I want to extract only the ID, which in this case is NM_003137492. Then I want to do exactly the same thing for all the other mutations, but only for the missense mutations not the other ones. How do I accomplish that? Where do I start? Best, Anna _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Oct 7 22:28:38 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 07 Oct 2011 16:28:38 -0400 Subject: [Tutor] Help! In-Reply-To: <8CE5325CD7B62C2-958-35B86@webmail-m005.sysops.aol.com> References: <8CE5325CD7B62C2-958-35B86@webmail-m005.sysops.aol.com> Message-ID: <4E8F60F6.2060904@gmail.com> On 10/7/2011 12:32 PM, rmntcverses at aol.com wrote: > I need serious help with this Rock, Paper, Scissors program. The > program runs smoothly but I can't get the score to print. Please help > me with this one aspect! Here is my code right now: Welcome to Python Help. In future please use a meaningful subject, such as 'Rock Paper Scissors" Always reply-all so a copy goes to the list. We had a similar discussion recently on the Python-Tutor list. I submitted an alternate version of the game, which I reproduce here for your perusal. It uses some features of Python which may be new to you. Please study it, as it may offer some learning. import random print """Welcome to Rock,Paper, Scissors! This is a game of chance. The computer randomly picks one of three throws. Rock beats Scissors, but is beaten by Paper. Scissors beat Paper, but are beaten by Rock. Paper beats Rock, but is beaten by Scissors. You enter: r for Rock s for Scissors p for Paper q to Quit'""" wins = loses = 0 while True: # "endless" loop - exited by break statement player = raw_input("Please pick your throw: (r, s, p, or q ):") if player == "q": break # exits the loop elif player not in "rps": # check for valid entry print "Invalid entry" else: computer= random.choice("rsp") # no need for a list - a string is a sequence print "Computer throw:", computer if player == computer: # testing various conditiions cam be greatly simplified print "Tie! Throw again." elif player + computer in ["rs", "sp", "pr"]: print "You win! " + player + " beats " + computer wins += 1 # simpler than wins = wins + 1 else: print "You lose! " + computer + " beats " + player loses +=1 print """Game Summary Wins: %s Loses:" %s""" % (wins,loses) # using % formatting and triple quoted string print"Thanks for playing!" -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Oct 7 22:35:39 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 07 Oct 2011 16:35:39 -0400 Subject: [Tutor] Runtime error while Test data creation In-Reply-To: References: Message-ID: <4E8F629B.606@gmail.com> On 10/7/2011 2:19 PM, Guess?!? wrote: > Hello all, > > I am trying to create some test data for a search module that I am > building. Since I dont want to hit performance related issues late in > the game, I decided to create half a million records in the DB. > > My approach is create a csv file with valid UUIDs which I already > have. Read each record from csv and generate random data and do DB > insert as long the csv file has records in them. This crashes near > 100000 record insertions. > > The problem is that my program eventually fails with this error. Any > ideas what I can improve to make it go all the way? > > Runtime Error! > Program: C:\Python27\pythonw.exe > This app has requested the Runtime to terminate it in an unusual > way. Please contact application support team Please just post ordinary text. No colors, no fancy formatting. Please always post the entire traceback so we tell where the code failed. > > Here is the code that I wrote to do this. > > ======================================================================= > import pyodbc, random, datetime, uuid > > #INT > conn = pyodbc.connect('DRIVER={SQL > Server};SERVER=SERVERNAME\INT_FOUNDATIONS;DATABASE=membership_service;UID=int_usr;PWD=blah') > > > c = conn.cursor() > > # "enterprise_person_id" TEXT NOT NULL, > > # read file > f = open('C:\\Users\\garora\\Desktop\\INTPPLHALFMIL.csv','r') > > # Hardcoded valid seed values > > # INT > programId = 50801 > packageId = 46101 > pkg_optionId = 40301 > > > seed_data = "TEST_DATA" > > numberPrePend = "AAAA-" > > create_dt = datetime.datetime.now(); > modified_dt = datetime.datetime.now(); > > i = 0 > > for each in f: > if (i == 0): > i = i + 1 > continue; > (id, entrpid,) = each.split(',') > print id > id = id.replace('\n', '') > print id > id = uuid.UUID(id) > #enterprise_person_id > print entrpid > entrpid = entrpid.replace('\n', '') > print entrpid > entrpid = uuid.UUID(entrpid) > #random values for few columns > statusRandom = random.randint(1,4) > sourceRandom = random.randint(1,7) > inputChannelRandom = random.randint(1,5) > marketRandom= random.randint(1,10) > trialRandom = random.randint(0,1) > monthRandom = random.randint(3,12) # prevent month of feb > dateRandom = random.randint(1,30) # prevent 31st on invalid month > yearRandom = random.randint(2007,2010) > member_start_dt = datetime.datetime(yearRandom, monthRandom, > dateRandom,0,0,0) > current_term_start_dt = datetime.datetime(yearRandom, monthRandom, > dateRandom,0,0,0) > > print "id: " + str(i) > print " programId: " + str(programId) > print " packageId: " + str(packageId) > print " pkgoptionId: " + str(pkg_optionId) > print " status id: " + str(statusRandom) > print " source id: " + str(sourceRandom) > print " input channel id: " + str(inputChannelRandom) > print " market id: " + str(marketRandom) > print " person id: " + str(id) > print "membership id: " + numberPrePend + str(i) > print " member_start_dt " + str(member_start_dt) > print " current_term_start_dt " + str(current_term_start_dt) > print " started_as_trial " + str(trialRandom) > print " enterprise_person_id " + str(entrpid) > > record = (i, programId, packageId, pkg_optionId, statusRandom, > sourceRandom, inputChannelRandom, > marketRandom, str(id), numberPrePend + str(i), member_start_dt, > current_term_start_dt, trialRandom > ,seed_data, seed_data, create_dt, modified_dt, str(entrpid)) > print record > c.execute("""insert into Members(id, membership_program_id, > membership_package_id, > membership_pkg_option_id, membership_status_id, membership_source_id, > src_input_channel_id, > src_market_id, person_id_ref, membership_id, member_start_dt, > current_term_start_dt, started_as_trial, > created_by, modified_by, create_dt, modified_dt, enterprise_person_id) > values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", record) > conn.commit() > i = i + 1 > > c.close() > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From wtfwhoami at gmail.com Fri Oct 7 23:32:20 2011 From: wtfwhoami at gmail.com (Guess?!?) Date: Fri, 7 Oct 2011 14:32:20 -0700 Subject: [Tutor] Runtime error while Test data creation In-Reply-To: <4E8F629B.606@gmail.com> References: <4E8F629B.606@gmail.com> Message-ID: Hey Bob, Thanks for the suggestions. There is no traceback/stacktrace errors that I can see (may be there is a file that is generated in python or windows directory due to run time failure but I am not able to locate it. Please let me know if you know). The run time error pops up in a windows dialog box with a text I wrote below in my first email and closing the dialog box closes the IDLE GUI python. Thanks, G On Fri, Oct 7, 2011 at 1:35 PM, bob gailer wrote: > On 10/7/2011 2:19 PM, Guess?!? wrote: > > Hello all, > > I am trying to create some test data for a search module that I am > building. Since I dont want to hit performance related issues late in the > game, I decided to create half a million records in the DB. > > My approach is create a csv file with valid UUIDs which I already > have. Read each record from csv and generate random data and do DB insert as > long the csv file has records in them. This crashes near 100000 record > insertions. > > The problem is that my program eventually fails with this error. Any > ideas what I can improve to make it go all the way? > > Runtime Error! > Program: C:\Python27\pythonw.exe > This app has requested the Runtime to terminate it in an unusual > way. Please contact application support team > > > Please just post ordinary text. No colors, no fancy formatting. > > Please always post the entire traceback so we tell where the code failed. > > > Here is the code that I wrote to do this. > > ======================================================================= > import pyodbc, random, datetime, uuid > > #INT > conn = pyodbc.connect('DRIVER={SQL > Server};SERVER=SERVERNAME\INT_FOUNDATIONS;DATABASE=membership_service;UID=int_usr;PWD=blah') > > > c = conn.cursor() > > # "enterprise_person_id" TEXT NOT NULL, > > # read file > f = open('C:\\Users\\garora\\Desktop\\INTPPLHALFMIL.csv','r') > > # Hardcoded valid seed values > > # INT > programId = 50801 > packageId = 46101 > pkg_optionId = 40301 > > > seed_data = "TEST_DATA" > > numberPrePend = "AAAA-" > > create_dt = datetime.datetime.now(); > modified_dt = datetime.datetime.now(); > > i = 0 > > for each in f: > if (i == 0): > i = i + 1 > continue; > (id, entrpid,) = each.split(',') > print id > id = id.replace('\n', '') > print id > id = uuid.UUID(id) > #enterprise_person_id > print entrpid > entrpid = entrpid.replace('\n', '') > print entrpid > entrpid = uuid.UUID(entrpid) > #random values for few columns > statusRandom = random.randint(1,4) > sourceRandom = random.randint(1,7) > inputChannelRandom = random.randint(1,5) > marketRandom= random.randint(1,10) > trialRandom = random.randint(0,1) > monthRandom = random.randint(3,12) # prevent month of feb > dateRandom = random.randint(1,30) # prevent 31st on invalid month > yearRandom = random.randint(2007,2010) > member_start_dt = datetime.datetime(yearRandom, monthRandom, > dateRandom,0,0,0) > current_term_start_dt = datetime.datetime(yearRandom, monthRandom, > dateRandom,0,0,0) > > print "id: " + str(i) > print " programId: " + str(programId) > print " packageId: " + str(packageId) > print " pkgoptionId: " + str(pkg_optionId) > print " status id: " + str(statusRandom) > print " source id: " + str(sourceRandom) > print " input channel id: " + str(inputChannelRandom) > print " market id: " + str(marketRandom) > print " person id: " + str(id) > print "membership id: " + numberPrePend + str(i) > print " member_start_dt " + str(member_start_dt) > print " current_term_start_dt " + str(current_term_start_dt) > print " started_as_trial " + str(trialRandom) > print " enterprise_person_id " + str(entrpid) > > record = (i, programId, packageId, pkg_optionId, statusRandom, > sourceRandom, inputChannelRandom, > marketRandom, str(id), numberPrePend + str(i), member_start_dt, > current_term_start_dt, trialRandom > ,seed_data, seed_data, create_dt, modified_dt, str(entrpid)) > print record > c.execute("""insert into Members(id, membership_program_id, > membership_package_id, > membership_pkg_option_id, membership_status_id, membership_source_id, > src_input_channel_id, > src_market_id, person_id_ref, membership_id, member_start_dt, > current_term_start_dt, started_as_trial, > created_by, modified_by, create_dt, modified_dt, enterprise_person_id) > values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", record) > conn.commit() > i = i + 1 > > c.close() > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor > > > > -- > Bob Gailer919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Oct 7 23:54:07 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 7 Oct 2011 17:54:07 -0400 Subject: [Tutor] Runtime error while Test data creation In-Reply-To: References: <4E8F629B.606@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21444863@EMARC112VS01.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Guess?!? Sent: Friday, October 07, 2011 4:32 PM To: bob gailer Cc: tutor at python.org Subject: Re: [Tutor] Runtime error while Test data creation Hey Bob, Thanks for the suggestions. There is no traceback/stacktrace errors that I can see (may be there is a file that is generated in python or windows directory due to run time failure but I am not able to locate it. Please let me know if you know).? The run time error pops up in a windows dialog box with a text I wrote below in my first email and closing the dialog box closes the IDLE GUI python.? Thanks, G ============================================================================== I would change those print statements to write to file (each record should be one line) instead. Be sure to append the file and not overwrite and close the file before each insert statement. Then you can see how far it gets and try to insert the last row again to see if it is a user error. Otherwise I would think it is possibly a connection/memory issue. Try running the code with 1 row first and then increase the number of rows being written. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From lina.lastname at gmail.com Sat Oct 8 04:52:01 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 10:52:01 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21444181@EMARC112VS01.exchad.jpmchase.net> Message-ID: > The 'with' syntax above implicitly closes the file for you > at the end of the block. If you use the > > f = open(...) > > style you are expected to explicitly close the file when you are finished > with it. This is especially important when writing to a file because that > will guarantee that the OS writes the data to the file on disk. Without a > close its possible for your data to get held in a buffer that doesn't get > written to disk. Rare, but possible. > > Thanks. BTW, are there some tricks in using gedit input code. such as I wanna backspace, but usually won't count 4 spaces, and sometimes I wanna more back space, like move: >>> a to >>> a the "prompt" sign here to give a reference position of a, I am interested in gedit, not idle here. Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Sat Oct 8 04:55:08 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 10:55:08 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: > C is a great language for writing Operating Systems and other "near the > metal" code. But its not the best language for busiess apps, artificial > intelligence and a host of other things. Bash is a good user shell, but its > not even the best Unix shell for scripting (Thats probably ksh). > D? Who actually uses D? I think your informant was not well informed. > Next time when I saw my friend, I would ask, "have you met someone who has actually started in use D yet?" it's a joke, thanks for informing me that. > > AS fopr Python becoming obsolete? Maybe someday, but not soon. > And even if it does the principles it teaches are alive and well in many > other languages - eg, Ruby, Lua both openly borrow from Python. > Just as Python borrows from Lisp and Haskell and Smalltalk and Perl. > > > > I was further told that fortran is obsolete, but still lots of > > fortran guys using it. > > Absolutely and Lisp and COBOL ghave both been predicted to die for decades > but are still marching on. It is very difficult to kill a popular language > because the thing that made it popular keeps it > alive. > > Ignore rumours and focus on programming. Don't worry about languages, once > you know one you'll usually pick up another very quickly. They come and go > in fashion but the concepts remain constant. Most programmers work in > multiple languages, often even in a single > project. Thanks again, > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Oct 8 05:14:45 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 07 Oct 2011 23:14:45 -0400 Subject: [Tutor] Runtime error while Test data creation In-Reply-To: References: <4E8F629B.606@gmail.com> Message-ID: <4E8FC025.5060906@gmail.com> On 10/7/2011 5:32 PM, Guess?!? wrote: > Hey Bob, > > Thanks for the suggestions. There is no traceback/stacktrace errors > that I can see (may be there is a file that is generated in python or > windows directory due to run time failure but I am not able to locate > it. Please let me know if you know). > > The run time error pops up in a windows dialog box with a text I wrote > below in my first email and closing the dialog box closes the IDLE GUI > python. Of course. I should have seen that from your original post. My guess is that the problem is raised by the insert. Try commenting that out and see if the program runs to completion. > On Fri, Oct 7, 2011 at 1:35 PM, bob gailer > wrote: > > On 10/7/2011 2:19 PM, Guess?!? wrote: >> Hello all, >> >> I am trying to create some test data for a search module that I >> am building. Since I dont want to hit performance related issues >> late in the game, I decided to create half a million records in >> the DB. >> >> My approach is create a csv file with valid UUIDs which I already >> have. Read each record from csv and generate random data and do >> DB insert as long the csv file has records in them. This crashes >> near 100000 record insertions. >> >> The problem is that my program eventually fails with this error. >> Any ideas what I can improve to make it go all the way? >> >> Runtime Error! >> Program: C:\Python27\pythonw.exe >> This app has requested the Runtime to terminate it in an unusual >> way. Please contact application support team > Here is the code that I wrote to do this. > > ======================================================================= > import pyodbc, random, datetime, uuid > > #INT > conn = pyodbc.connect('DRIVER={SQL > Server};SERVER=SERVERNAME\INT_FOUNDATIONS;DATABASE=membership_service;UID=int_usr;PWD=blah') > > > c = conn.cursor() > > # "enterprise_person_id" TEXT NOT NULL, > > # read file > f = open('C:\\Users\\garora\\Desktop\\INTPPLHALFMIL.csv','r') > > # Hardcoded valid seed values > > # INT > programId = 50801 > packageId = 46101 > pkg_optionId = 40301 > > > seed_data = "TEST_DATA" > > numberPrePend = "AAAA-" > > create_dt = datetime.datetime.now(); > modified_dt = datetime.datetime.now(); > > i = 0 > > for each in f: > if (i == 0): > i = i + 1 > continue; > (id, entrpid,) = each.split(',') > print id > id = id.replace('\n', '') > print id > id = uuid.UUID(id) > #enterprise_person_id > print entrpid > entrpid = entrpid.replace('\n', '') > print entrpid > entrpid = uuid.UUID(entrpid) > #random values for few columns > statusRandom = random.randint(1,4) > sourceRandom = random.randint(1,7) > inputChannelRandom = random.randint(1,5) > marketRandom= random.randint(1,10) > trialRandom = random.randint(0,1) > monthRandom = random.randint(3,12) # prevent month of feb > dateRandom = random.randint(1,30) # prevent 31st on invalid month > yearRandom = random.randint(2007,2010) > member_start_dt = datetime.datetime(yearRandom, monthRandom, > dateRandom,0,0,0) > current_term_start_dt = datetime.datetime(yearRandom, monthRandom, > dateRandom,0,0,0) > > print "id: " + str(i) > print " programId: " + str(programId) > print " packageId: " + str(packageId) > print " pkgoptionId: " + str(pkg_optionId) > print " status id: " + str(statusRandom) > print " source id: " + str(sourceRandom) > print " input channel id: " + str(inputChannelRandom) > print " market id: " + str(marketRandom) > print " person id: " + str(id) > print "membership id: " + numberPrePend + str(i) > print " member_start_dt " + str(member_start_dt) > print " current_term_start_dt " + str(current_term_start_dt) > print " started_as_trial " + str(trialRandom) > print " enterprise_person_id " + str(entrpid) > > record = (i, programId, packageId, pkg_optionId, statusRandom, > sourceRandom, inputChannelRandom, > marketRandom, str(id), numberPrePend + str(i), member_start_dt, > current_term_start_dt, trialRandom > ,seed_data, seed_data, create_dt, modified_dt, str(entrpid)) > print record > c.execute("""insert into Members(id, membership_program_id, > membership_package_id, > membership_pkg_option_id, membership_status_id, > membership_source_id, src_input_channel_id, > src_market_id, person_id_ref, membership_id, member_start_dt, > current_term_start_dt, started_as_trial, > created_by, modified_by, create_dt, modified_dt, > enterprise_person_id) > values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", record) > conn.commit() > i = i + 1 > > c.close() > > > >> _______________________________________________ >> Tutor maillist -Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Oct 8 05:28:55 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 07 Oct 2011 23:28:55 -0400 Subject: [Tutor] Runtime error while Test data creation In-Reply-To: References: <4E8F629B.606@gmail.com> Message-ID: <4E8FC377.90106@gmail.com> On 10/7/2011 5:32 PM, Guess?!? wrote: A couple of suggestion below (inline with the code): > >> import pyodbc, random, datetime, uuid >> >> #INT >> conn = pyodbc.connect('DRIVER={SQL >> Server};SERVER=SERVERNAME\INT_FOUNDATIONS;DATABASE=membership_service;UID=int_usr;PWD=blah') >> >> >> c = conn.cursor() >> >> # "enterprise_person_id" TEXT NOT NULL, >> >> # read file >> f = open('C:\\Users\\garora\\Desktop\\INTPPLHALFMIL.csv','r') >> >> # Hardcoded valid seed values >> >> # INT >> programId = 50801 >> packageId = 46101 >> pkg_optionId = 40301 >> >> >> seed_data = "TEST_DATA" >> >> numberPrePend = "AAAA-" >> >> create_dt = datetime.datetime.now(); >> modified_dt = datetime.datetime.now(); >> >> i = 0 > f.readline() # to dispense with first line > >> >> for each in f: >> (id, entrpid,) = each.split(',') >> print id >> id = id.replace('\n', '') >> print id >> id = uuid.UUID(id) >> #enterprise_person_id >> print entrpid >> entrpid = entrpid.replace('\n', '') >> print entrpid >> entrpid = uuid.UUID(entrpid) >> #random values for few columns >> statusRandom = random.randint(1,4) >> sourceRandom = random.randint(1,7) >> inputChannelRandom = random.randint(1,5) >> marketRandom= random.randint(1,10) >> trialRandom = random.randint(0,1) >> monthRandom = random.randint(3,12) # prevent month of feb >> dateRandom = random.randint(1,30) # prevent 31st on invalid month >> yearRandom = random.randint(2007,2010) >> member_start_dt = datetime.datetime(yearRandom, monthRandom, >> dateRandom,0,0,0) >> current_term_start_dt = datetime.datetime(yearRandom, >> monthRandom, dateRandom,0,0,0) >> >> print "id: " + str(i) > print id, i # same effect, less code. apply to following lines also > >> print " programId: " + str(programId) >> print " packageId: " + str(packageId) >> print " pkgoptionId: " + str(pkg_optionId) >> print " status id: " + str(statusRandom) >> print " source id: " + str(sourceRandom) >> print " input channel id: " + str(inputChannelRandom) >> print " market id: " + str(marketRandom) >> print " person id: " + str(id) >> print "membership id: " + numberPrePend + str(i) >> print " member_start_dt " + str(member_start_dt) >> print " current_term_start_dt " + str(current_term_start_dt) >> print " started_as_trial " + str(trialRandom) >> print " enterprise_person_id " + str(entrpid) >> >> record = (i, programId, packageId, pkg_optionId, statusRandom, >> sourceRandom, inputChannelRandom, >> marketRandom, str(id), numberPrePend + str(i), member_start_dt, >> current_term_start_dt, trialRandom >> ,seed_data, seed_data, create_dt, modified_dt, str(entrpid)) >> print record >> c.execute("""insert into Members(id, membership_program_id, >> membership_package_id, >> membership_pkg_option_id, membership_status_id, >> membership_source_id, src_input_channel_id, >> src_market_id, person_id_ref, membership_id, member_start_dt, >> current_term_start_dt, started_as_trial, >> created_by, modified_by, create_dt, modified_dt, >> enterprise_person_id) >> values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", record) >> conn.commit() >> i = i + 1 >> >> c.close() >> >> >> >> _______________________________________________ >> Tutor maillist -Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Sat Oct 8 05:34:05 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 11:34:05 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: Another minor derived questions: summary=[] for a,b in zip(results['E'],results['B']): summary.append(a+b) ## now the summary is '[0,1, 3, 5, 6,0,0,0]' del summary[0] ## here I wanna remove the first zero, which came from the initial double quote "EB...E", summary.pop() ## here I wanna remove the last three zeros summary.pop() summary.pop() print(summary) ### output is [1,3,5,6] summary='\n'.join(str(summary).split(',')) ### wish the result in one column, with open(base+OUTFILEEXT,"w") as f: f.write(str(summary)) the final result in the output.txt file is: [1 3 5 6] Q1: how can I remove the [1 "[" to only keep 1? Q2 how can I improve above expressions? Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Sat Oct 8 06:07:43 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 12:07:43 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: Still have a reading "multiple" files issue: Traceback (most recent call last): File "counter-vertically-WORKING.py", line 26, in results[ch][col]+=1 IndexError: list index out of range only one file ss_1.xpm was processed and wrote file, for the rest ss_2.xpm, ss_3.xpm and following keep intact, any suggestions? thanks, and sorry for so many questions here, -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sat Oct 8 06:22:47 2011 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXZgCDZhtmI2YHZhCDZgNin2K8p?=) Date: Sat, 8 Oct 2011 07:22:47 +0300 Subject: [Tutor] swapping list elements based on some criterion Message-ID: Hello Tutors, It's been quite some time since I last posted something here, and now I'm back with a question: I want to re-structure English so that the adjectives appear after the nouns, instead of before. If I have a sentence like: The tall man plays well I need to change it to The man tall plays well So far, I have thought of the following function, but I'm not sure it's the best solution. It assumes that the sentence has been augmented with part of speech tags (Also plz note that there may be multiple adjectives) ###################### test = "the/DET tall/ADJ man/N plays/VBZ well/ADV" def swapAdjNoun(sentence): sentence = sentence.split() new = [] x = enumerate(sentence) for idx, lex in x: if lex.endswith("/N") and sentence[idx-1].endswith("/ADJ"): idx = idx - 1 elif lex.endswith("/ADJ") and sentence[idx+1].endswith("/N"): idx = idx + 1 new.append((idx, lex)) new.sort() new = [ elm[1] for elm in new] return new #################### I'd appreciate if if you gave me some advice on how to do this the right way. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Oct 8 07:51:16 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 08 Oct 2011 16:51:16 +1100 Subject: [Tutor] swapping list elements based on some criterion In-Reply-To: References: Message-ID: <4E8FE4D4.2060508@pearwood.info> Emad Nawfal (??? ???? ???) wrote: > Hello Tutors, > It's been quite some time since I last posted something here, and now I'm > back with a question: > > I want to re-structure English so that the adjectives appear after the > nouns, instead of before. > If I have a sentence like: > > The tall man plays well > I need to change it to > The man tall plays well > So far, I have thought of the following function, but I'm not sure it's the > best solution. It assumes that the sentence has been augmented with part of > speech tags > (Also plz note that there may be multiple adjectives) And what do you expect to happen with multiple adjectives? "the tall fat bald man" => "the man tall fat bald" => "the man fat tall bald" => "the man bald fat tall" => "the man fat bald tall" => something else? The approach I would take is this: Walk along the sentence, inspecting each word. Collect all consecutive adjectives into a list of adjectives Other words get copied straight into the buffer. When you reach a noun, copy the noun into the buffer, plus the list of adjectives (in whichever order you like!), then clear the list of adjectives ready for the next noun. Does that help? Something like this: def swap(sentence): buffer = [] adjectives = [] for word in sentence.split(): if word.endswith('/ADJ'): adjectives.append(word) elif word.endswith('/N'): buffer.extend(adjectives) buffer.append(word) adjectives = [] else: buffer.append(word) return ' '.join(buffer) P.S. Since this looks like homework, I have left a deliberate mistake in my code for you to fix. But it should be easy to fix if you study the code and think about what it is doing. -- Steven From andreas.perstinger at gmx.net Sat Oct 8 07:57:37 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 08 Oct 2011 07:57:37 +0200 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On 2011-10-08 05:34, lina wrote: > Another minor derived questions: > > summary=[] > for a,b in zip(results['E'],results['B']): > summary.append(a+b) ## now the summary is '[0,1, 3, 5, > 6,0,0,0]' > del summary[0] ## here I wanna remove the first zero, which came > from the initial double quote "EB...E", > summary.pop() ## here I wanna remove the last three zeros > summary.pop() > summary.pop() > print(summary) ### output is [1,3,5,6] > summary='\n'.join(str(summary).split(',')) ### wish the result in > one column, > with open(base+OUTFILEEXT,"w") as f: > f.write(str(summary)) > > the final result in the output.txt file is: > [1 > 3 > 5 > 6] > > Q1: how can I remove the [1 "[" to only keep 1? That's a job for a list comprehension (read http://docs.python.org/py3k/tutorial/datastructures.html#list-comprehensions for a short introduction): new_summary = '\n'.join([str(element) for element in summary]) > Q2 how can I improve above expressions? -) As above, you could use a list comprehension for creating your summary list: summary = [(a + b) for a, b in zip(results['E'], results['B'])] -) Instead of del summary[0] summary.pop() summary.pop() summary.pop() I suggest to slice your list: summary = summary[1:-3] But this assumes that your summary list will always have one leading zero and 3 trailing zeros. -) In your last line with open(base+OUTFILEEXT,"w") as f: f.write(str(summary)) you don't need to convert summary to a string because it is already one. Bye, Andreas From andreas.perstinger at gmx.net Sat Oct 8 07:59:27 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 08 Oct 2011 07:59:27 +0200 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On 2011-10-08 06:07, lina wrote: > Still have a reading "multiple" files issue: > > Traceback (most recent call last): > File "counter-vertically-WORKING.py", line 26, in > results[ch][col]+=1 > IndexError: list index out of range > > only one file ss_1.xpm was processed and wrote file, for the rest ss_2.xpm, > ss_3.xpm and following keep intact, > > any suggestions? Could you provide links to your current script file (counter-vertically-WORKING.py) and your data files(ss_1.xpm, ss_2.xpm, ...)? Bye, Andreas From andreas.perstinger at gmx.net Sat Oct 8 08:08:02 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 08 Oct 2011 08:08:02 +0200 Subject: [Tutor] vcf_files and strings In-Reply-To: References: Message-ID: [I have already answered your first post but it seems you missed it] On 2011-10-07 18:12, Anna Olofsson wrote: > > Hi, > > I'm a beginner at Python and would really appreciate some help in how > to extract information from a vcf file. What does "beginner" mean? Do you have experience in other languages? Do you understand how different datatypes work (strings, integers, lists, dictionaries, ...)? Do you know the basic programming concepts (for-loops, if-then-else conditions, ...)? > The important column is 7 where the ID is, i.e. > refseq.functionalClass=missense. It's a missense mutation, so then I > want to extract refseq.name=NM_003137492, or I want to extract only > the ID, which in this case is NM_003137492. > > Then I want to do exactly the same thing for all the other mutations, > but only for the missense mutations not the other ones. How do I > accomplish that? Where do I start? Can you show us some code snippets of your attempts? Bye, Andreas From lina.lastname at gmail.com Sat Oct 8 08:25:13 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 14:25:13 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: > Still have a reading "multiple" files issue: >> >> Traceback (most recent call last): >> File "counter-vertically-WORKING.**py", line 26, in >> results[ch][col]+=1 >> IndexError: list index out of range >> >> only one file ss_1.xpm was processed and wrote file, for the rest >> ss_2.xpm, >> ss_3.xpm and following keep intact, >> >> any suggestions? >> > > Could you provide links to your current script file > (counter-vertically-WORKING.**py) and your data files(ss_1.xpm, ss_2.xpm, > ...)? > https://docs.google.com/leaf?id=0B93SVRfpVVg3MjIxZGI5YWQtN2NiYy00MWFkLWE0ZTctNjExNGJiNjYzYjQw&hl=en_GB https://docs.google.com/leaf?id=0B93SVRfpVVg3YjQ1ZWRkMjUtNmZhYS00MTA4LTg3YTktY2JjYzEyMDU5OTI2&hl=en_GB https://docs.google.com/leaf?id=0B93SVRfpVVg3YjQ1ZWRkMjUtNmZhYS00MTA4LTg3YTktY2JjYzEyMDU5OTI2&hl=en_US you may rename ss_1.xpm to the ss_2 or 3, keep them the same is okay, just different names. Thanks, > Bye, Andreas > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sat Oct 8 08:37:33 2011 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXZgCDZhtmI2YHZhCDZgNin2K8p?=) Date: Sat, 8 Oct 2011 09:37:33 +0300 Subject: [Tutor] swapping list elements based on some criterion In-Reply-To: <4E8FE4D4.2060508@pearwood.info> References: <4E8FE4D4.2060508@pearwood.info> Message-ID: Hi Steven ans Tutors, Thanks for the code. Actually I'm not a student at all. I'm an assistant professor of Arabic at Suez Canal University in Egypt. I would appreciate more contributions from you and the other list members. 2011/10/8 Steven D'Aprano > Emad Nawfal (??? ???? ???) wrote: > >> Hello Tutors, >> It's been quite some time since I last posted something here, and now I'm >> back with a question: >> >> I want to re-structure English so that the adjectives appear after the >> nouns, instead of before. >> If I have a sentence like: >> >> The tall man plays well >> I need to change it to >> The man tall plays well >> So far, I have thought of the following function, but I'm not sure it's >> the >> best solution. It assumes that the sentence has been augmented with part >> of >> speech tags >> (Also plz note that there may be multiple adjectives) >> > > And what do you expect to happen with multiple adjectives? > > "the tall fat bald man" > > => "the man tall fat bald" > => "the man fat tall bald" > => "the man bald fat tall" > => "the man fat bald tall" > => something else? > > The approach I would take is this: > > > Walk along the sentence, inspecting each word. > Collect all consecutive adjectives into a list of adjectives > Other words get copied straight into the buffer. > When you reach a noun, copy the noun into the buffer, plus the list > of adjectives (in whichever order you like!), then clear the list > of adjectives ready for the next noun. > > Does that help? > > Something like this: > > def swap(sentence): > buffer = [] > adjectives = [] > for word in sentence.split(): > if word.endswith('/ADJ'): > adjectives.append(word) > elif word.endswith('/N'): > buffer.extend(adjectives) > buffer.append(word) > adjectives = [] > else: > buffer.append(word) > return ' '.join(buffer) > > > P.S. Since this looks like homework, I have left a deliberate mistake in my > code for you to fix. But it should be easy to fix if you study the code and > think about what it is doing. > > > -- > Steven > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sat Oct 8 08:50:03 2011 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXZgCDZhtmI2YHZhCDZgNin2K8p?=) Date: Sat, 8 Oct 2011 09:50:03 +0300 Subject: [Tutor] swapping list elements based on some criterion In-Reply-To: References: <4E8FE4D4.2060508@pearwood.info> Message-ID: 2011/10/8 Emad Nawfal (??? ???? ???) > Hi Steven ans Tutors, > Thanks for the code. > Actually I'm not a student at all. I'm an assistant professor of Arabic at > Suez Canal University in Egypt. I would appreciate more contributions from > you and the other list members. > > > 2011/10/8 Steven D'Aprano > >> Emad Nawfal (??? ???? ???) wrote: >> >>> Hello Tutors, >>> It's been quite some time since I last posted something here, and now I'm >>> back with a question: >>> >>> I want to re-structure English so that the adjectives appear after the >>> nouns, instead of before. >>> If I have a sentence like: >>> >>> The tall man plays well >>> I need to change it to >>> The man tall plays well >>> So far, I have thought of the following function, but I'm not sure it's >>> the >>> best solution. It assumes that the sentence has been augmented with part >>> of >>> speech tags >>> (Also plz note that there may be multiple adjectives) >>> >> >> And what do you expect to happen with multiple adjectives? >> >> "the tall fat bald man" >> >> => "the man tall fat bald" >> => "the man fat tall bald" >> => "the man bald fat tall" >> => "the man fat bald tall" >> => something else? >> >> The approach I would take is this: >> >> >> Walk along the sentence, inspecting each word. >> Collect all consecutive adjectives into a list of adjectives >> Other words get copied straight into the buffer. >> When you reach a noun, copy the noun into the buffer, plus the list >> of adjectives (in whichever order you like!), then clear the list >> of adjectives ready for the next noun. >> >> Does that help? >> >> Something like this: >> >> def swap(sentence): >> buffer = [] >> adjectives = [] >> for word in sentence.split(): >> if word.endswith('/ADJ'): >> adjectives.append(word) >> elif word.endswith('/N'): >> buffer.extend(adjectives) >> buffer.append(word) >> adjectives = [] >> else: >> buffer.append(word) >> return ' '.join(buffer) >> >> >> P.S. Since this looks like homework, I have left a deliberate mistake in >> my code for you to fix. But it should be easy to fix if you study the code >> and think about what it is doing. >> >> >> -- >> Steven >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? > ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > -------------------------------------------------------- > Hi Steven, Thanks again for the recipe and for leaving an error in the function. This forced me to use my mind a little bit. Here is the function as I used it, and it works fine: def swap(sentence): buffer = [] adjectives = [] for word in sentence.split(): if word.endswith('/ADJ'): adjectives.append(word) elif word.endswith('/N'): buffer.append(word) buffer.extend(adjectives) adjectives = [] else: buffer.append(word) return ' '.join(buffer) and SORRY for top-posting in the previous email. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Sat Oct 8 08:50:34 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 08 Oct 2011 08:50:34 +0200 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: <4E8FF2BA.9050204@gmx.net> On 2011-10-08 08:25, lina wrote: >> Still have a reading "multiple" files issue: >>> >>> Traceback (most recent call last): >>> File "counter-vertically-WORKING.**py", line 26, in >>> results[ch][col]+=1 >>> IndexError: list index out of range >>> >>> only one file ss_1.xpm was processed and wrote file, for the rest >>> ss_2.xpm, >>> ss_3.xpm and following keep intact, >>> >>> any suggestions? > > https://docs.google.com/leaf?id=0B93SVRfpVVg3MjIxZGI5YWQtN2NiYy00MWFkLWE0ZTctNjExNGJiNjYzYjQw&hl=en_GB > > https://docs.google.com/leaf?id=0B93SVRfpVVg3YjQ1ZWRkMjUtNmZhYS00MTA4LTg3YTktY2JjYzEyMDU5OTI2&hl=en_GB > > https://docs.google.com/leaf?id=0B93SVRfpVVg3YjQ1ZWRkMjUtNmZhYS00MTA4LTg3YTktY2JjYzEyMDU5OTI2&hl=en_US > > you may rename ss_1.xpm to the ss_2 or 3, keep them the same is okay, just > different names. Ok, I just ran your script with this files and don't get an error. Except some stylistic issues the code looks fine. The resulting txt-files still have the problem with the leading '[' and trailing ']' but I've already suggested a solution earlier today. Do you still get an error? Bye, Andreas From lina.lastname at gmail.com Sat Oct 8 09:12:31 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 15:12:31 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8FF2BA.9050204@gmx.net> References: <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <4E8FF2BA.9050204@gmx.net> Message-ID: On Sat, Oct 8, 2011 at 2:50 PM, Andreas Perstinger < andreas.perstinger at gmx.net> wrote: > On 2011-10-08 08:25, lina wrote: > >> Still have a reading "multiple" files issue: >>> >>>> >>>> Traceback (most recent call last): >>>> File "counter-vertically-WORKING.****py", line 26, in >>>> >>>> results[ch][col]+=1 >>>> IndexError: list index out of range >>>> >>>> only one file ss_1.xpm was processed and wrote file, for the rest >>>> ss_2.xpm, >>>> ss_3.xpm and following keep intact, >>>> >>>> any suggestions? >>>> >>> >> https://docs.google.com/leaf?**id=**0B93SVRfpVVg3MjIxZGI5YWQtN2NiY** >> y00MWFkLWE0ZTctNjExNGJiNjYzYjQ**w&hl=en_GB >> >> https://docs.google.com/leaf?**id=**0B93SVRfpVVg3YjQ1ZWRkMjUtNmZhY** >> S00MTA4LTg3YTktY2JjYzEyMDU5OTI**2&hl=en_GB >> >> https://docs.google.com/leaf?**id=**0B93SVRfpVVg3YjQ1ZWRkMjUtNmZhY** >> S00MTA4LTg3YTktY2JjYzEyMDU5OTI**2&hl=en_US >> >> you may rename ss_1.xpm to the ss_2 or 3, keep them the same is okay, just >> different names. >> > > Ok, I just ran your script with this files and don't get an error. Except > some stylistic issues the code looks fine. The resulting txt-files still > have the problem with the leading '[' and trailing ']' but I've already > suggested a solution earlier today. > > Do you still get an error? $ python3 counter-vertically-WORKING.py [26, 22, 28, 30, 32, 27, 30, 29, 28, 30, 32, 24, 27, 27, 28, 30, 32, 30, 33, 27, 33, 32, 34, 31, 28, 34, 33, 32, 25, 35, 30, 32, 30, 32, 25, 30, 26, 24, 33, 28, 27, 26, 23, 27, 27, 28, 27, 25, 24, 23, 23, 27, 24, 27, 26, 23, 17, 25, 21, 28, 21, 15, 24, 21, 12, 11, 9, 15, 20, 15, 15, 22, 29, 30, 23, 21, 29, 31, 17, 26, 21, 23, 23, 19, 25, 21, 27, 23, 25, 30, 26, 23, 25, 23, 25, 30, 28, 29, 25, 26, 28, 23, 26, 30, 25, 25, 21, 23, 23, 25, 21, 25, 25, 23, 30, 29, 28, 27, 27, 29, 27, 23, 27, 29, 21, 24, 23, 21, 25, 23, 26, 23, 23, 23, 23, 24, 25, 21, 23, 23, 23, 25, 25, 30, 25, 23, 26, 24, 28, 25, 25, 23, 23, 19, 23, 23, 21, 25, 18, 23, 21, 25, 21, 23, 25, 23, 22, 23, 21, 28, 25, 24, 21, 20, 21, 14, 23, 21, 13, 14, 21, 23, 24, 29, 26, 26, 21, 17, 19, 23, 21, 24, 26, 24, 26, 29, 29, 28, 28, 21, 24] Traceback (most recent call last): File "counter-vertically-WORKING.py", line 26, in results[ch][col]+=1 IndexError: list index out of range still the same, and only one txt coming out. the others did not process. $ ls *.xpm *.txt ss_0.xpm ss_1.xpm ss_4.xpm ss_7.xpm ss_9.xpm ss_10.xpm ss_2.xpm ss_5.xpm ss_1.txt ss_3.xpm ss_6.xpm ss_8.xpm thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Sat Oct 8 09:28:06 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 15:28:06 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E8FF2BA.9050204@gmx.net> References: <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <4E8FF2BA.9050204@gmx.net> Message-ID: On Sat, Oct 8, 2011 at 2:50 PM, Andreas Perstinger < andreas.perstinger at gmx.net> wrote: > On 2011-10-08 08:25, lina wrote: > >> Still have a reading "multiple" files issue: >>> >>>> >>>> Traceback (most recent call last): >>>> File "counter-vertically-WORKING.****py", line 26, in >>>> >>>> results[ch][col]+=1 >>>> IndexError: list index out of range >>>> >>>> only one file ss_1.xpm was processed and wrote file, for the rest >>>> ss_2.xpm, >>>> ss_3.xpm and following keep intact, >>>> >>>> any suggestions? >>>> >>> >> https://docs.google.com/leaf?**id=**0B93SVRfpVVg3MjIxZGI5YWQtN2NiY** >> y00MWFkLWE0ZTctNjExNGJiNjYzYjQ**w&hl=en_GB >> >> https://docs.google.com/leaf?**id=**0B93SVRfpVVg3YjQ1ZWRkMjUtNmZhY** >> S00MTA4LTg3YTktY2JjYzEyMDU5OTI**2&hl=en_GB >> >> https://docs.google.com/leaf?**id=**0B93SVRfpVVg3YjQ1ZWRkMjUtNmZhY** >> S00MTA4LTg3YTktY2JjYzEyMDU5OTI**2&hl=en_US >> >> you may rename ss_1.xpm to the ss_2 or 3, keep them the same is okay, just >> different names. >> > > Ok, I just ran your script with this files and don't get an error. Except > some stylistic issues the code looks fine. The resulting txt-files still > have the problem with the leading '[' and trailing ']' but I've already > suggested a solution earlier today. > > Do you still get an error? I figured it out, my mistake, the following files from ss_2.xpm to ss_10.xpm has one more line than ss_1.xpm so after changed LINESTOSKIP=23 to 24 it works. before the ss_1.xpm was taking as the trial and finished, the last 9 was generated with script, so there was a very minor differences. Thanks for your help, Best, -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Sat Oct 8 09:37:23 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 08 Oct 2011 09:37:23 +0200 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <4E8FF2BA.9050204@gmx.net> Message-ID: <4E8FFDB3.3050708@gmx.net> On 2011-10-08 09:12, lina wrote: > $ python3 counter-vertically-WORKING.py > [26, 22, 28, 30, 32, 27, 30, 29, 28, 30, 32, 24, 27, 27, 28, 30, 32, 30, 33, > 27, 33, 32, 34, 31, 28, 34, 33, 32, 25, 35, 30, 32, 30, 32, 25, 30, 26, 24, > 33, 28, 27, 26, 23, 27, 27, 28, 27, 25, 24, 23, 23, 27, 24, 27, 26, 23, 17, > 25, 21, 28, 21, 15, 24, 21, 12, 11, 9, 15, 20, 15, 15, 22, 29, 30, 23, 21, > 29, 31, 17, 26, 21, 23, 23, 19, 25, 21, 27, 23, 25, 30, 26, 23, 25, 23, 25, > 30, 28, 29, 25, 26, 28, 23, 26, 30, 25, 25, 21, 23, 23, 25, 21, 25, 25, 23, > 30, 29, 28, 27, 27, 29, 27, 23, 27, 29, 21, 24, 23, 21, 25, 23, 26, 23, 23, > 23, 23, 24, 25, 21, 23, 23, 23, 25, 25, 30, 25, 23, 26, 24, 28, 25, 25, 23, > 23, 19, 23, 23, 21, 25, 18, 23, 21, 25, 21, 23, 25, 23, 22, 23, 21, 28, 25, > 24, 21, 20, 21, 14, 23, 21, 13, 14, 21, 23, 24, 29, 26, 26, 21, 17, 19, 23, > 21, 24, 26, 24, 26, 29, 29, 28, 28, 21, 24] > Traceback (most recent call last): > File "counter-vertically-WORKING.py", line 26, in > results[ch][col]+=1 > IndexError: list index out of range > > still the same, and only one txt coming out. the others did not process. > > $ ls *.xpm *.txt > ss_0.xpm ss_1.xpm ss_4.xpm ss_7.xpm ss_9.xpm > ss_10.xpm ss_2.xpm ss_5.xpm > ss_1.txt ss_3.xpm ss_6.xpm ss_8.xpm Strange, if I do $ python3.2 counter-vertically-WORKING.py it prints all results and also creates all txt-files: $ ls *.xpm *.txt ss_0.txt ss_0.xpm ss_1.txt ss_1.xpm ss_2.txt ss_2.xpm Please insert "print(fileName)" as the first line in your main for-loop so we can see on which file the program hangs. Bye, Andreas From __peter__ at web.de Sat Oct 8 09:53:35 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Oct 2011 09:53:35 +0200 Subject: [Tutor] swapping list elements based on some criterion References: <4E8FE4D4.2060508@pearwood.info> Message-ID: Emad Nawfal (??? ???? ???) wrote: > Here is the function as I used it, and it works fine: > > def swap(sentence): > buffer = [] > adjectives = [] > for word in sentence.split(): > if word.endswith('/ADJ'): > adjectives.append(word) > elif word.endswith('/N'): > buffer.append(word) > buffer.extend(adjectives) > > adjectives = [] > else: > buffer.append(word) > return ' '.join(buffer) Does the classification scheme allow for adjectives that are not followed by a noun? Example: if "good" in the sentence "That looks good" were classified as an adjective it would be silently dropped. From steve at pearwood.info Sat Oct 8 10:43:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 08 Oct 2011 19:43:27 +1100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: <4E900D2F.70702@pearwood.info> Alan Gauld wrote: > On 07/10/11 16:40, lina wrote: > >> but today I was also discouraged, I was told that you should not have >> learned python, you should focus on C or bash, or D, cause python is >> going to be obsolete, > > C is a great language for writing Operating Systems and other "near the > metal" code. But its not the best language for busiess apps, artificial > intelligence and a host of other things. Bash is a good user shell, but > its not even the best Unix shell for scripting (Thats probably ksh). > D? Who actually uses D? I think your informant was not well informed. Ah, flame wars over which is the best language :) I don't know enough about ksh to compare it to bash, but at least you didn't recommend csh :) http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/ But frankly, all the shell languages are pretty horrible. D might not be a popular language, but it is a modern, advanced language in the C family, influenced heavily by Python. If I were to learn a new statically typed procedural/object-oriented language, I'd seriously consider learning D. http://en.wikipedia.org/wiki/D_(programming_language) But it really depends on why you are learning the language. Are you learning a language because you need it for a specific job or project? Then learn whatever language you need, because you need it, regardless of whether it is widespread or not. Are you learning a language because you want to maximize your chances of getting a job? Then learn one of the big commercial languages like VB, C, C++, PHP, Javascript or Java. You won't learn to be a better programmer, you may learn to be a *worse* programmer, and you might be competing with thousands of code monkeys, but there are plenty of jobs available. Are you learning a language because you want to get the highest paid job? Then become an expert in an old language like PL/I or Fortran or something, and do it 30 years ago so you can claim 30 years experience. Now, if you can find a job -- and good luck with that -- you can pretty much set your own rate. Do you want to learn a new language for the love of learning languages? Then learn a wide variety of languages. Do you want to expand your skill-set (good for the resume!) and open your mind to new programming concepts? Then learn a variety of languages using many different programming paradigms: * procedural * declarative * functional * logic/deductive * object-oriented * stack-based * concatenative * concurrent * natural language programming * esoteric languages etc. Even if you don't have the time to learn the language, learn ABOUT the language. You will never say, "Gosh, I wish I knew FEWER programming languages!" -- Steven From andreas.perstinger at gmx.net Sat Oct 8 11:11:51 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 08 Oct 2011 11:11:51 +0200 Subject: [Tutor] swapping list elements based on some criterion In-Reply-To: References: <4E8FE4D4.2060508@pearwood.info> Message-ID: <4E9013D7.6080306@gmx.net> On 2011-10-08 09:53, Peter Otten wrote: > Emad Nawfal (??? ???? ???) wrote: >> Here is the function as I used it, and it works fine: >> >> def swap(sentence): >> buffer = [] >> adjectives = [] >> for word in sentence.split(): >> if word.endswith('/ADJ'): >> adjectives.append(word) >> elif word.endswith('/N'): >> buffer.append(word) >> buffer.extend(adjectives) >> >> adjectives = [] >> else: >> buffer.append(word) >> return ' '.join(buffer) > > Does the classification scheme allow for adjectives that are not followed by > a noun? Example: if "good" in the sentence "That looks good" were classified > as an adjective it would be silently dropped. As far as I know, adjectives are always in front of a noun in English. Therefore I suggest iterating backwards and everytime you come across a noun check if it is preceded by an adjective and swap the positions. Iterating backwards is necessary for cases where more than one adjective is in front of the noun. So the noun "floats" towards the beginning of the sentence while all adjectives without nouns (or behind nouns - I don't know if that's possible in English) will stay where they are: def swap(sentence): s = sentence.split() for i in reversed(range(len(s))): if s[i].endswith("/N") and s[i-1].endswith("/ADJ"): s[i], s[i-1] = s[i-1], s[i] return s >>> swap("the/DET tall/ADJ man/N plays/VBZ well/ADV") ['the/DET', 'man/N', 'tall/ADJ', 'plays/VBZ', 'well/ADV'] >>> swap("That/DET looks/VBZ good/ADJ") ['That/DET', 'looks/VBZ', 'good/ADJ'] >>> swap("He/P is/VBZ a/ART big/ADJ old/ADJ man/N who/P went/VBZ crazy/ADJ") ['He/P', 'is/VBZ', 'a/ART', 'man/N', 'big/ADJ', 'old/ADJ', 'who/P', 'went/VBZ', 'crazy/ADJ'] Bye, Andreas From emadnawfal at gmail.com Sat Oct 8 11:31:51 2011 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXZgCDZhtmI2YHZhCDZgNin2K8p?=) Date: Sat, 8 Oct 2011 12:31:51 +0300 Subject: [Tutor] swapping list elements based on some criterion In-Reply-To: <4E9013D7.6080306@gmx.net> References: <4E8FE4D4.2060508@pearwood.info> <4E9013D7.6080306@gmx.net> Message-ID: On Sat, Oct 8, 2011 at 12:11 PM, Andreas Perstinger < andreas.perstinger at gmx.net> wrote: > On 2011-10-08 09:53, Peter Otten wrote: > >> Emad Nawfal (??? ???? ???) wrote: >> >>> Here is the function as I used it, and it works fine: >>> >>> def swap(sentence): >>> buffer = [] >>> adjectives = [] >>> for word in sentence.split(): >>> if word.endswith('/ADJ'): >>> adjectives.append(word) >>> elif word.endswith('/N'): >>> buffer.append(word) >>> buffer.extend(adjectives) >>> >>> adjectives = [] >>> else: >>> buffer.append(word) >>> return ' '.join(buffer) >>> >> >> Does the classification scheme allow for adjectives that are not followed >> by >> a noun? Example: if "good" in the sentence "That looks good" were >> classified >> as an adjective it would be silently dropped. >> > > As far as I know, adjectives are always in front of a noun in English. > Therefore I suggest iterating backwards and everytime you come across a noun > check if it is preceded by an adjective and swap the positions. Iterating > backwards is necessary for cases where more than one adjective is in front > of the noun. So the noun "floats" towards the beginning of the sentence > while all adjectives without nouns (or behind nouns - I don't know if that's > possible in English) will stay where they are: > > def swap(sentence): > s = sentence.split() > for i in reversed(range(len(s))): > if s[i].endswith("/N") and s[i-1].endswith("/ADJ"): > s[i], s[i-1] = s[i-1], s[i] > return s > > >>> swap("the/DET tall/ADJ man/N plays/VBZ well/ADV") > ['the/DET', 'man/N', 'tall/ADJ', 'plays/VBZ', 'well/ADV'] > > >>> swap("That/DET looks/VBZ good/ADJ") > ['That/DET', 'looks/VBZ', 'good/ADJ'] > > >>> swap("He/P is/VBZ a/ART big/ADJ old/ADJ man/N who/P went/VBZ > crazy/ADJ") > ['He/P', 'is/VBZ', 'a/ART', 'man/N', 'big/ADJ', 'old/ADJ', 'who/P', > 'went/VBZ', 'crazy/ADJ'] > > Bye, Andreas > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Thanks Andreas and Peter. Andreas's solution works perfect for me as it takes care of non-qualitative adjectives. I now have enough information to get started on my little project. Hope you don't mind my coming back to you if something comes up. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Sat Oct 8 11:34:19 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 08 Oct 2011 11:34:19 +0200 Subject: [Tutor] swapping list elements based on some criterion In-Reply-To: <4E9013D7.6080306@gmx.net> References: <4E8FE4D4.2060508@pearwood.info> <4E9013D7.6080306@gmx.net> Message-ID: <4E90191B.4010706@gmx.net> On 2011-10-08 11:11, Andreas Perstinger wrote: > def swap(sentence): > s = sentence.split() > for i in reversed(range(len(s))): > if s[i].endswith("/N") and s[i-1].endswith("/ADJ"): > s[i], s[i-1] = s[i-1], s[i] > return s Oops, noticed a little bug: The for-loop should be "for i in reversed(range(1, len(s))):" so that sentences starting with a noun get processed correctly: >>> swap("Joe/N went/VBZ crazy/ADJ") ['Joe/N', 'went/VBZ', 'crazy/ADJ'] Bye, Andreas From alan.gauld at btinternet.com Sat Oct 8 12:27:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 08 Oct 2011 11:27:54 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On 08/10/11 04:34, lina wrote: > print(summary) ### output is [1,3,5,6] > summary='\n'.join(str(summary).split(',')) This line is wrong. This is converting summary to a string -> '[1,3,5,6]' Then splitting by commas to create a new list -> [ '[1', '3', '5', 6]' ] Notice the first and last elements have the [] Then it joins then into a string using \n as seperators. What you want, I think, is to join the original list with spaces(and maybe add a newline for writing to file) summary = ' '.join(summary) + \n > with open(base+OUTFILEEXT,"w") as f: > f.write(str(summary)) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Oct 8 12:37:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 08 Oct 2011 11:37:45 +0100 Subject: [Tutor] Runtime error while Test data creation In-Reply-To: References: <4E8F629B.606@gmail.com> Message-ID: On 07/10/11 22:32, Guess?!? wrote: > Thanks for the suggestions. There is no traceback/stacktrace errors that > I can see The key is the last phrase. Your GUI IDE is hiding it. If you run your program from an Operating Command prompt then you should see the full error stack trace which (usually) contains a lot of useful information. > The run time error pops up in a windows dialog box with a text I wrote > below in my first email and closing the dialog box closes the IDLE GUI > python. IDLE is good for many things but sadly displaying error messages is not one of them. Run it from a command prompt. In fact that's good advice with any IDE in my experience. If an error is hard to debug try running in the native OS and see if anything changes. IDEs bring all sorts of nice tools but in doing so they tend to mess with the execution environment so that things are different from "the real world" environment. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Oct 8 14:05:54 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 08 Oct 2011 23:05:54 +1100 Subject: [Tutor] Runtime error while Test data creation In-Reply-To: References: Message-ID: <4E903CA2.8060909@pearwood.info> Guess?!? wrote: > Hello all, > > I am trying to create some test data for a search module that I am building. > Since I dont want to hit performance related issues late in the game, I > decided to create half a million records in the DB. > > My approach is create a csv file with valid UUIDs which I already have. Read > each record from csv and generate random data and do DB insert as long the > csv file has records in them. This crashes near 100000 record insertions. > > The problem is that my program eventually fails with this error. Any ideas > what I can improve to make it go all the way? > > Runtime Error! > Program: C:\Python27\pythonw.exe > This app has requested the Runtime to terminate it in an unusual way. Please > contact application support team You should try to identify the actual error. That probably means running the script directly in Python, using the command line, so as to avoid unhelpful error messages like the above. Are you using IDLE or some other IDE? They usually make debugging much harder. Try just running the script directly from the command line. If you have Windows: Start menu > Run Type "cmd" [enter] Type "C:\python26\python.exe myscript.py" [enter] You may have to change the pathname to the Python executable, if you are using a different version, or I might have just got it wrong. And of course change "myscript.py" to the name of your script. > Here is the code that I wrote to do this. Please do not send code using HTML or "rich text", because it messes up the formatting of the code and makes it difficult or impossible to tell what it actually does. -- Steven From emadnawfal at gmail.com Sat Oct 8 14:18:33 2011 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXZgCDZhtmI2YHZhCDZgNin2K8p?=) Date: Sat, 8 Oct 2011 15:18:33 +0300 Subject: [Tutor] swapping list elements based on some criterion In-Reply-To: <4E90191B.4010706@gmx.net> References: <4E8FE4D4.2060508@pearwood.info> <4E9013D7.6080306@gmx.net> <4E90191B.4010706@gmx.net> Message-ID: On Sat, Oct 8, 2011 at 12:34 PM, Andreas Perstinger < andreas.perstinger at gmx.net> wrote: > On 2011-10-08 11:11, Andreas Perstinger wrote: > >> def swap(sentence): >> s = sentence.split() >> for i in reversed(range(len(s))): >> if s[i].endswith("/N") and s[i-1].endswith("/ADJ"): >> s[i], s[i-1] = s[i-1], s[i] >> return s >> > > Oops, noticed a little bug: > > The for-loop should be "for i in reversed(range(1, len(s))):" so that > sentences starting with a noun get processed correctly: > > >>> swap("Joe/N went/VBZ crazy/ADJ") > ['Joe/N', 'went/VBZ', 'crazy/ADJ'] > > Thanks again Andreas > Bye, Andreas > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Sat Oct 8 15:17:54 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 21:17:54 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E900D2F.70702@pearwood.info> References: <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <4E900D2F.70702@pearwood.info> Message-ID: On Sat, Oct 8, 2011 at 4:43 PM, Steven D'Aprano wrote: > Alan Gauld wrote: > >> On 07/10/11 16:40, lina wrote: >> >> but today I was also discouraged, I was told that you should not have >>> learned python, you should focus on C or bash, or D, cause python is >>> going to be obsolete, >>> >> >> C is a great language for writing Operating Systems and other "near the >> metal" code. But its not the best language for busiess apps, artificial >> intelligence and a host of other things. Bash is a good user shell, but its >> not even the best Unix shell for scripting (Thats probably ksh). >> D? Who actually uses D? I think your informant was not well informed. >> > > > Ah, flame wars over which is the best language :) > > I don't know enough about ksh to compare it to bash, but at least you > didn't recommend csh :) > > http://www.faqs.org/faqs/unix-**faq/shell/csh-whynot/ > > But frankly, all the shell languages are pretty horrible. > > D might not be a popular language, but it is a modern, advanced language in > the C family, influenced heavily by Python. If I were to learn a new > statically typed procedural/object-oriented language, I'd seriously consider > learning D. > > http://en.wikipedia.org/wiki/**D_(programming_language) > > But it really depends on why you are learning the language. > > Are you learning a language because you need it for a specific job or > project? Then learn whatever language you need, because you need it, > regardless of whether it is widespread or not. > > Are you learning a language because you want to maximize your chances of > getting a job? Then learn one of the big commercial languages like VB, C, > C++, PHP, Javascript or Java. You won't learn to be a better programmer, you > may learn to be a *worse* programmer, and you might be competing with > thousands of code monkeys, but there are plenty of jobs available. > > Are you learning a language because you want to get the highest paid job? > Then become an expert in an old language like PL/I or Fortran or something, > and do it 30 years ago so you can claim 30 years experience. Now, if you can > find a job -- and good luck with that -- you can pretty much set your own > rate. > > Do you want to learn a new language for the love of learning languages? > Then learn a wide variety of languages. > > Do you want to expand your skill-set (good for the resume!) and open your > mind to new programming concepts? Then learn a variety of languages using > many different programming paradigms: > > * procedural > * declarative > * functional > * logic/deductive > * object-oriented > * stack-based > * concatenative > * concurrent > * natural language programming > * esoteric languages > > etc. > > Even if you don't have the time to learn the language, learn ABOUT the > language. > > You will never say, "Gosh, I wish I knew FEWER programming languages!" > Ha Ha ... Today I also talked with someone who had 20 years computation experience, what I was told is that writing the algorithm is the most challenge things than language its own. regarding the python and C, I was told that python is good for interface and others, but slow. and further was suggested to write the main part in C and wrapped in python. so complicated for me to achieve at present I guess. Thanks > > > > -- > Steven > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Sat Oct 8 15:18:36 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 21:18:36 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On Sat, Oct 8, 2011 at 6:27 PM, Alan Gauld wrote: > On 08/10/11 04:34, lina wrote: > > print(summary) ### output is [1,3,5,6] >> summary='\n'.join(str(summary)**.split(',')) >> > > This line is wrong. > This is converting summary to a string -> '[1,3,5,6]' > Then splitting by commas to create a new list -> [ '[1', '3', '5', 6]' ] > Notice the first and last elements have the [] > Then it joins then into a string using \n as seperators. > > What you want, I think, is to join the original list > with spaces(and maybe add a newline for writing to file) > You are right! > > > summary = ' '.join(summary) + \n > > > Just correct. > with open(base+OUTFILEEXT,"w") as f: >> f.write(str(summary)) >> > > HTH, Thanks, it's helpful. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Sat Oct 8 15:30:17 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 8 Oct 2011 21:30:17 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On Sat, Oct 8, 2011 at 6:27 PM, Alan Gauld wrote: > On 08/10/11 04:34, lina wrote: > > print(summary) ### output is [1,3,5,6] >> summary='\n'.join(str(summary)**.split(',')) >> > > This line is wrong. > This is converting summary to a string -> '[1,3,5,6]' > Then splitting by commas to create a new list -> [ '[1', '3', '5', 6]' ] > Notice the first and last elements have the [] > Then it joins then into a string using \n as seperators. > > What you want, I think, is to join the original list > with spaces(and maybe add a newline for writing to file) > > > summary = ' '.join(summary) + \n sorry, just correct forget testing, Traceback (most recent call last): File "counter-vertically-WORKING.py", line 32, in new_summary=''.join((summary[1:-3]))+"\n" TypeError: sequence item 0: expected str instance, int found so new_summary=''.join(str(summary[1:-3]))+"\n" but the results seems as summary[1:-3], still has [ ] and not in new lines. Thanks, > > > with open(base+OUTFILEEXT,"w") as f: >> f.write(str(summary)) >> > > HTH, > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Oct 8 16:50:52 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 08 Oct 2011 15:50:52 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On 08/10/11 11:27, Alan Gauld wrote: > What you want, I think, is to join the original list > with spaces(and maybe add a newline for writing to file) > > summary = ' '.join(summary) + \n But you need to make the original items strings first so it should be: summary = ' '.join( map(str,summary) ) + \n Sorry about that, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Oct 8 17:34:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 08 Oct 2011 16:34:33 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <4E900D2F.70702@pearwood.info> Message-ID: On 08/10/11 14:17, lina wrote: > You will never say, "Gosh, I wish I knew FEWER programming languages!" > Ha Ha ... > > regarding the python and C, I was told that python is good for interface > and others, but slow. and further was suggested to write the main part > in C and wrapped in python. The myth that Python (and interpreted languages in general) are too slow for "real programming" is common among older programmers(*) who were trained on old computers like the original PC and servers like the DEC PDP series. When I left university our office had just acquired the largest, most powerful VAX computer in Europe - it ran at 12MHz and had 16MB of RAM and supported over 100 users! Wow! However many. many, applications can now be written in interpreted languages and run fast enough (and the key word is "enough"). If you really need the last bit of speed then yes, C (or even assembler) may be needed, but that is a tiny proportion of the code for most things. So to take your friends comment and turn it around: "... write the main part in Python (or .NET or Java or...) and write the speed critical parts in C." Because typically the Python part is likely to be 70-90% of the code and the C part much less. (*)I tend to consider myself in that group and up until about 15 years ago held the same view. But around then I got involved in projects using languages like Smalltalk, Tcl/Tk and VB. It was obvious that these languages were perfectly capable of producing usable apps on the typical hardware of the time - early Pentiums running at around 500MHz and with 128M RAM etc. Nowadays with most PCs having processors running in excess of 2GHz and over 2GB RAM there are very few apps that cannot be constructed using interpreted languages, and many are. I suspect the reason most commercial projects still use Java, C++ etc is twofold: 1) Magazines etc tend to review apps against their competition on speed, even if the real world speed measures are irrelevant. So for marketing purposes you must be seen to be comparable to your competitors. 2) Compiled code is harder for the competition to reverse engineer so coding secrets are 'safer'. (This is largely psychological since its the design concepts your competitors are more likely to steal, not the algorithmic details.) There are projects where ultimate speed is still important, indeed one of my current projects at work is being largely rewritten from C#.Net to compiled C++ for exactly that reason. (But it is a number crunching server app supporting around 15000 concurrent users) But the vast bulk of user programs could be written in interpreted languages IMHO. One of the interesting things about my recent conversion from Windows to Linux for my home PC is to see just how many of the desktop apps are written in Python, including games and office apps etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Sat Oct 8 18:20:03 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 9 Oct 2011 00:20:03 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: On Sat, Oct 8, 2011 at 10:50 PM, Alan Gauld wrote: > On 08/10/11 11:27, Alan Gauld wrote: > > What you want, I think, is to join the original list >> with spaces(and maybe add a newline for writing to file) >> >> summary = ' '.join(summary) + \n >> > > But you need to make the original items strings first > so it should be: > > summary = ' '.join( map(str,summary) ) + \n > new_summary=' '.join( map(str,summary) ) + \n ^ SyntaxError: unexpected character after line continuation character so I added it as new_summary=' '.join( map(str,summary[1:-3]) ) + "\n" but each one in summary does not show in new line. new_summary='\n'.join(map(str,summary[1:-3])) This one works, > > Sorry about that, Thanks for your suggestions. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Sat Oct 8 18:51:14 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 9 Oct 2011 00:51:14 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <4E900D2F.70702@pearwood.info> Message-ID: On Sat, Oct 8, 2011 at 11:34 PM, Alan Gauld wrote: > On 08/10/11 14:17, lina wrote: > > You will never say, "Gosh, I wish I knew FEWER programming languages!" >> Ha Ha ... >> >> regarding the python and C, I was told that python is good for interface >> and others, but slow. and further was suggested to write the main part >> in C and wrapped in python. >> > > The myth that Python (and interpreted languages in general) are too slow > for "real programming" is common among older programmers(*) who were trained > on old computers like the original PC and servers like the DEC PDP series. > When I left university our office had just acquired the largest, most > powerful VAX computer in Europe - it ran at 12MHz and had 16MB of RAM and > supported over 100 users! Wow! However many. many, applications can now be > written in interpreted languages and run fast enough (and the key word is > "enough"). > Wow .. I used to hate slow computer. Now I won't hate the retard (slow reaction) lab computers any more. (It's a joke) When I was in college, I needed to copy assignment to print it out. I used floppy driver at that time, and the stores in campus put the floppy driver near the cashier place with the gum and other candies. Now the gum and other candies I guess are still there, but no floppy driver any more, but probably some CDs or DVDs. > > If you really need the last bit of speed then yes, C (or even assembler) > may be needed, but that is a tiny proportion of the code for most things. So > to take your friends comment and turn it around: > > "... write the main part in Python (or .NET or Java or...) and write the > speed critical parts in C." > > Because typically the Python part is likely to be 70-90% of the code > and the C part much less. > > (*)I tend to consider myself in that group and up until about 15 years ago > held the same view. But around then I got involved in projects using > languages like Smalltalk, Tcl/Tk and VB. It was obvious that these languages > were perfectly capable of producing usable apps > on the typical hardware of the time - early Pentiums running at > around 500MHz and with 128M RAM etc. Nowadays with most PCs having > processors running in excess of 2GHz and over 2GB RAM there are very few > apps that cannot be constructed using interpreted languages, and many are. I > suspect the reason most commercial projects still use Java, C++ etc is > twofold: > 1) Magazines etc tend to review apps against their competition on speed, > even if the real world speed measures are irrelevant. So for marketing > purposes you must be seen to be comparable to your competitors. > 2) Compiled code is harder for the competition to reverse engineer so > coding secrets are 'safer'. (This is largely psychological since its the > design concepts your competitors are more likely to steal, not the > algorithmic details.) > > There are projects where ultimate speed is still important, indeed one of > my current projects at work is being largely rewritten from C#.Net to > compiled C++ for exactly that reason. (But it is a number crunching server > app supporting around 15000 concurrent users) But the vast bulk of user > programs could be written in interpreted languages IMHO. One of the > interesting things about my recent conversion from Windows to Linux for my > home PC is to see just how many of the desktop apps are written in Python, > including games and office apps etc. > My initiative to learn python is that I noticed some (often used) apps are written in python. Another reason is that I want to learn (at least) one language deeper and seriously (hopeful to have a happy ending in learning). Thanks, I have forwarded this email to my friend. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Sat Oct 8 19:18:44 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 9 Oct 2011 01:18:44 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <4E900D2F.70702@pearwood.info> Message-ID: On Sat, Oct 8, 2011 at 11:34 PM, Alan Gauld wrote: > On 08/10/11 14:17, lina wrote: > > You will never say, "Gosh, I wish I knew FEWER programming languages!" >> Ha Ha ... >> >> regarding the python and C, I was told that python is good for interface >> and others, but slow. and further was suggested to write the main part >> in C and wrapped in python. >> > > The myth that Python (and interpreted languages in general) are too slow > for "real programming" is common among older programmers(*) who were trained > on old computers like the original PC and servers like the DEC PDP series. > When I left university our office had just acquired the largest, most > powerful VAX computer in Europe - it ran at 12MHz and had 16MB of RAM and > supported over 100 users! Wow! However many. many, applications can now be > written in interpreted languages and run fast enough (and the key word is > "enough"). > > If you really need the last bit of speed then yes, C (or even assembler) > may be needed, but that is a tiny proportion of the code for most things. So > to take your friends comment and turn it around: > > "... write the main part in Python (or .NET or Java or...) and write the > speed critical parts in C." > > Because typically the Python part is likely to be 70-90% of the code > and the C part much less. > > (*)I tend to consider myself in that group and up until about 15 years ago > held the same view. But around then I got involved in projects using > languages like Smalltalk, Tcl/Tk and VB. It was obvious that these languages > were perfectly capable of producing usable apps > on the typical hardware of the time - early Pentiums running at > around 500MHz and with 128M RAM etc. Nowadays with most PCs having > processors running in excess of 2GHz and over 2GB RAM there are very few > apps that cannot be constructed using interpreted languages, and many are. I > suspect the reason most commercial projects still use Java, C++ etc is > twofold: > 1) Magazines etc tend to review apps against their competition on speed, > even if the real world speed measures are irrelevant. So for marketing > purposes you must be seen to be comparable to your competitors. > 2) Compiled code is harder for the competition to reverse engineer so > coding secrets are 'safer'. (This is largely psychological since its the > design concepts your competitors are more likely to steal, not the > algorithmic details.) > > There are projects where ultimate speed is still important, indeed one of > my current projects at work is being largely rewritten from C#.Net to > compiled C++ for exactly that reason. (But it is a number crunching server > app supporting around 15000 concurrent users) But the vast bulk of user > programs could be written in interpreted languages IMHO. One of the > interesting things about my recent conversion from Windows to Linux for my > home PC is to see just how many of the desktop apps are written in Python, > including games and office apps etc. > Here is the feedback:" He is certainly right and we are agree: I have to choose a program language because I cannot afford to learn a lot of them; when I have to choose it was early age compare to today; I do not really care about interface (a good command line interface is enough that can use (BASH/DASH) script and can be incorporated in (BASH/DASH) script is enough for me); I write mainly critical speed code and large memory code that are meant to run as hug jobs over cluster (transportability is an issue; my C code is really faster than my Maple code; interpreter language are good for development of algorithm in view to write a fast C code; speed does not involved human time but machine time; I do not really care about candy interfaces; for human interface Python and alike are recommended but BASH (and even DASH) can do very good job; I am not sure that a scientist is more concerned with interface than with efficient code except for visual stuff; being very familiar with of a given language is certainly better than knowing superficially a lot of languages; as a lot of interpreter languages, Python has a huge manual; C manual is rather small; D is both a interpreter language and a compiler language: it is why I want to learn D: no more need to write wrapper that can be boring and that can be bottle neck. Last, enter in the game rather than watching. Then you can get your opinion. According to the question in the Subject, I guess that you still have a lot to learn before to appreciate all this subtilitises. " I kept the content of the email intact. Thanks, > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Sat Oct 8 19:45:56 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 8 Oct 2011 18:45:56 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> Message-ID: Lina, Just a couple of comments on the topic of Python vs other languages to add to what others have said: On 7 October 2011 16:40, lina wrote: > but today I was also discouraged, I was told that you should not have > learned python, you should focus on C or bash, or D, cause python is going > to be obsolete, and I defensed that I saw lots people/apps using python, and > it's always good to learn a language well, it's helpful for you to > understand another language. I was further told that fortran is obsolete, > but still lots of fortran guys using it. > I don't know much, since I started and wanted to learn, actually I wish to > hear some encouraging words, not some words discouraging, but on another > hands, it's always good to have an open mind, so I want to hear your opinion > and perspective, I am not knowledgable about this. > I'd say rather than being obsolete, Python is, if anything, on the ascendancy. My own personal opinion as someone who has been in this game for a while now and know (for various levels of know) quite a number languages (e.g. off the top of my head: C, C++, Java, C#, Pascal, Delphi, Oberon, Python, VB, sql, prolog, Lisp, bash, awk), is that Python is (generally speaking) one of the "best" languages I've had the pleasure to work with. By "best" here I mean that it's useful and available in more contexts than most of the others, it's better at encouraging good programming practices, the included as well as third party libraries are very comprehensive, and usually as good as or better than many of the other languages I've tried, etc etc, it's fast enough [and in this context I'd point at the multiple implementations (CPython, IronPython, Jython, PyPy etc) as a further advantage, not to mention the fact that you can still fall back to writing Python modules in C if need be.], it's highly productive, it keeps you close to the problem domain and usually doesn't burden you with lower level details, etc etc. Addiontally, you might be interested to know that Python is used as one of Google's core 3 languages, as well as being extensively used in several Linux distributions as a system utility programming language (for example Redhat, Ubuntu.) So, for all these reasons (and probably many others I've not mentioned) I again suggest it's rather a stretch to claim Python is "obsolete". (I'd addtionally ask, what does something being "obsolete" mean anyway? If lots of people use a languages, is it not then by definition not obsolete?) I'll also point you at some stats which I dug up (for entertainment value, or maybe you can use it to counter some of your friend's claims of obsolescence etc.) 1) According to langpop.com, Python is overall the 6th most popular language, ahead of C# at no. 7. D only comes in at no. 28. (C is at no.1) There's several ranking listss, and Python is in fact no.1 one on a couple (the programming.reddit.com ranking and the IRC ranking). For more see here: http://langpop.com/ 2) On the TIOBE Programming Community Index (Sept. 2011) Python is similarly ranked at no. 8. D only re-entered the table recently at no. 20. For more see here: http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html Hope that helps, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Sat Oct 8 20:20:29 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sat, 8 Oct 2011 18:20:29 +0000 Subject: [Tutor] START-UP PROJECT Message-ID: <1857200442-1318098023-cardhu_decombobulator_blackberry.rim.net-2001899392-@b18.c12.bise7.blackberry> Hi all, I have been coding python for a while but I just can't get to rate myself. I have been part of few projects that are python based and did a pretty good job with other team mates. I however want to step up my game and make python my core competence; the challenge I have is what project to embark on. I really can't figure out what project to take on but would be prepared to take on anything and get my hand dirtier than before. Kindly put forth suggestions. I wouldn't mind being pushed to the extreme. I just want something to work on. Thanks as I look forward to your thoughts. Cheers. Sent from my BlackBerry wireless device from MTN From amonroe at columbus.rr.com Sat Oct 8 20:59:43 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 8 Oct 2011 14:59:43 -0400 Subject: [Tutor] START-UP PROJECT In-Reply-To: <1857200442-1318098023-cardhu_decombobulator_blackberry.rim.net-2001899392-@b18.c12.bise7.blackberry> References: <1857200442-1318098023-cardhu_decombobulator_blackberry.rim.net-2001899392-@b18.c12.bise7.blackberry> Message-ID: <144419652758.20111008145943@columbus.rr.com> > I really can't figure out what project to take on but would be > prepared to take on anything and get my hand dirtier than before. Popular ones are: http://www.pythonchallenge.com/ http://projecteuler.net/ I also like: http://www.atariarchives.org/basicgames/ http://www.atariarchives.org/morebasicgames/ http://cplus.about.com/od/programmingchallenges/Programming_Challenges.htm Alan From g.nius.ck at gmail.com Sat Oct 8 21:03:33 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Sat, 8 Oct 2011 15:03:33 -0400 Subject: [Tutor] String switch In-Reply-To: <4E8DCB8C.6090301@gmail.com> References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> <4E8DCB8C.6090301@gmail.com> Message-ID: Okay, here's what I what to do *--Target.py--* print "Hello World" *--Target.py Output--* *Hello World* *--Main.py--* target=open("target.py", "r") old=target.read() target.close() target=open("target.py", "w") target.write(''' Str.__repr__ = Str.__repr__.swapcase()'''+old) target.close() *--Modified Target.py--* Str.__repr__ = Str.__repr__.swapcase() print "Hello World" *--Modified Target.py Output--* *hELLO wORLD* The only problem is I don't think that "Str.__repr__ = Str.__repr__.swapcase()" works. What should I use in its place to make the above a reality. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Oct 8 22:18:57 2011 From: d at davea.name (Dave Angel) Date: Sat, 08 Oct 2011 16:18:57 -0400 Subject: [Tutor] String switch In-Reply-To: References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> <4E8DCB8C.6090301@gmail.com> Message-ID: <4E90B031.4090304@davea.name> On 10/08/2011 03:03 PM, Christopher King wrote: > Okay, here's what I what to do > *--Target.py--* > print "Hello World" > *--Target.py Output--* > *Hello World* > *--Main.py--* > target=open("target.py", "r") > old=target.read() > target.close() > target=open("target.py", "w") > target.write(''' > Str.__repr__ = Str.__repr__.swapcase()'''+old) > target.close() > *--Modified Target.py--* > Str.__repr__ = Str.__repr__.swapcase() > print "Hello World" > *--Modified Target.py Output--* > *hELLO wORLD* > > The only problem is I don't think that "Str.__repr__ = > Str.__repr__.swapcase()" works. What should I use in its place to make the > above a reality. > That certainly won't work in Python 2.x, since Str isn't a defined symbol. In any case, I can't see what you intended it to do, since __repr__ isn't called anywhere in that code. What are your constraints? Which Python version? Are the only allowable changes a prefix to the code in the input file? What strings do you want modified, only those inside literals, or those that are generated by the program? For example, if the program says x = raw_input("What's your name"); print x do you want that prompt string swapcased as well? What about the name the person types in? How about a program like z = 3.14 print z.hex() Do you want the output changed from 0x1.91eb851eb851fp+1 to 0X1.91EB851EB851FP+1 ? Do you only want things swapped that are printed with "print", or do you want anything that goes to stdout? What about things that are written to file? What about things that are written to a file, but that file happens to be stdout ? Or vice versa? There are lots of other possible questions, but perhaps that's enough to convince you that you haven't begun to specify what you want. -- DaveA From wprins at gmail.com Sat Oct 8 22:36:20 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 8 Oct 2011 21:36:20 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <1769514952-1318096541-cardhu_decombobulator_blackberry.rim.net-755081903-@b18.c12.bise7.blackberry> References: <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C4BE6.9040908@davea.name> <4E8C5DDA.4060906@davea.name> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <1769514952-1318096541-cardhu_decombobulator_blackberry.rim.net-755081903-@b18.c12.bise7.blackberry> Message-ID: Hi Lina, On 8 October 2011 18:18, lina wrote: > I write mainly critical speed code and large memory code that are meant to > run as hug jobs over cluster (transportability is an issue; > my C code is really faster than my Maple code; interpreter language are > good for development of algorithm in view to write a fast C code; > speed does not involved human time but machine time; I do not really care > about candy interfaces; for human interface Python and alike are recommended > but BASH (and even DASH) can do very good job; I am not sure that a > scientist is more concerned with interface than with efficient code except > for > visual stuff; being very familiar with of a given language is certainly > better than knowing superficially a lot of languages; > as a lot of interpreter languages, Python has a huge manual; C manual is > rather small; D is both a interpreter language and a compiler language: > it is why I want to learn D: no more need to write wrapper that can be > boring and that can be bottle neck. > I should think that the Core Python *language* manual is almost certainly smaller than the C one. (The base Python language is actually rather small and concise. What typically makes Python books larger in general is I think actually the (so called "batteries included") extensive set of libraries and modules included and commonly available for the language, not the Python language itself.) As for the compiler/interpreter argument, I'll just point out again that actually Python in its various forms can either be compiled and/or interepreted, it depends on you really. For compiled Python flavours, see for example Cython (http://cython.org/) which provides a way to write C/C++ modules for Python effectively in Python syntax. (Cython arguably also makes the "need to write wrapper" comment a moot point.) Or see Shedskin ( http://shed-skin.blogspot.com/), a Python to C++ static compiler), or Psyco (http://psyco.sourceforge.net/introduction.html ), a JIT (Just In Time) compiler for CPython. Or see Pypy (http://pypy.org/) which is another reimplementation of the Python language with an optimizing JIT compiler. (The following post re realtime image processing in Python is rather impressive: http://morepypy.blogspot.com/2011/07/realtime-image-processing-in-python.html) I'd like to also mention that there's many many Python packages of interest or used by the scientific community, not least NumPy/SciPy ( http://numpy.scipy.org/ and http://www.scipy.org/). For a more complete list see: http://www.scipy.org/Topical_Software You'll see that Python is used extensively in many science and engineering contexts. Lastly regarding (user) interfaces -- as has already been pointed out, Python can obviously do UI's, but it's by no means limited to being some sort of front-end language. Anyway, I think I'll leave it at that for now. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Oct 9 02:45:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 09 Oct 2011 01:45:40 +0100 Subject: [Tutor] START-UP PROJECT In-Reply-To: <1857200442-1318098023-cardhu_decombobulator_blackberry.rim.net-2001899392-@b18.c12.bise7.blackberry> References: <1857200442-1318098023-cardhu_decombobulator_blackberry.rim.net-2001899392-@b18.c12.bise7.blackberry> Message-ID: On 08/10/11 19:20, delegbede at dudupay.com wrote: > I have been coding python for a while but I just can't get to rate myself. > I have been part of few projects that are python based and did a pretty > good job with other team mates. OK, You probably don't need the Python tutor list then :-) Have you tried asking for ideas on the main python language list (aka comp.lang.python) > I however want to step up my game and make python my core competence; > the challenge I have is what project to embark on. > I really can't figure out what project to take on Pick one you are interested in. And don;t worry so much about Python being your core competence, make it programming. There are far more opportunities that way. > I just want something to work on. Go to SourceForge, search for Python projects. Pick one you find interesting. Get involved. Or alternatively look at the jobs adverts and apply for some. Ask for feedback after interviews, that's a pretty good way to rate yourself. If somebody is willing to pay you then they must rate you! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Sun Oct 9 04:40:15 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 08 Oct 2011 22:40:15 -0400 Subject: [Tutor] START-UP PROJECT In-Reply-To: <1857200442-1318098023-cardhu_decombobulator_blackberry.rim.net-2001899392-@b18.c12.bise7.blackberry> References: <1857200442-1318098023-cardhu_decombobulator_blackberry.rim.net-2001899392-@b18.c12.bise7.blackberry> Message-ID: <4E91098F.1010003@gmail.com> On 10/8/2011 2:20 PM, delegbede at dudupay.com wrote: > Hi all, > > I have been coding python for a while but I just can't get to rate myself. > > I have been part of few projects that are python based and did a pretty good job with other team mates. > > I however want to step up my game and make python my core competence; the challenge I have is what project to embark on. > > I really can't figure out what project to take on but would be prepared to take on anything and get my hand dirtier than before. > > Kindly put forth suggestions. I wouldn't mind being pushed to the extreme. I just want something to work on. I've been developing (for a long time) an open-source Python implementation of IBM's CMS/TSO Pipelines. I don't have any project pages or web site to point you to, just the IBM documentation which I seek to (incrementally) meet. Take a look at http://publibfp.dhe.ibm.com/epubs/pdf/dfsc4a01.pdf. Chapter 1 is a good starting place. There are references to mainframe-specific stuff that you may safely ignore. If this inspires you or not, let me know. I would enjoy some partnership working on this. -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Sun Oct 9 05:08:38 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Oct 2011 14:08:38 +1100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <1769514952-1318096541-cardhu_decombobulator_blackberry.rim.net-755081903-@b18.c12.bise7.blackberry> Message-ID: <4E911036.7010906@pearwood.info> Walter Prins wrote: > As for the compiler/interpreter argument, I'll just point out again that > actually Python in its various forms can either be compiled and/or > interepreted, it depends on you really. For compiled Python flavours, see > for example Cython (http://cython.org/) which provides a way to write C/C++ > modules for Python effectively in Python syntax. (Cython arguably also > makes the "need to write wrapper" comment a moot point.) Cython is not Python. It is a separate language similar to Python, based on Python, but not actually Python. It's actually a superset of Python. Any Python code should be legal in Cython, but not all Cython code is legal in Python. See, for example: http://docs.cython.org/src/userguide/tutorial.html#primes and notice that the Cython code: def primes(int kmax): cdef int n, k, i cdef int p[1000] # ... gives you a SyntaxError in Python. Credit where credit is due: Cython is a wonderful tool and very useful to anyone wanting to write C extensions for Python, but it isn't Python. That's not a limitation or a bad thing: it couldn't do what it sets out to do if it were Python. > Or see Shedskin ( > http://shed-skin.blogspot.com/), a Python to C++ static compiler), Shedskin, on the other hand, is a subset of Python: it can only work with a restricted set of Python features. So also not Python. http://code.google.com/p/shedskin/ But still a very useful and valuable tool. > or Psyco > (http://psyco.sourceforge.net/introduction.html ), a JIT (Just In Time) > compiler for CPython. Psyco, on the other hand, is an add-on to Python: it runs inside the CPython compiler, as an importable module, rather than being a separate Python interpreter. > Or see Pypy (http://pypy.org/) which is another > reimplementation of the Python language with an optimizing JIT compiler. > (The following post re realtime image processing in Python is rather > impressive: > http://morepypy.blogspot.com/2011/07/realtime-image-processing-in-python.html) PyPy is very impressive, and it truly is an independent implementation of Python, like CPython, Jython, IronPython and Stackless. It is faster than CPython (although requires more memory) and in certain restricted micro-benchmarks faster than C. Yes, faster than C. http://morepypy.blogspot.com/2008/01/rpython-can-be-faster-than-c.html http://morepypy.blogspot.com/2011/02/pypy-faster-than-c-on-carefully-crafted.html http://morepypy.blogspot.com/2011/08/pypy-is-faster-than-c-again-string.html This just goes to show that *languages* aren't faster or slower than other languages. Languages just are. But *implementations* can be faster or slower. -- Steven From ajarncolin at gmail.com Sun Oct 9 07:16:51 2011 From: ajarncolin at gmail.com (col speed) Date: Sun, 9 Oct 2011 12:16:51 +0700 Subject: [Tutor] Crazy craps problem Message-ID: Hi again, Once more I've come up with a problem I can't explain. It must be something simple, but I can't work it out. The part of the script that is causing the problem is as follows: def point(num): while True: raw_input("Roll") uno, dos = random.choice(dice), random.choice(dice) three = uno+dos print "{0} + {1} = {2}".format(uno, dos, three) print "Point is {0}. You scored {1}.".format(num, three) if three == num: return "win" if three == 7: return "lose" else: print "Try again." What I have tried to do is - simulate dice throws, if the total is the same as originally thrown, return from the function(this works). If I throw a 7, I also want to return(this does not work as you can see from this sample output: Try again. Roll 6 + 1 = 7 Point is 4. You scored 7. <--> snip 4 + 1 = 5 Point is 4. You scored 5. Try again. Roll 3 + 4 = 7 Point is 4. You scored 7. You have lost! You have $100 left. As you can see, after throwing a 7, it just continues. It only returns after throwing a second 7. 1. I know it's bad form to print from a function, I'll change it later. 2. I've tried the second if statement using "elif". 3. I've tried omitting the "three" variable and just using "uno" + "dos". 4. I've used "uno" and "dos" because I use "one" and "two" in another part of the script(outside and after the function definition), although they shouldn't be affected in any way. Any help greatly appreciated. Thanks Col -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Sun Oct 9 08:17:15 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sun, 09 Oct 2011 08:17:15 +0200 Subject: [Tutor] Crazy craps problem In-Reply-To: References: Message-ID: <4E913C6B.2010406@gmx.net> On 2011-10-09 07:16, col speed wrote: > The part of the script that is causing the problem is as follows: > > def point(num): > while True: > raw_input("Roll") > uno, dos = random.choice(dice), random.choice(dice) > three = uno+dos > print "{0} + {1} = {2}".format(uno, dos, three) > print "Point is {0}. You scored {1}.".format(num, three) > if three == num: > return "win" > if three == 7: > return "lose" > else: > print "Try again." > > What I have tried to do is - simulate dice throws, if the total is the same > as originally thrown, return from the function(this works). If I throw a 7, > I also want to return(this does not work as you can see from this sample > output: I'm pretty sure that your problem is not in the code snippet you have shown us. Here it works as expected (I've copied your code, added "import random" and "dice = [1, 2, 3, 4, 5, 6]" at the top and saved as "dice.py"): Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import dice >>> dice.point(1) Roll 4 + 5 = 9 Point is 1. You scored 9. Try again. Roll 4 + 3 = 7 Point is 1. You scored 7. 'lose' >>> Please show us the part where you use the "point" function. Bye, Andreas From ajarncolin at gmail.com Sun Oct 9 08:25:48 2011 From: ajarncolin at gmail.com (col speed) Date: Sun, 9 Oct 2011 13:25:48 +0700 Subject: [Tutor] Crazy craps problem In-Reply-To: <4E913C6B.2010406@gmx.net> References: <4E913C6B.2010406@gmx.net> Message-ID: On 9 October 2011 13:17, Andreas Perstinger wrote: > On 2011-10-09 07:16, col speed wrote: > >> The part of the script that is causing the problem is as follows: >> >> def point(num): >> while True: >> raw_input("Roll") >> uno, dos = random.choice(dice), random.choice(dice) >> three = uno+dos >> print "{0} + {1} = {2}".format(uno, dos, three) >> print "Point is {0}. You scored {1}.".format(num, three) >> if three == num: >> return "win" >> if three == 7: >> return "lose" >> else: >> print "Try again." >> >> What I have tried to do is - simulate dice throws, if the total is the >> same >> as originally thrown, return from the function(this works). If I throw a >> 7, >> I also want to return(this does not work as you can see from this sample >> output: >> > > I'm pretty sure that your problem is not in the code snippet you have shown > us. Here it works as expected (I've copied your code, added "import random" > and "dice = [1, 2, 3, 4, 5, 6]" at the top and saved as "dice.py"): > > Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import dice > >>> dice.point(1) > Roll > 4 + 5 = 9 > Point is 1. You scored 9. > Try again. > Roll > 4 + 3 = 7 > Point is 1. You scored 7. > 'lose' > >>> > > Please show us the part where you use the "point" function. > > Bye, Andreas > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Thanks for your prompt reply! Here's the whole thing: import random message = """Welcome to craps!!!! Place your bet and roll the dice. 7 or 11 wins. 2, 3 or 12 loses. Others are "point".""" player = "Your" dice = range(1, 7) stake = 100 bet = 5 winmsg = "You have won!You have ${0} left.".format(stake) losemsg = "You have lost! You have ${0} left.".format(stake) players = ["Your", "My"] def win(num): if num in [7,11]: return "win" elif num in [2,3,12]: return "lose" else: return "point" def changePlayer(player): if player == "Your": return "My" else: return "Your" def point(num): while True: raw_input("Roll") uno, dos = random.choice(dice), random.choice(dice) three = uno+dos print "{0} + {1} = {2}".format(uno, dos, three) print "Point is {0}. You scored {1}.".format(num, three) if three == num: return "win" if three == 7: return "lose" else: print "Try again." print message while stake: print "{0} throw! You have ${1}. How much do you bet?".format(player, stake) bet = int(raw_input("$")) stake -= bet one, two = random.choice(dice), random.choice(dice) print "{0} + {1} = {2}".format(one, two, one+two) if win(one+two) == "win": stake += bet*2 print winmsg elif win(one+two) == "lose": print losemsg else: if point(one+two) == "win": stake += bet*2 print winmsg elif point(one+two) == "lose": print losemsg player = changePlayer(player) Thanks Col -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Oct 9 08:42:46 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Oct 2011 17:42:46 +1100 Subject: [Tutor] Crazy craps problem In-Reply-To: References: Message-ID: <4E914266.9000108@pearwood.info> col speed wrote: > Hi again, Once more I've come up with a problem I can't explain. It must be > something simple, but I can't work it out. > The part of the script that is causing the problem is as follows: > > > def point(num): > while True: > raw_input("Roll") You ask the user for input, but don't do anything with their answer. Is that deliberate? > uno, dos = random.choice(dice), random.choice(dice) > three = uno+dos It is confusing to have a variable called "three" which isn't equal to three. Likewise for "uno" and "dos", especially for Spanish or Italian speakers. > print "{0} + {1} = {2}".format(uno, dos, three) > print "Point is {0}. You scored {1}.".format(num, three) > if three == num: > return "win" What happens if the caller passes 7 as the argument to point? > if three == 7: > return "lose" > else: > print "Try again." > > What I have tried to do is - simulate dice throws, if the total is the same > as originally thrown, return from the function(this works). If I throw a 7, > I also want to return(this does not work as you can see from this sample > output: I cannot confirm that behaviour. When I try it, it works as expected: if you throw seven, it breaks out of the loop and you lose immediately. I've tried that a couple of times, but because the scores are random, it takes a while. So I monkey-patched the game for testing purposes: Kids! Don't do this at home! Monkey-patching is bad and wrong! >>> class MonkeyPatchedRandom: ... scores = [6, 1, 3, 4, 5, 6, 2, 1, 1, 3] ... index = -1 ... def choice(self, arg): ... self.index += 1 ... return self.scores[self.index] ... >>> random = MonkeyPatchedRandom() >>> point(3) Roll 6 + 1 = 7 Point is 3. You scored 7. 'lose' >>> As you can see, if you happen to roll 7 on the first go, it exits the loop as expected. [...] > Point is 4. You scored 7. > You have lost! You have $100 left. There is nothing in the point() function that could possible print "You have lost". There is obviously some other code that you aren't showing us. > As you can see, after throwing a 7, it just continues. It only returns after > throwing a second 7. > > 1. I know it's bad form to print from a function, I'll change it later. A better way of stating this is that you should separate *interface* from *implementation*: printing messages to the user is part of the interface, and actually comparing dice rolls and deciding whether you have won or lost is part of the implementation, so they should be in separate functions. > 2. I've tried the second if statement using "elif". > 3. I've tried omitting the "three" variable and just using "uno" + "dos". > 4. I've used "uno" and "dos" because I use "one" and "two" in another part > of the script(outside and after the function definition), although they > shouldn't be affected in any way. Local variables are local. You don't need to fear that variables "one" and "two" inside function A will clash with variables inside function B (unless you declare them as global!). So don't worry about having every variable in every function have a unique name. More importantly, though, it is confusing to name a variable "one". One what? Better names would be "roll_one", "score_one", "dice_a", or even "a" and "b" -- at least they are *generic* names and you won't fool the reader into expecting that variable two == 2. -- Steven From andreas.perstinger at gmx.net Sun Oct 9 08:55:39 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sun, 09 Oct 2011 08:55:39 +0200 Subject: [Tutor] Crazy craps problem In-Reply-To: References: <4E913C6B.2010406@gmx.net> Message-ID: <4E91456B.7010900@gmx.net> On 2011-10-09 08:25, col speed wrote: > Thanks for your prompt reply! Here's the whole thing: > > import random > > message = """Welcome to craps!!!! Place your bet > and roll the dice. > 7 or 11 wins. > 2, 3 or 12 loses. > Others are "point".""" > player = "Your" > dice = range(1, 7) > stake = 100 > bet = 5 > winmsg = "You have won!You have ${0} left.".format(stake) > losemsg = "You have lost! You have ${0} left.".format(stake) > players = ["Your", "My"] > > def win(num): > if num in [7,11]: > return "win" > elif num in [2,3,12]: > return "lose" > else: > return "point" > > def changePlayer(player): > if player == "Your": > return "My" > else: > return "Your" > > def point(num): > while True: > raw_input("Roll") > uno, dos = random.choice(dice), random.choice(dice) > three = uno+dos > print "{0} + {1} = {2}".format(uno, dos, three) > print "Point is {0}. You scored {1}.".format(num, three) > if three == num: > return "win" > if three == 7: > return "lose" > else: > print "Try again." > > print message > while stake: > print "{0} throw! You have ${1}. How much do you bet?".format(player, > stake) > bet = int(raw_input("$")) > stake -= bet > one, two = random.choice(dice), random.choice(dice) > print "{0} + {1} = {2}".format(one, two, one+two) > if win(one+two) == "win": > stake += bet*2 > print winmsg > elif win(one+two) == "lose": > > print losemsg > else: > if point(one+two) == "win": Here you go into the function "point" the first time. Inside the function you are in an infinite while-loop where you only exit if the sum is either 7 ("lose") or equal the given parameter ("win"). Then you compare the return value. In the case of "lose" you continue to the next elif-statement: > stake += bet*2 > print winmsg > elif point(one+two) == "lose": Now you go into the function "point" a *second* time, in other words you have to throw another 7 to leave the function with the return value "lose". But just now you will print out the message for loosing the game: > print losemsg > player = changePlayer(player) What you probably want is to go into "point" only once, save the result value and check if it's "win" or "lose". HTH, Andreas From ajarncolin at gmail.com Sun Oct 9 09:01:58 2011 From: ajarncolin at gmail.com (col speed) Date: Sun, 9 Oct 2011 14:01:58 +0700 Subject: [Tutor] Crazy craps problem In-Reply-To: <4E91456B.7010900@gmx.net> References: <4E913C6B.2010406@gmx.net> <4E91456B.7010900@gmx.net> Message-ID: <--> snip >> if point(one+two) == "win": >> > > Here you go into the function "point" the first time. Inside the function > you are in an infinite while-loop where you only exit if the sum is either 7 > ("lose") or equal the given parameter ("win"). Then you compare the return > value. In the case of "lose" you continue to the next elif-statement: > > > stake += bet*2 >> print winmsg >> elif point(one+two) == "lose": >> > > Now you go into the function "point" a *second* time, in other words you > have to throw another 7 to leave the function with the return value "lose". > But just now you will print out the message for loosing the game: > > > print losemsg >> player = changePlayer(player) >> > > What you probably want is to go into "point" only once, save the result > value and check if it's "win" or "lose". > > HTH, > > Andreas > > Amazing as always. I will act upon all suggestions. Thanks again -------------- next part -------------- An HTML attachment was scrubbed... URL: From aisha.ali101 at yahoo.com Sun Oct 9 02:40:38 2011 From: aisha.ali101 at yahoo.com (Aisha Ali) Date: Sat, 8 Oct 2011 17:40:38 -0700 (PDT) Subject: [Tutor] Python coding help Message-ID: <1318120838.786.YahooMailNeo@web121605.mail.ne1.yahoo.com> Hi, My computer science teacher provided optional Python exercises for us as we're learning about Java/Python right now. I decided to learn how to code these because I'm very interested in programming, but I don't know how to start on the problems in this case. Help? I'll love to learn more about Python! Thanks, Aisha -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: python.py Type: application/octet-stream Size: 3826 bytes Desc: not available URL: From delegbede at dudupay.com Sun Oct 9 13:49:41 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sun, 9 Oct 2011 11:49:41 +0000 Subject: [Tutor] Python coding help In-Reply-To: <1318120838.786.YahooMailNeo@web121605.mail.ne1.yahoo.com> References: <1318120838.786.YahooMailNeo@web121605.mail.ne1.yahoo.com> Message-ID: <283357319-1318160975-cardhu_decombobulator_blackberry.rim.net-140867246-@b18.c12.bise7.blackberry> Try a byte of a python or alan gauld site on learning python. Welcome to python. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Aisha Ali Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Sat, 8 Oct 2011 17:40:38 To: tutor at python.org Reply-To: Aisha Ali Subject: [Tutor] Python coding help _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Oct 9 15:51:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 09 Oct 2011 14:51:44 +0100 Subject: [Tutor] Python coding help In-Reply-To: <1318120838.786.YahooMailNeo@web121605.mail.ne1.yahoo.com> References: <1318120838.786.YahooMailNeo@web121605.mail.ne1.yahoo.com> Message-ID: On 09/10/11 01:40, Aisha Ali wrote: > My computer science teacher provided optional Python exercises for us as > we're learning about Java/Python right now. I decided to learn how to > code these because I'm very interested in programming, but I don't know > how to start on the problems in this case. Help? I'll love to learn more > about Python! That's a bit too vague for us to provide much help. What level of programmer are you? Can you write programs in any other language? Or are you just starting computer science? Also it helps if we know what OS you are using (Linux, MacOS, Windows etc) Have you installed Python? If so which major version (There are two currently available, V2 and V3) If you visit the python.org web site you may get all your questions answered there. If not come back here with something a bit more specific and we will try to help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Sun Oct 9 16:02:20 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 9 Oct 2011 22:02:20 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E911036.7010906@pearwood.info> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E86E3@EMARC112VS01.exchad.jpmchase.net> <4E8E5AED.8050207@pearwood.info> <4E8ED388.2040305@davea.name> <1769514952-1318096541-cardhu_decombobulator_blackberry.rim.net-755081903-@b18.c12.bise7.blackberry> <4E911036.7010906@pearwood.info> Message-ID: Just wanna say a quick thanks to all of you here, Very informative. Thanks, On Sun, Oct 9, 2011 at 11:08 AM, Steven D'Aprano wrote: > Walter Prins wrote: > > As for the compiler/interpreter argument, I'll just point out again that >> actually Python in its various forms can either be compiled and/or >> interepreted, it depends on you really. For compiled Python flavours, see >> for example Cython (http://cython.org/) which provides a way to write >> C/C++ >> modules for Python effectively in Python syntax. (Cython arguably also >> makes the "need to write wrapper" comment a moot point.) >> > > Cython is not Python. It is a separate language similar to Python, based on > Python, but not actually Python. It's actually a superset of Python. Any > Python code should be legal in Cython, but not all Cython code is legal in > Python. > > See, for example: > > http://docs.cython.org/src/**userguide/tutorial.html#primes > > and notice that the Cython code: > > > def primes(int kmax): > cdef int n, k, i > cdef int p[1000] > # ... > > gives you a SyntaxError in Python. > > Credit where credit is due: Cython is a wonderful tool and very useful to > anyone wanting to write C extensions for Python, but it isn't Python. That's > not a limitation or a bad thing: it couldn't do what it sets out to do if it > were Python. > > > Or see Shedskin ( >> >> http://shed-skin.blogspot.com/**), a Python to C++ static compiler), >> > > > Shedskin, on the other hand, is a subset of Python: it can only work with a > restricted set of Python features. So also not Python. > > http://code.google.com/p/**shedskin/ > > But still a very useful and valuable tool. > > > > or Psyco >> (http://psyco.sourceforge.net/**introduction.html), a JIT (Just In Time) >> compiler for CPython. >> > > Psyco, on the other hand, is an add-on to Python: it runs inside the > CPython compiler, as an importable module, rather than being a separate > Python interpreter. > > > > Or see Pypy (http://pypy.org/) which is another >> reimplementation of the Python language with an optimizing JIT compiler. >> (The following post re realtime image processing in Python is rather >> impressive: >> http://morepypy.blogspot.com/**2011/07/realtime-image-** >> processing-in-python.html >> ) >> > > > PyPy is very impressive, and it truly is an independent implementation of > Python, like CPython, Jython, IronPython and Stackless. It is faster than > CPython (although requires more memory) and in certain restricted > micro-benchmarks faster than C. > > Yes, faster than C. > > http://morepypy.blogspot.com/**2008/01/rpython-can-be-faster-**than-c.html > http://morepypy.blogspot.com/**2011/02/pypy-faster-than-c-on-** > carefully-crafted.html > http://morepypy.blogspot.com/**2011/08/pypy-is-faster-than-c-** > again-string.html > > > > This just goes to show that *languages* aren't faster or slower than other > languages. Languages just are. But *implementations* can be faster or > slower. > > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Sun Oct 9 17:27:21 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Sun, 9 Oct 2011 11:27:21 -0400 Subject: [Tutor] String switch In-Reply-To: <4E90D06C.5060203@gmail.com> References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> <4E8DCB8C.6090301@gmail.com> <4E90D06C.5060203@gmail.com> Message-ID: I know the method of finding every string, and inserting a swapcase in to the code. Does anyone now a way just to insert code at the top though? P.S. I use python 2.* -------------- next part -------------- An HTML attachment was scrubbed... URL: From olofsson_anna585 at hotmail.com Sun Oct 9 17:56:28 2011 From: olofsson_anna585 at hotmail.com (Anna Olofsson) Date: Sun, 9 Oct 2011 17:56:28 +0200 Subject: [Tutor] vcf_files and strings In-Reply-To: <1318018627.43378.YahooMailNeo@web111215.mail.gq1.yahoo.com> References: , <1318018627.43378.YahooMailNeo@web111215.mail.gq1.yahoo.com> Message-ID: Hi, I still don't know how to make a loop that makes it work for all the mutations. Best, Anna Date: Fri, 7 Oct 2011 13:17:07 -0700 From: ilhs_hs at yahoo.com Subject: Re: [Tutor] vcf_files and strings To: olofsson_anna585 at hotmail.com; tutor at python.org if col[x] == 'missense': print col[withRefSeqID] hth From: Anna Olofsson To: tutor at python.org Sent: Friday, October 7, 2011 12:12 PM Subject: [Tutor] vcf_files and strings Hi, I'm a beginner at Python and would really appreciate some help in how to extract information from a vcf file. The attached file consists of a lot of information on mutations, this one though is just 2 rows and 10 columns (the real one has a lot more rows). I want to extract the mRNA ID only if the mutation is missense. These two rows (mutations) that I have attached happens to be missense but how do I say that I'm not interested in the mutations that's not missense (they might be e.g. synonymous). Also, how do I say that if a mutation starts with a # symbol I don't want to include it (sometimes the chr starts with a hash). vcf file: 2 rows, 10 columns. col 0 col 1 col 2 col 3 col 4 col5 col6 col7 col8 col9 chromosome position . Reference ALT position . some statistics and the ID:s not important not important The important column is 7 where the ID is, i.e. refseq.functionalClass=missense. It's a missense mutation, so then I want to extract refseq.name=NM_003137492, or I want to extract only the ID, which in this case is NM_003137492. Then I want to do exactly the same thing for all the other mutations, but only for the missense mutations not the other ones. How do I accomplish that? Where do I start? Best, Anna _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Oct 9 18:20:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 09 Oct 2011 17:20:30 +0100 Subject: [Tutor] String switch In-Reply-To: References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> <4E8DCB8C.6090301@gmail.com> <4E90D06C.5060203@gmail.com> Message-ID: On 09/10/11 16:27, Christopher King wrote: > I know the method of finding every string, and inserting a swapcase in > to the code. Does anyone now a way just to insert code at the top though? Inserting code at the top of the file is just like inserting any kind of text at the top of any kind of text file. Whjether the code does what you want is another matter and whether inserting code at the top of a file is a good way of achieving what you want is yet another. But for an example of inserting text at the top of a file look in the File Handling topic of my tutorial. Look at the example just above the "OS Gotchas" box... But I really don't think this is the best way to achieve your real objective. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Sun Oct 9 18:34:48 2011 From: d at davea.name (Dave Angel) Date: Sun, 09 Oct 2011 12:34:48 -0400 Subject: [Tutor] String switch In-Reply-To: References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> <4E8DCB8C.6090301@gmail.com> <4E90D06C.5060203@gmail.com> Message-ID: <4E91CD28.1050905@davea.name> On 10/09/2011 11:27 AM, Christopher King wrote: > I know the method of finding every string, and inserting a swapcase in to > the code. Does anyone now a way just to insert code at the top though? > > P.S. I use python 2.* > Would you consider answering the rest of my questions? Since this is obviously a puzzle of some sort, could you just show us the whole problem, as given in the puzzle book, or on the blackboard? If the program to be modified is a trivial one, using only prints of literal strings to stdout, then perhaps you want all of stdout modified. You could solve *that* problem by replacing sys.stdout with an object of your own creation. -- DaveA From alan.gauld at btinternet.com Sun Oct 9 20:07:43 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 9 Oct 2011 19:07:43 +0100 (BST) Subject: [Tutor] Fw: Python coding help In-Reply-To: References: <1318120838.786.YahooMailNeo@web121605.mail.ne1.yahoo.com> Message-ID: <1318183663.14318.YahooMailRC@web86706.mail.ird.yahoo.com> Forwarding for group Please always use ReplyAll to send stuff to the group as a whole. That way you get more replies! :-) Alan G. ----- Forwarded Message ---- From: Aisha Ali To: Alan Gauld Sent: Sunday, 9 October, 2011 18:04:16 Subject: Re: [Tutor] Python coding help I just recently started learning computer science this year, and I'm using V2 Python on Mac. :) ________________________________ From: Alan Gauld To: tutor at python.org Sent: Sunday, October 9, 2011 9:51 AM Subject: Re: [Tutor] Python coding help On 09/10/11 01:40, Aisha Ali wrote: > My computer science teacher provided optional Python exercises for us as > we're learning about Java/Python right now. I decided to learn how to > code these because I'm very interested in programming, but I don't know > how to start on the problems in this case. Help? I'll love to learn more > about Python! That's a bit too vague for us to provide much help. What level of programmer are you? Can you write programs in any other language? Or are you just starting computer science? Also it helps if we know what OS you are using (Linux, MacOS, Windows etc) Have you installed Python? If so which major version (There are two currently available, V2 and V3) If you visit the python.org web site you may get all your questions answered there. If not come back here with something a bit more specific and we will try to help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From guandalino at gmail.com Mon Oct 10 00:41:03 2011 From: guandalino at gmail.com (D. Guandalino) Date: Mon, 10 Oct 2011 00:41:03 +0200 Subject: [Tutor] Help refactoring this code Message-ID: Hi, in this class many methods share common code. class Foo(object): def m1(self): if self.foo: pass # m1 do something elif self.bar: pass # m1 do something else else: pass # m1 do something different def m2(self): if self.foo: pass # m2 do something elif self.bar: pass # m2 do something else else: pass # m2 do something different # def m_n(self): pass # same conditionals, different implementation I'm wondering if I have to duplicate the if/elif/else for each method. Does Python 2.7 provide a way to factor out this common structure? From alan.gauld at btinternet.com Mon Oct 10 02:21:47 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Oct 2011 01:21:47 +0100 Subject: [Tutor] Help refactoring this code In-Reply-To: References: Message-ID: On 09/10/11 23:41, D. Guandalino wrote: > Hi, in this class many methods share common code. > > class Foo(object): > def m1(self): > if self.foo: > pass # m1 do something > elif self.bar: > pass # m1 do something else > else: > pass # m1 do something different > > def m2(self): > if self.foo: > pass # m2 do something > elif self.bar: > pass # m2 do something else > else: > pass # m2 do something different > > # def m_n(self): > pass # same conditionals, different implementation > > I'm wondering if I have to duplicate the if/elif/else for each method. > Does Python 2.7 provide a way to factor out this common structure? Refactoring does not depend on the language so yes you can refactor this code in 2.7 as well as you can in any other language, but... Should you? We can't tell from the code you have posted because you have commented out the bits that matter - what the methods actually do. Just because they have the same set of conditional tests does not mean you should refactor (except maybe at the class level - maybe you need to split the class into one with foo true and the other with bar true (and maybe a third for the else...) but never rush to create subclasses because that brings its own problems!). At the method level refactoring would depend on the content of the implementation sections. If the two methods did similar things within those code blocks then you might introduce new helper methods or parameterise the two methods into one. But without any idea of the implementation we really can't say. For example, if m1 creates formatted output for reporting purposes and m2 saves the data into a database and m_n serialises the class for transmission over a network then its unlikely that there is much opportunity to refactor the methods. But it is likely that all three share the kind of structure you show above. But if the three methods represent three different styles of report formatting then yes, we probably can do something. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From amonroe at columbus.rr.com Mon Oct 10 02:31:52 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 9 Oct 2011 20:31:52 -0400 Subject: [Tutor] fake defrag revisited In-Reply-To: <4E8C591F.6050703@davea.name> References: <145120072334.20111001020636@columbus.rr.com> <4E86FE05.8040608@davea.name> <150155273711.20111001115318@columbus.rr.com> <4E875600.4060400@davea.name> <101169689560.20111001155333@columbus.rr.com> <4E8BF615.8000806@davea.name> <15135188871.20111005075845@columbus.rr.com> <4E8C591F.6050703@davea.name> Message-ID: <139525982332.20111009203152@columbus.rr.com> >> I did get a semi-working version, but it was crazy inefficient because >> it regenerated the swap list after every move, and it bombed out with >> a IndexError about half the time. I found that moving a single block >> at a time lacked the aesthetic appeal I was hoping for, so I bagged it >> for now. I did go back and play with this some more. This version is much more efficient and does not crash, although it does have one shortcoming. It blindly assumes that there's enough free space to move the largest existing file, which isn't necessarily the case. Aesthetically, it doesn't match what I'm envisioning in my mind's eye, but it's still kind of neat to watch for a few minutes. http://javajack.dynalias.net/defrag/defrag014.py (requires pygame for the visuals) Alan From steve at pearwood.info Mon Oct 10 03:16:35 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Oct 2011 12:16:35 +1100 Subject: [Tutor] Help refactoring this code In-Reply-To: References: Message-ID: <4E924773.1080304@pearwood.info> D. Guandalino wrote: > Hi, in this class many methods share common code. Given your example, I wouldn't bother refactoring it. There's not enough code in common to matter. -- Steven From steve at pearwood.info Mon Oct 10 04:04:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Oct 2011 13:04:50 +1100 Subject: [Tutor] vcf_files and strings In-Reply-To: References: Message-ID: <4E9252C2.6030804@pearwood.info> Anna Olofsson wrote: > Hi, > > I'm a beginner at Python and would really like some help in how to > extract information from a vcf file. > > The attached file consists of a lot of information on mutations, this > one though is just 2 rows and 10 columns (the real one has a lot more > rows). What do you mean by a VCF file? On my computer, a VCF file is an electronic business card, which tries to open in an Address Book application (which obviously fails). I don't know how to interpret the contents of your VCF file. After opening it in a hex editor, I can *guess* that it is a tab-separated file: each row takes one line, with the columns separated by tab characters. Column 7 appears to be a great big ugly blob with sub-fields separated by semi-colons. Am I right? Can you link us to a description of the vcf file format? > I want to extract the mRNA ID only if the mutation is missense. These > two rows (mutations) that I have attached happens to be missense but > how do I say that I'm not interested in the mutations that's not > missense (they might be e.g. synonymous). Also, how do I say that if > a mutation starts with a # symbol I don't want to include it > (sometimes the chr starts with a hash). What chr? Where is the mutation? I'm afraid your questions are assuming familiarity with your data that we don't have. > vcf file: 2 rows, 10 columns. > col 0 col 1 col 2 > col 3 col 4 col5 col6 > col7 col8 > col9 chromosome position . > Reference ALT position . some statistics > and the ID:s not important not important > > The important column is 7 where the ID is, i.e. > refseq.functionalClass=missense. It's a missense mutation, so then I > want to extract refseq.name=NM_003137492, or I want to extract only > the ID, which in this case is NM_003137492. This is what I *think* you want to do. Am I right? * read each line of the file * for each line, split on tabs * extract the 7th column and split it on semi-colons * inspect the refseq.functionalClass field * if it matches, extract the ID from the refseq.name and store it in a list for later (I have completely ignored the part about the #, because I don't understand what you mean by it.) Here's some code to do it: ids = [] f = open('vcf_file.vcf', 'r') for row in f: columns = row.split('\t') # Split on tabs data = columns[7] # Huge ugly blob of data values = data.split(';') # Split on semi-colons if values[25] == "refseq.functionalClass=missense": name_chunk = values[28] # looks like "refseq.name=..." a, b = name_chunk.split("=") if a != "refseq.name": raise ValueError('expected refseq.name but got %s' % a) ids.append(b) f.close() print(ids) Does this help? -- Steven From johan at accesstel.com.au Mon Oct 10 05:04:40 2011 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Mon, 10 Oct 2011 14:04:40 +1100 Subject: [Tutor] urllib2 sslerror In-Reply-To: References: <02da01cc84b4$4082dec0$c1889c40$@com.au> Message-ID: <002b01cc86f9$5a632f10$0f298d30$@com.au> Hi, The connection I am making is not going through a proxy, but directly to the device over https. Like I said in the original post, it works most of the time, but not always and it I can't reproduce the error on-demand. In this line: html_content = return_object.read(), will it read binary data or is that only applicable when I write it to a file to write it as binary? Any help would be appreciated. Thanks Johan From: nehal dattani [mailto:nehal.dattani at gmail.com] Sent: Friday, 7 October 2011 7:49 PM To: Johan Geldenhuys Subject: Re: [Tutor] urllib2 sslerror Hi Johan, If you are using http proxy, this may be helpful. http://stackoverflow.com/questions/1030113/does-urllib2-in-python-2-6-1-supp ort-proxy-via-https Regards, Nehal Dattani On Fri, Oct 7, 2011 at 11:14 AM, Johan Geldenhuys wrote: Hi everybody, Almost weekend, hang in there. I need some advice and hope somebody can help me. I have the follow piece of code that I use to get some data from a https webpage. ------------------------------------------------------- < some other stuff up here> try: return_object = urllib2.urlopen(theurl) html_content = return_object.read() now = time.strftime("%Y%m%d%H%M%S") img_file = "%s_%s.jpg"% (location, now) f = open(img_file, 'wb') f.write(html_content) f.close() file = img_file except Exception, e: print e ------------------------------------------------------- Sometimes I get the following error and I don't know why. It occurs very randomly and is hard or nearly impossible to reproduce (maybe there is somebody who knows how to create it). ------------------------------------------------------- Traceback (most recent call last): File "/var/ai-muse/jail/pkgdb/camimage/getimage.py", line 74, in run return_object = urllib2.urlopen(self.theurl) File "/usr/lib/python2.2/urllib2.py", line 138, in urlopen File "/usr/lib/python2.2/urllib2.py", line 322, in open File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain File "/usr/lib/python2.2/urllib2.py", line 792, in https_open File "/usr/lib/python2.2/urllib2.py", line 779, in do_open File "/usr/lib/python2.2/urllib2.py", line 342, in error File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain File "/usr/lib/python2.2/urllib2.py", line 611, in http_error_401 File "/usr/lib/python2.2/urllib2.py", line 590, in http_error_auth_reqed File "/usr/lib/python2.2/urllib2.py", line 600, in retry_http_basic_auth File "/usr/lib/python2.2/urllib2.py", line 322, in open File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain File "/usr/lib/python2.2/urllib2.py", line 792, in https_open File "/usr/lib/python2.2/urllib2.py", line 774, in do_open File "/usr/lib/python2.2/httplib.py", line 752, in getreply File "/usr/lib/python2.2/httplib.py", line 593, in getresponse File "/usr/lib/python2.2/httplib.py", line 99, in __init__ File "/usr/lib/python2.2/httplib.py", line 628, in makefile sslerror: (5, 'EOF occurred in violation of protocol') ------------------------------------------------------------ Any idea why it happens randomly and how I can check the cause? I read on a Google search page that one guy had the same issue and traced it back to some characters in the data he was receiving. Could that cause it? Thanks in advance Johan _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Oct 10 05:19:14 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 09 Oct 2011 23:19:14 -0400 Subject: [Tutor] Python coding help In-Reply-To: <1318120838.786.YahooMailNeo@web121605.mail.ne1.yahoo.com> References: <1318120838.786.YahooMailNeo@web121605.mail.ne1.yahoo.com> Message-ID: <4E926432.9060807@gmail.com> On 10/8/2011 8:40 PM, Aisha Ali wrote: > Hi, > > My computer science teacher provided optional Python exercises for us > as we're learning about Java/Python right now. I decided to learn how > to code these because I'm very interested in programming, but I don't > know how to start on the problems in this case. Help? I'll love to > learn more about Python! > > #############CODE YOUR FUNCTIONS HERE############################## > # 0. Example: > def f2c(tempF): > """precondition: tempF is a number > postcondition: returns tempF converted to centigrade""" > return 5.0/9.0*(tempF - 32) Above is an example of a complete Python function. > # 1. > def c2f(tempC): > """precondition: tempC is a number > postcondition: returns tempC converted to farenheit""" > return 0 Above is an incomplete function which you are to complete - by replacing return 0 with return erxpression-converting-c-to-f Do you understand that much? Can you complete the function? ditto for 2 thru 10 This is backwards - here you are asked to do this before te above! The idea is to write code to test your functions. ###################TEST CODE GOES HERE############################## ##Begin here! Look at your functions and develop tests before ##you create the function's code. This is your best protection ##against crash and burn..... print "***********************Problem 0 Test Code:***********************" t = 212 print "f2c(%5.4fs) = %5.4f, expected: %5.4f" %(t, f2c(t), 100) t = -40 print "f2c(%5.4fs) = %5.4f, expected: %5.4f" %(t, f2c(t), -40) t = 32 print "f2c(%5.4fs) = %5.4f, expected: %5.4f" %(t, f2c(t), 0) The above are 3 calls to f2c which was defined in 0. way above. They "test" f2c. The test code is complicated by the use of % for formatting. You might be better off doing it this way to avoid the complication of learning % formatting. t = 212 print "f2(" + t +") = " + f2c(t) + " expected: 100" Now you are to write similar tests for problems 1-10. Enough to get you started? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From c2praveen30jun at gmail.com Mon Oct 10 15:26:31 2011 From: c2praveen30jun at gmail.com (Praveen Singh) Date: Mon, 10 Oct 2011 09:26:31 -0400 Subject: [Tutor] I am trying to print list elements but i am getting 'none' Message-ID: This is my code- def getNumbers(num): myList=[] for numbers in range(0,num,2): print myList.append(numbers) output- >>> getNumbers(10) None None None None None Then i find out that list.append doesn't return anything.Then what should i use for this kind of operation.but if i do something like this on idle's interpreter it gives me answer- >>> myList=[] >>> myList.append(8) >>> print myList [8] Confused!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From nitinpawar432 at gmail.com Mon Oct 10 15:30:40 2011 From: nitinpawar432 at gmail.com (Nitin Pawar) Date: Mon, 10 Oct 2011 19:00:40 +0530 Subject: [Tutor] I am trying to print list elements but i am getting 'none' In-Reply-To: References: Message-ID: Try giving the print statement outside the for loop On Mon, Oct 10, 2011 at 6:56 PM, Praveen Singh wrote: > This is my code- > def getNumbers(num): > myList=[] > for numbers in range(0,num,2): > print myList.append(numbers) > > > output- > >>> getNumbers(10) > None > None > None > None > None > > Then i find out that list.append doesn't return anything.Then what should i > use for this kind of operation.but if i do something like this on idle's > interpreter it gives me answer- > >>> myList=[] > >>> myList.append(8) > >>> print myList > [8] > > Confused!!! > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Nitin Pawar -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Mon Oct 10 15:32:28 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 10 Oct 2011 15:32:28 +0200 Subject: [Tutor] I am trying to print list elements but i am getting 'none' In-Reply-To: References: Message-ID: <4E92F3EC.8080003@compuscan.co.za> On 2011/10/10 03:26 PM, Praveen Singh wrote: > This is my code- > def getNumbers(num): > myList=[] > for numbers in range(0,num,2): > print myList.append(numbers) > > > output- > >>> getNumbers(10) > None > None > None > None > None > > Then i find out that list.append doesn't return anything.Then what > should i use for this kind of operation.but if i do something like > this on idle's interpreter it gives me answer- > >>> myList=[] > >>> myList.append(8) > >>> print myList > [8] > > Confused!!! > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor If you seperate your print and the myList.append operation you will get what you want, which is why it works in IDLE. Are you sure you don't want to rather build your list, and return it from your function and then when you call it you do `print getNumbers(10)` if you wish. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Oct 10 15:51:36 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 11 Oct 2011 00:51:36 +1100 Subject: [Tutor] I am trying to print list elements but i am getting 'none' In-Reply-To: References: Message-ID: <4E92F868.8060407@pearwood.info> Praveen Singh wrote: > This is my code- > def getNumbers(num): > myList=[] > for numbers in range(0,num,2): > print myList.append(numbers) > > > output- >>>> getNumbers(10) > None > None > None > None > None > > Then i find out that list.append doesn't return anything.Then what should i > use for this kind of operation.but if i do something like this on idle's > interpreter it gives me answer- If you want to print the list after each append, then print the list after each append: def getNumbers(num): myList=[] for number in range(0, num, 2): myList.append(number) print mylist If you want to print the list once, at the end, then print it once, at the end, *outside* the loop: def getNumbers(num): myList=[] for number in range(0, num, 2): myList.append(number) print mylist -- Steven From waynejwerner at gmail.com Mon Oct 10 16:14:01 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 10 Oct 2011 09:14:01 -0500 Subject: [Tutor] I am trying to print list elements but i am getting 'none' In-Reply-To: References: Message-ID: On Mon, Oct 10, 2011 at 8:26 AM, Praveen Singh wrote: > print myList.append(numbers) Your problem is with that statement. >>> mylist = [] >>> x = mylist.append(3) >>> x >>> x is None True >>> help(mylist.append) Help on built-in function append: append(...) L.append(object) -- append object to end append returns None (all functions do, unless you explicitly return something that is not None) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Mon Oct 10 18:52:00 2011 From: bodsda at googlemail.com (Bod Soutar) Date: Mon, 10 Oct 2011 17:52:00 +0100 Subject: [Tutor] I am trying to print list elements but i am getting 'none' In-Reply-To: References: Message-ID: On 10 October 2011 14:26, Praveen Singh wrote: > This is my code- > ?def getNumbers(num): > ??? myList=[] > ??? for numbers in range(0,num,2): > ????????? print myList.append(numbers) > > > output- >>>> getNumbers(10) > None > None > None > None > None > > Then i find out that list.append doesn't return anything.Then what should i > use for this kind of operation.but if i do something like this on idle's > interpreter it gives me answer- >>>> myList=[] >>>> myList.append(8) >>>> print myList > [8] > > Confused!!! > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Print your list after you have appended to it. def getNumbers(num): myList=[] for numbers in range(0,num,2): myList.append(numbers) for item in list: print item From geonyoro at gmail.com Mon Oct 10 21:23:11 2011 From: geonyoro at gmail.com (George Nyoro) Date: Mon, 10 Oct 2011 16:23:11 -0300 Subject: [Tutor] help Message-ID: On 10/10/2011, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. I am trying to print list elements but i am getting 'none' > (Praveen Singh) > 2. Re: I am trying to print list elements but i am getting > 'none' (Nitin Pawar) > 3. Re: I am trying to print list elements but i am getting > 'none' (Christian Witts) > 4. Re: I am trying to print list elements but i am getting > 'none' (Steven D'Aprano) > 5. Re: I am trying to print list elements but i am getting > 'none' (Wayne Werner) > 6. Re: I am trying to print list elements but i am getting > 'none' (Bod Soutar) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 10 Oct 2011 09:26:31 -0400 > From: Praveen Singh > To: tutor at python.org > Subject: [Tutor] I am trying to print list elements but i am getting > 'none' > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > This is my code- > def getNumbers(num): > myList=[] > for numbers in range(0,num,2): > print myList.append(numbers) > > > output- >>>> getNumbers(10) > None > None > None > None > None > > Then i find out that list.append doesn't return anything.Then what should i > use for this kind of operation.but if i do something like this on idle's > interpreter it gives me answer- >>>> myList=[] >>>> myList.append(8) >>>> print myList > [8] > > Confused!!! > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 2 > Date: Mon, 10 Oct 2011 19:00:40 +0530 > From: Nitin Pawar > To: Praveen Singh > Cc: tutor at python.org > Subject: Re: [Tutor] I am trying to print list elements but i am > getting 'none' > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > Try giving the print statement outside the for loop > > On Mon, Oct 10, 2011 at 6:56 PM, Praveen Singh > wrote: > >> This is my code- >> def getNumbers(num): >> myList=[] >> for numbers in range(0,num,2): >> print myList.append(numbers) >> >> >> output- >> >>> getNumbers(10) >> None >> None >> None >> None >> None >> >> Then i find out that list.append doesn't return anything.Then what should >> i >> use for this kind of operation.but if i do something like this on idle's >> interpreter it gives me answer- >> >>> myList=[] >> >>> myList.append(8) >> >>> print myList >> [8] >> >> Confused!!! >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Nitin Pawar > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 3 > Date: Mon, 10 Oct 2011 15:32:28 +0200 > From: Christian Witts > To: Praveen Singh > Cc: tutor at python.org > Subject: Re: [Tutor] I am trying to print list elements but i am > getting 'none' > Message-ID: <4E92F3EC.8080003 at compuscan.co.za> > Content-Type: text/plain; charset="windows-1252"; Format="flowed" > > On 2011/10/10 03:26 PM, Praveen Singh wrote: >> This is my code- >> def getNumbers(num): >> myList=[] >> for numbers in range(0,num,2): >> print myList.append(numbers) >> >> >> output- >> >>> getNumbers(10) >> None >> None >> None >> None >> None >> >> Then i find out that list.append doesn't return anything.Then what >> should i use for this kind of operation.but if i do something like >> this on idle's interpreter it gives me answer- >> >>> myList=[] >> >>> myList.append(8) >> >>> print myList >> [8] >> >> Confused!!! >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > If you seperate your print and the myList.append operation you will get > what you want, which is why it works in IDLE. Are you sure you don't > want to rather build your list, and return it from your function and > then when you call it you do `print getNumbers(10)` if you wish. > > -- > > Christian Witts > Python Developer > > // > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 4 > Date: Tue, 11 Oct 2011 00:51:36 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] I am trying to print list elements but i am > getting 'none' > Message-ID: <4E92F868.8060407 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Praveen Singh wrote: >> This is my code- >> def getNumbers(num): >> myList=[] >> for numbers in range(0,num,2): >> print myList.append(numbers) >> >> >> output- >>>>> getNumbers(10) >> None >> None >> None >> None >> None >> >> Then i find out that list.append doesn't return anything.Then what should >> i >> use for this kind of operation.but if i do something like this on idle's >> interpreter it gives me answer- > > > If you want to print the list after each append, then print the list > after each append: > > def getNumbers(num): > myList=[] > for number in range(0, num, 2): > myList.append(number) > print mylist > > > If you want to print the list once, at the end, then print it once, at > the end, *outside* the loop: > > def getNumbers(num): > myList=[] > for number in range(0, num, 2): > myList.append(number) > print mylist > > > -- > Steven > > > > ------------------------------ > > Message: 5 > Date: Mon, 10 Oct 2011 09:14:01 -0500 > From: Wayne Werner > To: Praveen Singh > Cc: tutor at python.org > Subject: Re: [Tutor] I am trying to print list elements but i am > getting 'none' > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > On Mon, Oct 10, 2011 at 8:26 AM, Praveen Singh > wrote: > >> print myList.append(numbers) > > > Your problem is with that statement. > >>>> mylist = [] >>>> x = mylist.append(3) >>>> x >>>> x is None > True >>>> help(mylist.append) > Help on built-in function append: > > append(...) > L.append(object) -- append object to end > > > append returns None (all functions do, unless you explicitly return > something that is not None) > > HTH, > Wayne > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 6 > Date: Mon, 10 Oct 2011 17:52:00 +0100 > From: Bod Soutar > To: Praveen Singh > Cc: tutor at python.org > Subject: Re: [Tutor] I am trying to print list elements but i am > getting 'none' > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > On 10 October 2011 14:26, Praveen Singh wrote: >> This is my code- >> ?def getNumbers(num): >> ??? myList=[] >> ??? for numbers in range(0,num,2): >> ????????? print myList.append(numbers) >> >> >> output- >>>>> getNumbers(10) >> None >> None >> None >> None >> None >> >> Then i find out that list.append doesn't return anything.Then what should >> i >> use for this kind of operation.but if i do something like this on idle's >> interpreter it gives me answer- >>>>> myList=[] >>>>> myList.append(8) >>>>> print myList >> [8] >> >> Confused!!! >> >> >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > Print your list after you have appended to it. > > def getNumbers(num): > myList=[] > for numbers in range(0,num,2): > myList.append(numbers) > > for item in list: > print item > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 92, Issue 54 > ************************************* > From waynejwerner at gmail.com Mon Oct 10 21:28:57 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 10 Oct 2011 14:28:57 -0500 Subject: [Tutor] swapping list elements based on some criterion In-Reply-To: References: Message-ID: 2011/10/7 Emad Nawfal (??? ???? ???) > I want to re-structure English so that the adjectives appear after the > nouns, instead of before. > If I have a sentence like: > > The tall man plays well > I need to change it to > The man tall plays well > Others have offered plenty of help, though I noticed that no one mentioned the Natural Language Tool Kit (http://www.nltk.org/) which is quite powerful if you're playing around with language processing. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 10 23:44:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Oct 2011 22:44:44 +0100 Subject: [Tutor] help In-Reply-To: References: Message-ID: On 10/10/11 20:23, George Nyoro wrote: > On 10/10/2011, tutor-request at python.org wrote: >> Send Tutor mailing list submissions to >> tutor at python.org >> >> To subscribe or unsubscribe via the World Wide Web, visit >> ....snip .... >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." >> And please do not resend the entire content of the digest back to the list, we've mostly read them all already. If you have a new question start a new thread. If you want to respond to something in the digest then edit away all the irrelevant stuff. As it is, I cannot see anything in the message from you apart from the first (auto-generated) line. Do you have a question? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mnickey at gmail.com Tue Oct 11 00:13:04 2011 From: mnickey at gmail.com (Mike Nickey) Date: Mon, 10 Oct 2011 15:13:04 -0700 Subject: [Tutor] Finding if a passed variable is within to set parameters Message-ID: Hey all, I'm trying to write a def that has a check to see if the entered information is within a pre-determined valid set. Below is what I have so far but it doesn't seem to be working properly. What I want is to have the user be able to enter 1 through 8 and have the information pass fine but anything else would cause the user to repeat the process. I'm using a while loop to try to do this. The only other thing I can think of to do is incorporate a list and see if I can check the list to complete this. Any assistance would be greatly appreciated. def getUserSkillLvl(GameType): #GameType is an in of 8 or 9 passed to this def based on previous input temp = 0 while temp == 0: if GameType == 8: UserSkillLvl = raw_input("Enter your current skill level: ") int(UserSkillLvl) if ((UserSkillLvl <= 8) and (UserSkillLvl >=1)): print "thank you" temp = 1 break elif (UserSkillLvl >8) or (UserSkillLvl < 1): while temp == 0: UserSkillLvl = raw_input("Please re-enter your skill level: ") return UserSkillLvl Best, Mike Nickey mnickey at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Oct 11 00:21:24 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 11 Oct 2011 09:21:24 +1100 Subject: [Tutor] swapping list elements based on some criterion In-Reply-To: References: Message-ID: <4E936FE4.9080006@pearwood.info> Wayne Werner wrote: > 2011/10/7 Emad Nawfal (??? ???? ???) > >> I want to re-structure English so that the adjectives appear after the >> nouns, instead of before. >> If I have a sentence like: >> >> The tall man plays well >> I need to change it to >> The man tall plays well >> > > Others have offered plenty of help, though I noticed that no one mentioned > the Natural Language Tool Kit (http://www.nltk.org/) which is quite powerful > if you're playing around with language processing. I assumed that since the words were already tagged as /N /ADJ etc. that the poster was already using NLT. -- Steven From marc.tompkins at gmail.com Tue Oct 11 00:21:38 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 10 Oct 2011 15:21:38 -0700 Subject: [Tutor] Finding if a passed variable is within to set parameters In-Reply-To: References: Message-ID: On Mon, Oct 10, 2011 at 3:13 PM, Mike Nickey wrote: > Hey all, > > I'm trying to write a def that has a check to see if the entered > information is within a pre-determined valid set. > Below is what I have so far but it doesn't seem to be working properly. > What I want is to have the user be able to enter 1 through 8 and have the > information pass fine but anything else would cause the user to repeat the > process. > I'm using a while loop to try to do this. The only other thing I can think > of to do is incorporate a list and see if I can check the list to complete > this. > > Any assistance would be greatly appreciated. > > def getUserSkillLvl(GameType): #GameType is an in of 8 or 9 passed to this > def based on previous input > temp = 0 > while temp == 0: > if GameType == 8: > UserSkillLvl = raw_input("Enter your current skill level: ") > int(UserSkillLvl) > if ((UserSkillLvl <= 8) and (UserSkillLvl >=1)): > print "thank you" > temp = 1 > break > elif (UserSkillLvl >8) or (UserSkillLvl < 1): > while temp == 0: > UserSkillLvl = raw_input("Please re-enter your skill > level: ") > return UserSkillLvl > > int() is a function, not a statement - it returns a value, but doesn't change the value you pass in to it. (Generally, things with () at the end are functions... there are exceptions, but it's a useful rule of thumb.) So UserSkillLvl is a string when the user enters it - you run int() on it, but throw away the result - it's still a string a moment later when you try to see whether it's <=8 or >=1. You could do > UserSkillLvl = int(UserSkillLvl) or > if ((int(UserSkillLvl) <= 8) and (int(UserSkillLvl) >=1)): Your choice. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Oct 11 00:20:53 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 11 Oct 2011 09:20:53 +1100 Subject: [Tutor] Finding if a passed variable is within to set parameters In-Reply-To: References: Message-ID: <4E936FC5.2030004@pearwood.info> Mike Nickey wrote: > Hey all, > > I'm trying to write a def that has a check to see if the entered information is within a pre-determined valid set. > Below is what I have so far but it doesn't seem to be working properly. > What I want is to have the user be able to enter 1 through 8 and have the information pass fine but anything else would cause the user to repeat the process. > I'm using a while loop to try to do this. The only other thing I can think of to do is incorporate a list and see if I can check the list to complete this. You convert the user's response into an integer, but don't do anything with it: it just gets immediately thrown away. Change the line: int(UserSkillLvl) to UserSkillLvl = int(UserSkillLvl) -- Steven From alan.gauld at btinternet.com Tue Oct 11 02:46:47 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Oct 2011 01:46:47 +0100 Subject: [Tutor] Finding if a passed variable is within to set parameters In-Reply-To: References: Message-ID: On 10/10/11 23:13, Mike Nickey wrote: > What I want is to have the user be able to enter 1 through 8 and have > the information pass fine but anything else would cause the user to > repeat the process. if not (1 <= value <= 8): # handle error else: # carry on as planned > I'm using a while loop to try to do this. You will need a loop if you want to keep trying till the user gets it right > The only other thing I can think of to do is incorporate > a list and see if I can check the list to complete this. That's another option, particularly common with characters: if ch not in "yYnNqQ": # deal with error else: # carry on For your case it could be if value not in range(1,9): # handle error else: # carry on But the <=> test above is more efficient, especially for large ranges. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From g.nius.ck at gmail.com Tue Oct 11 02:56:21 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Mon, 10 Oct 2011 20:56:21 -0400 Subject: [Tutor] String switch In-Reply-To: <4E91CD28.1050905@davea.name> References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> <4E8DCB8C.6090301@gmail.com> <4E90D06C.5060203@gmail.com> <4E91CD28.1050905@davea.name> Message-ID: Okay, there is a python file called target.py. In the same directory there is a file named main.py. You are the author of main.py. The code in main.py will write to target.py. Then the antivirus catches main.py and removes, but not the modification to target.py. Main.py can not create new files. What would Main.py have to write to target.py, so that its output is swapped case. It does not matter how this is achieved. I know that one way is to do a regex search for every string in the file and then write the text of the file, with swapcases after strings, back to the file. What is a more elegant way for this to be achieved. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Oct 11 03:31:17 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 11 Oct 2011 12:31:17 +1100 Subject: [Tutor] String switch In-Reply-To: References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> <4E8DCB8C.6090301@gmail.com> <4E90D06C.5060203@gmail.com> <4E91CD28.1050905@davea.name> Message-ID: <4E939C65.7050309@pearwood.info> Christopher King wrote: > Okay, there is a python file called target.py. In the same directory there > is a file named main.py. You are the author of main.py. The code in main.py > will write to target.py. Then the antivirus catches main.py and removes, but > not the modification to target.py. Main.py can not create new files. What > would Main.py have to write to target.py, so that its output is swapped > case. It does not matter how this is achieved. I know that one way is to do > a regex search for every string in the file and then write the text of the > file, with swapcases after strings, back to the file. What is a more elegant > way for this to be achieved. What makes you think that target.py contains any strings at all? Or that the strings are only used for output? Why do you say that main.py is deleted by "the anti-virus"? (Which anti-virus?) Has this actually happened to you, or is this a hypothetical question? If you have target.py on your computer, why don't you just edit it yourself instead of trying to write a script to modify it? Or better still, leave target.py alone and just pipe the output to a second script which runs swapcase on its input? Something like this should work: # swapcase script import sys sys.stdout.write(sys.stdin.read().swapcase()) then from the shell: python swapcase.py < python target.py (All of the above is untested, but should work on Linux or Mac, and probably even Windows.) -- Steven From d at davea.name Tue Oct 11 06:45:57 2011 From: d at davea.name (Dave Angel) Date: Tue, 11 Oct 2011 00:45:57 -0400 Subject: [Tutor] String switch In-Reply-To: References: <4E8948DA.50302@gmail.com> <4E8B9FD5.5070602@gmail.com> <4E8DCB8C.6090301@gmail.com> <4E90D06C.5060203@gmail.com> <4E91CD28.1050905@davea.name> Message-ID: <4E93CA05.7010302@davea.name> On 10/10/2011 08:56 PM, Christopher King wrote: > Okay, there is a python file called target.py. In the same directory there > is a file named main.py. You are the author of main.py. The code in main.py > will write to target.py. Then the antivirus catches main.py and removes, but > not the modification to target.py. Main.py can not create new files. What > would Main.py have to write to target.py, so that its output is swapped > case. It does not matter how this is achieved. I know that one way is to do > a regex search for every string in the file and then write the text of the > file, with swapcases after strings, back to the file. What is a more elegant > way for this to be achieved. > I'll try once more, before giving up. You want to put something at the head of target.py that has some effect on the running of that script. Which is it you want, "output is swapped case"? Or do you want the equivalent of putting swapcase() after each literal string? You can't have it both ways, since swapping the case of literals does not affect all output. And it affects things that are not output. -- DaveA From emohamed at umail.iu.edu Tue Oct 11 06:19:31 2011 From: emohamed at umail.iu.edu (Emad Mohamed) Date: Tue, 11 Oct 2011 07:19:31 +0300 Subject: [Tutor] swapping list elements based on some criterion In-Reply-To: <4E936FE4.9080006@pearwood.info> References: <4E936FE4.9080006@pearwood.info> Message-ID: On Tue, Oct 11, 2011 at 1:21 AM, Steven D'Aprano wrote: > Wayne Werner wrote: > >> 2011/10/7 Emad Nawfal (??? ???? ???) >> >> I want to re-structure English so that the adjectives appear after the >>> nouns, instead of before. >>> If I have a sentence like: >>> >>> The tall man plays well >>> I need to change it to >>> The man tall plays well >>> >>> >> Others have offered plenty of help, though I noticed that no one mentioned >> the Natural Language Tool Kit (http://www.nltk.org/) which is quite >> powerful >> if you're playing around with language processing. >> > > I assumed that since the words were already tagged as /N /ADJ etc. that the > poster was already using NLT. > > > -- > Steven > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Hi, I actually used the POS tagger available here to tag the English text. http://www-tsujii.is.s.u-tokyo.ac.jp/~tsuruoka/postagger/ The NLTK should be worth looking into. Best, -- Emad Soliman Ali Mohamed aka Emad Nawfal (*???? ????*) PhD in Linguistics, Computational Linguistics Track, Department of Linguistics, Indiana University, Bloomington http://jones.ling.indiana.edu/~emadnawfal -------------- next part -------------- An HTML attachment was scrubbed... URL: From rail.shafigulin at gmail.com Tue Oct 11 16:20:25 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Tue, 11 Oct 2011 10:20:25 -0400 Subject: [Tutor] inheritance, python and pygame Message-ID: i'm trying to learn OOP, python and pygame at the same time. so far it has been ok, but i stumbled onto a problem here is the code that causes problems #!/usr/bin/python3.1 import pygame pygame.init() class BaseSprite(pygame.sprite.Sprite): def __init(self, imagefile): super(type(self), self).__init__() self.image = pygame.image.load(imagefile) self.image = self.image.convert() self.rect = self.image.get_rect() class Cloud(BaseSprite): """ cloud sprite scrolls down and moves side to side when it is reset """ IMAGE = 'cloud.gif' def __init__(self): super(type(self), self).__init__(type(self).IMAGE) def main(): cloud = Cloud() if __name__ == '__main__': main() when i run i get the following error: ........................... File "/usr/local/lib/python3.1/dist-packages/pygame/sprite.py", line 129, in add else: self.add(*group) File "/usr/local/lib/python3.1/dist-packages/pygame/sprite.py", line 129, in add else: self.add(*group) File "/usr/local/lib/python3.1/dist-packages/pygame/sprite.py", line 129, in add else: self.add(*group) File "/usr/local/lib/python3.1/dist-packages/pygame/sprite.py", line 129, in add else: self.add(*group) File "/usr/local/lib/python3.1/dist-packages/pygame/sprite.py", line 129, in add else: self.add(*group) File "/usr/local/lib/python3.1/dist-packages/pygame/sprite.py", line 129, in add else: self.add(*group) File "/usr/local/lib/python3.1/dist-packages/pygame/sprite.py", line 129, in add else: self.add(*group) RuntimeError: maximum recursion depth exceeded while calling a Python object i can't figure out where and why the recursion occurs. can someone help me out? any advice is appreciated -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Tue Oct 11 16:56:50 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 11 Oct 2011 16:56:50 +0200 Subject: [Tutor] inheritance, python and pygame In-Reply-To: References: Message-ID: On Tue, Oct 11, 2011 at 4:20 PM, rail shafigulin wrote: > i'm trying to learn OOP, python and pygame at the same time. so far it has > been ok, but i stumbled onto a problem > > here is the code that causes problems > > #!/usr/bin/python3.1 > import pygame > pygame.init() > > class BaseSprite(pygame.sprite.Sprite): > ? def __init(self, imagefile): > ??? super(type(self), self).__init__() > ??? self.image = pygame.image.load(imagefile) > ??? self.image = self.image.convert() > ??? self.rect = self.image.get_rect() > > class Cloud(BaseSprite): > ? """ > ? cloud sprite > ? scrolls down and moves side to side when it is reset > ? """ > ? IMAGE = 'cloud.gif' > ? def __init__(self): > ??? super(type(self), self).__init__(type(self).IMAGE) > > def main(): > ? cloud = Cloud() > > if __name__ == '__main__': > ? main() > Well, for one, you misspelled __init__ in the BaseSprite class above (you have it written as __init). That means that method won't be called at all, which is likely what is causing problems. Also, when using python3, you don't need to specify any arguments to super. Just calling super() will work. Hugo From ilhs_hs at yahoo.com Tue Oct 11 19:16:35 2011 From: ilhs_hs at yahoo.com (Hs Hs) Date: Tue, 11 Oct 2011 10:16:35 -0700 (PDT) Subject: [Tutor] vcf_files and strings In-Reply-To: <4E9252C2.6030804@pearwood.info> References: <4E9252C2.6030804@pearwood.info> Message-ID: <1318353395.41212.YahooMailNeo@web111213.mail.gq1.yahoo.com> VCF - Variant Call Format VCF files are nothing special but tab delim files describing the genetic mutations, friquencies and other base information (bases here mean ATGC pertaining to DNA). These files are generated by variety of genome sequence data analysis pipelines.? MIT and Haplotype Mapping Project consortium developed this format. Nothing special except that a genetics or any biologist will understand this - nothing special! hth cheers ________________________________ From: Steven D'Aprano To: tutor at python.org Sent: Sunday, October 9, 2011 10:04 PM Subject: Re: [Tutor] vcf_files and strings Anna Olofsson wrote: > Hi, > > I'm a beginner at Python and would really like some help in how to > extract information from a vcf file. > > The attached file consists of a lot of information on mutations, this > one though is just 2 rows and 10 columns (the real one has a lot more > rows). What do you mean by a VCF file? On my computer, a VCF file is an electronic business card, which tries to open in an Address Book application (which obviously fails). I don't know how to interpret the contents of your VCF file. After opening it in a hex editor, I can *guess* that it is a tab-separated file: each row takes one line, with the columns separated by tab characters. Column 7 appears to be a great big ugly blob with sub-fields separated by semi-colons. Am I right? Can you link us to a description of the vcf file format? > I want to extract the mRNA ID only if the mutation is missense. These > two rows (mutations) that I have attached happens to be missense but > how do I say that I'm not interested in the mutations that's not > missense (they might be e.g. synonymous).? Also, how do I say that if > a mutation starts with a # symbol I don't want to include it > (sometimes the chr starts with a hash). What chr? Where is the mutation? I'm afraid your questions are assuming familiarity with your data that we don't have. > vcf file: 2 rows, 10 columns. > col 0? ? ? ? ? ? ? ? ? ? ? ? col 1? ? ? ? ? ? col 2 > col 3? ? ? ? ? ? ? col 4? ? ? col5? ? ? ? ? ? col6 > col7? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? col8 > col9 chromosome? ? ? ? ? position? ? ? ? ? . > Reference? ? ? ALT? ? ? position? ? ? ? ? .? ? ? ? ? some statistics > and the ID:s? ? ? ? not important? ? ? ? not important > > The important column is 7 where the ID is, i.e. > refseq.functionalClass=missense. It's a missense mutation, so then I > want to extract refseq.name=NM_003137492, or I want to extract only > the ID, which in this case is NM_003137492. This is what I *think* you want to do. Am I right? * read each line of the file * for each line, split on tabs * extract the 7th column and split it on semi-colons * inspect the refseq.functionalClass field * if it matches, extract the ID from the refseq.name and store it in a list for later (I have completely ignored the part about the #, because I don't understand what you mean by it.) Here's some code to do it: ids = [] f = open('vcf_file.vcf', 'r') for row in f: ? ? columns = row.split('\t')? # Split on tabs ? ? data = columns[7]? # Huge ugly blob of data ? ? values = data.split(';')? # Split on semi-colons ? ? if values[25] == "refseq.functionalClass=missense": ? ? ? ? name_chunk = values[28]? # looks like "refseq.name=..." ? ? ? ? a, b = name_chunk.split("=") ? ? ? ? if a != "refseq.name": ? ? ? ? ? ? raise ValueError('expected refseq.name but got %s' % a) ? ? ? ? ids.append(b) f.close() print(ids) Does this help? -- Steven _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Oct 11 19:52:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Oct 2011 18:52:35 +0100 Subject: [Tutor] vcf_files and strings In-Reply-To: <1318353395.41212.YahooMailNeo@web111213.mail.gq1.yahoo.com> References: <4E9252C2.6030804@pearwood.info> <1318353395.41212.YahooMailNeo@web111213.mail.gq1.yahoo.com> Message-ID: On 11/10/11 18:16, Hs Hs wrote: > > VCF - Variant Call Format > ... > > Nothing special except that a genetics or any biologist will understand > this - nothing special! The problem is that this list, being for beginners to Python, is a bit short on Geneticists and Biologists! :-) So you need to explain your problem in general terms, that the rest of us can make sense of, or else rely on the few who might understand being available/willing to respond. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rail.shafigulin at gmail.com Tue Oct 11 20:08:25 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Tue, 11 Oct 2011 14:08:25 -0400 Subject: [Tutor] inheritance, python and pygame In-Reply-To: References: Message-ID: On Tue, Oct 11, 2011 at 10:56 AM, Hugo Arts wrote: > On Tue, Oct 11, 2011 at 4:20 PM, rail shafigulin > wrote: > > i'm trying to learn OOP, python and pygame at the same time. so far it > has > > been ok, but i stumbled onto a problem > > > > here is the code that causes problems > > > > #!/usr/bin/python3.1 > > import pygame > > pygame.init() > > > > class BaseSprite(pygame.sprite.Sprite): > > def __init(self, imagefile): > > super(type(self), self).__init__() > > self.image = pygame.image.load(imagefile) > > self.image = self.image.convert() > > self.rect = self.image.get_rect() > > > > class Cloud(BaseSprite): > > """ > > cloud sprite > > scrolls down and moves side to side when it is reset > > """ > > IMAGE = 'cloud.gif' > > def __init__(self): > > super(type(self), self).__init__(type(self).IMAGE) > > > > def main(): > > cloud = Cloud() > > > > if __name__ == '__main__': > > main() > > > > Well, for one, you misspelled __init__ in the BaseSprite class above > (you have it written as __init). That means that method won't be > called at all, which is likely what is causing problems. > > Also, when using python3, you don't need to specify any arguments to > super. Just calling super() will work. > > Hugo > my apologies for not writing and reading my own code correctly. Hugo you were correct, once i fixed the spelling error it all worked. and thanks for the hint on how to use super() in python3. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ilhs_hs at yahoo.com Tue Oct 11 22:04:33 2011 From: ilhs_hs at yahoo.com (Hs Hs) Date: Tue, 11 Oct 2011 13:04:33 -0700 (PDT) Subject: [Tutor] vcf_files and strings In-Reply-To: References: <4E9252C2.6030804@pearwood.info> <1318353395.41212.YahooMailNeo@web111213.mail.gq1.yahoo.com> Message-ID: <1318363473.31294.YahooMailNeo@web111201.mail.gq1.yahoo.com> http://www.1000genomes.org/node/101 ________________________________ From: Alan Gauld To: tutor at python.org Sent: Tuesday, October 11, 2011 1:52 PM Subject: Re: [Tutor] vcf_files and strings On 11/10/11 18:16, Hs Hs wrote: > > VCF - Variant Call Format > ... > > Nothing special except that a genetics or any biologist will understand > this - nothing special! The problem is that this list, being for beginners to Python, is a bit short on Geneticists and Biologists! :-) So you need to explain your problem in general terms, that the rest of us can make sense of, or else rely on the few who might understand being available/willing to respond. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Oct 12 00:41:20 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 12 Oct 2011 09:41:20 +1100 Subject: [Tutor] inheritance, python and pygame In-Reply-To: References: Message-ID: <4E94C610.8030603@pearwood.info> rail shafigulin wrote: > i'm trying to learn OOP, python and pygame at the same time. so far it has > been ok, but i stumbled onto a problem Hugo has already pointed out that you mispelled __init__, and that in Python 3 you don't need to explicitly provide arguments to super(). > class BaseSprite(pygame.sprite.Sprite): > def __init(self, imagefile): > super(type(self), self).__init__() Should be written like this in Python 3: def __init__(self, imagefile): super().__init__() However, for those still using Python 2.x, you might be tempted to write this: def __init__(self, imagefile): super(type(self), self).__init__() # NO! Don't do this! This does not work! But you might be fooled into thinking it does work, because it *seems* to work if you only check a simple example: class Base(object): def __init__(self): print "Base called" class Subclass(Base): def __init__(self): print "Subclass called" super(type(self), self).__init__() # Wrong! It seems to work: >>> x = Subclass() Subclass called Base called But watch what happens when we subclass again: class AnotherSubclass(Subclass): def __init__(self): print "AnotherSubclass called" super(type(self), self).__init__() >>> y = AnotherSubclass() AnotherSubclass called Subclass called Subclass called Subclass called ... Traceback (most recent call last): File "", line 1, in File "", line 4, in __init__ File "", line 4, in __init__ File "", line 4, in __init__ File "", line 4, in __init__ ... RuntimeError: maximum recursion depth exceeded The problem is that inside Subclass.__init__ the call to super(type(self), self) does not necessary give super(Subclass, self). If the instance being created is from AnotherSubclass, you get super(AnotherSubclass, self) inside the Subclass.__init__, which then loops forever. So in Python 2.x, you must explicitly give the class. You can't use type(self). -- Steven From ryan.strunk at gmail.com Wed Oct 12 03:32:52 2011 From: ryan.strunk at gmail.com (Ryan Strunk) Date: Tue, 11 Oct 2011 20:32:52 -0500 Subject: [Tutor] Keyboard Module Message-ID: <017d01cc887e$e02a7f00$a07f7d00$@gmail.com> Hello everyone, I'm still hard at work on this boxing game; I know, I think it's taking forever too. I've recently run into some trouble with my current keyboard handler, and I'm hoping someone here might have a recommendation as to what I could use to handle keyboard input for this and future projects. The keyboard module I currently have access to is a wrapper for the wx keyboard handler, which is fine, but it prevents me from holding one key and pressing another. In an ideal world, I'd love something like this: def left_hand(self): if key_down('up'): self.left_head_hook() elif key_down('down'): self.left_uppercut() elif key_down('left'): self.left_body_hook() else: self.jab() The above functionality could be useful in other places as well. I would like to some day create a keyboard trainer for my students, giving them the ability to practice key combinations like capslock+t, control+alt+pgdn, numpad0+numpad4, and so on. I thought of using Pygame to pull this off, but I gather from my research that I can't just use certain pieces of Pygame; in order to get the functionality I want out of the keyboard module, I'll need other modules as well. I don't want to work specifically in Pygame, because I've heard Pygame is quite bloated and requires a good deal of overhead. (I wouldn't mind being proven wrong on this) All of which leads me to my question. Can anyone recommend a keyboard module which will allow me to work with various facets of the keyboard to execute functions. I would love to have access to presses, holds, and releases, and it would be helpful to use unorthodox combinations of keys. Thanks for any recommendations or advice you all have. Best, Ryan From lina.lastname at gmail.com Wed Oct 12 05:31:42 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 12 Oct 2011 11:31:42 +0800 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E90A2@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E90A2@EMARC112VS01.exchad.jpmchase.net> Message-ID: I tried to write one (not working one) as below, so many problems here. #!/usr/bin/python3 import os.path LINESTOSKIP=0 CHAINID="CDEFGHI" INFILENAME="pdbone.pdb" DICTIONARYFILE="itpone.itp" mapping={} valuefromdict={} def sortfile(): for chainid in CHAINID: sortoneblock(chainid) def generatedictionary(dictfilename): text=fetchonefiledata(DICTIONARYFILE) for line in text: parts=line.strip().split() if len(parts)==8: mapping[parts[4]]=parts[0] print(mapping) def sortoneblock(cID) text=fetchonefiledata(INFILENAME) for line in text: blocks=line.strip().split() if len(blocks)== 11 and blocks[3] == "CUR" and blocks[4] == "cID": valuefromdict[blocks[2]]=mapping[block[2]] return def fetchonefiledata(infilename): text=open("infilename").readlines() if os.path.splitext(infilename)[1]=".itp" return text if os.path.splitext(infilename)[1]=".pdb" return text[LINESTOSKIP:] if __name__=="__main__": sortfiles() The representative lines from itpone.itp is: 1 CH3 1 CUR C21 1 0.200 15.0350 2 OA 1 CUR O4 1 -0.400 15.9994 3 C 1 CUR C19 1 0.200 12.0110 The representative lines from pdbone.pdb is: ATOM 827 C19 CUR C 85 31.891 29.624 0.280 1.00 0.00 ... ATOM 831 O4 CUR C 85 31.865 28.248 0.183 1.00 0.00 ATOM 832 C21 CUR C 85 32.823 27.366 0.801 1.00 0.00 The expected results of pdbone.pdb will be: ATOM 832 C21 CUR C 85 32.823 27.366 0.801 1.00 0.00 ATOM 831 O4 CUR C 85 31.865 28.248 0.183 1.00 0.00 ATOM 827 C19 CUR C 85 31.891 29.624 0.280 1.00 0.00 Thanks for telling me the existing problems. Best regards, -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Wed Oct 12 09:29:40 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Wed, 12 Oct 2011 09:29:40 +0200 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E90A2@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E9541E4.6050609@gmx.net> On 2011-10-12 05:31, lina wrote: > I tried to write one (not working one) as below, so many problems here. Just some quick remarks: > #!/usr/bin/python3 > > import os.path > > LINESTOSKIP=0 > CHAINID="CDEFGHI" > INFILENAME="pdbone.pdb" > DICTIONARYFILE="itpone.itp" > mapping={} > valuefromdict={} > > def sortfile(): > for chainid in CHAINID: > sortoneblock(chainid) > > > def generatedictionary(dictfilename): You define the function with the parameter "dictfilename" but you'll never use it. > text=fetchonefiledata(DICTIONARYFILE) > for line in text: > parts=line.strip().split() > if len(parts)==8: > mapping[parts[4]]=parts[0] > print(mapping) The if-branch is probably wrongly indented (should be inside the for-loop). > def sortoneblock(cID) > text=fetchonefiledata(INFILENAME) > for line in text: > blocks=line.strip().split() > if len(blocks)== 11 and blocks[3] == "CUR" and blocks[4] == "cID": "cID" is a string-variable but you compare block 4 to the literal string "cID". In "pdbone.pdb" you will never find "cID" so this function will do nothing. You probably mean "blocks[4] == cID". > valuefromdict[blocks[2]]=mapping[block[2]] You never fill up "mapping" because you never call your "generatedictionary"-function. Therefore "mapping" is still an empty dictionary and this line will raise an exception. > return Firstly, the indentation is wrong because you would leave "sortoneblock" after the first processed line. Secondly, as you return nothing, you don't need this line because you will leave the function anyway. > > > def fetchonefiledata(infilename): > text=open("infilename").readlines() Again, "infilename" is a variable, so no need for the quotes. > if os.path.splitext(infilename)[1]=".itp" > return text > if os.path.splitext(infilename)[1]=".pdb" > return text[LINESTOSKIP:] > > > if __name__=="__main__": > sortfiles() There is no "sortfiles()" in your script. The function you probably mean is called "sortfile()" Bye, Andreas From alan.gauld at btinternet.com Wed Oct 12 09:57:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Oct 2011 08:57:42 +0100 Subject: [Tutor] Keyboard Module In-Reply-To: <017d01cc887e$e02a7f00$a07f7d00$@gmail.com> References: <017d01cc887e$e02a7f00$a07f7d00$@gmail.com> Message-ID: On 12/10/11 02:32, Ryan Strunk wrote: > The keyboard module I currently have access to is a wrapper for the wx > keyboard handler, which is fine, but it prevents me from holding one key and > pressing another. So use raw wx key events. They include key down,up and press events. > I thought of using Pygame to pull this off, but I gather from my research > that I can't just use certain pieces of Pygame; in order to get the > functionality I want out of the keyboard module, I'll need other modules as > well. I don't want to work specifically in Pygame, because I've heard Pygame > is quite bloated and requires a good deal of overhead. (I wouldn't mind > being proven wrong on this) Bloated carries the connotation of unnecessary code, but pygame provides a lot of functionality. You may not need it all, and using pygame may require you to import more than you need. But thats not quite the same as saying pygame is bloated. And its not that huge that it should stop you using it. If it works, why not? > All of which leads me to my question. Can anyone recommend a keyboard module > which will allow me to work with various facets of the keyboard to execute > functions. Since you mentioned wx I assume thats the GUI you are using. If not you can also investigate Tkinter which likewise traps keyboard events and might be considered slightly easier to use. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Wed Oct 12 10:27:28 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 12 Oct 2011 16:27:28 +0800 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <4E9541E4.6050609@gmx.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E90A2@EMARC112VS01.exchad.jpmchase.net> <4E9541E4.6050609@gmx.net> Message-ID: On Wed, Oct 12, 2011 at 3:29 PM, Andreas Perstinger < andreas.perstinger at gmx.net> wrote: > On 2011-10-12 05:31, lina wrote: > >> I tried to write one (not working one) as below, so many problems here. >> > > Just some quick remarks: Thanks, Now the newly-improved one as following: but still the "sort" parts did not work. #!/usr/bin/python3 import os.path LINESTOSKIP=0 CHAINID="CDEFGHI" INFILENAME="pdbone.pdb" DICTIONARYFILE="itpone.itp" mapping={} valuefromdict={} def sortfile(): for chainid in CHAINID: sortoneblock(chainid) def generatedictionary(dictfilename): text=fetchonefiledata(DICTIONARYFILE) for line in text: parts=line.strip().split() if len(parts)==8: mapping[parts[4]]=parts[0] print(mapping) def sortoneblock(cID): text=fetchonefiledata(INFILENAME) for line in text: blocks=line.strip().split() if len(blocks)== 11 and blocks[3] == "CUR" and blocks[4] == cID and blocks[2] in mapping.keys(): valuefromdict[cID]=mapping[blocks[2]] print(valuefromdict) def fetchonefiledata(infilename): text=open(infilename).readlines() if os.path.splitext(infilename)[1]==".itp": return text if os.path.splitext(infilename)[1]==".pdb": return text[LINESTOSKIP:] if __name__=="__main__": generatedictionary(DICTIONARYFILE) sortfile() The result is: $ python3 map-to-itp.py {'O4': '2', 'C19': '3', 'C21': '1'} {'C': '3'} {'C': '2'} {'C': '1'} for print(mapping) part, {'O4': '2', 'C19': '3', 'C21': '1'} the value doesn't keep the 1, 2, 3 order any more. Thanks for further suggestions. The relevant files I put it here: https://docs.google.com/leaf?id=0B93SVRfpVVg3NzkyOGU2ZTUtZTFjNC00ZjE4LThhNmQtOWY1YWFkOWI0NWEw&hl=en_GB https://docs.google.com/leaf?id=0B93SVRfpVVg3YTEwZjhiOTItN2I2Yi00NTEyLTljODAtYTc2ODI4Njk1YzZl&hl=en_GB https://docs.google.com/leaf?id=0B93SVRfpVVg3M2Y1MWZiMmEtOTE2Mi00M2VjLTljNjAtYWNlMjhiNzEyODY1&hl=en_GB > > #!/usr/bin/python3 >> >> import os.path >> >> LINESTOSKIP=0 >> CHAINID="CDEFGHI" >> INFILENAME="pdbone.pdb" >> DICTIONARYFILE="itpone.itp" >> mapping={} >> valuefromdict={} >> >> def sortfile(): >> for chainid in CHAINID: >> sortoneblock(chainid) >> >> >> def generatedictionary(**dictfilename): >> > > You define the function with the parameter "dictfilename" but you'll never > use it. > > > text=fetchonefiledata(**DICTIONARYFILE) >> for line in text: >> parts=line.strip().split() >> if len(parts)==8: >> mapping[parts[4]]=parts[0] >> print(mapping) >> > > The if-branch is probably wrongly indented (should be inside the for-loop). > > > def sortoneblock(cID) >> text=fetchonefiledata(**INFILENAME) >> for line in text: >> blocks=line.strip().split() >> if len(blocks)== 11 and blocks[3] == "CUR" and blocks[4] == >> "cID": >> > > > "cID" is a string-variable but you compare block 4 to the literal string > "cID". In "pdbone.pdb" you will never find "cID" so this function will do > nothing. You probably mean "blocks[4] == cID". > > > valuefromdict[blocks[2]]=**mapping[block[2]] >> > > You never fill up "mapping" because you never call your > "generatedictionary"-function. Therefore "mapping" is still an empty > dictionary and this line will raise an exception. > > return >> > > Firstly, the indentation is wrong because you would leave "sortoneblock" > after the first processed line. Secondly, as you return nothing, you don't > need this line because you will leave the function anyway. > > > >> >> def fetchonefiledata(infilename): >> text=open("infilename").**readlines() >> > > Again, "infilename" is a variable, so no need for the quotes. > > > if os.path.splitext(infilename)[**1]=".itp" >> return text >> if os.path.splitext(infilename)[**1]=".pdb" >> return text[LINESTOSKIP:] >> >> >> if __name__=="__main__": >> sortfiles() >> > > There is no "sortfiles()" in your script. The function you probably mean is > called "sortfile()" > > Bye, Andreas > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Wed Oct 12 14:50:26 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Wed, 12 Oct 2011 14:50:26 +0200 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E90A2@EMARC112VS01.exchad.jpmchase.net> <4E9541E4.6050609@gmx.net> Message-ID: <4E958D12.4060607@gmx.net> On 2011-10-12 10:27, lina wrote: > $ python3 map-to-itp.py > {'O4': '2', 'C19': '3', 'C21': '1'} > {'C': '3'} > {'C': '2'} > {'C': '1'} > > for print(mapping) part, {'O4': '2', 'C19': '3', 'C21': '1'} the value > doesn't keep the 1, 2, 3 order any more. That's fine, because "mapping" is a dictionary which has no order. From the tutorial (http://docs.python.org/py3k/tutorial/datastructures.html#dictionaries): "It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)." What you want (as far as I understand it) is sorting the lines in "pdbone.pdb" based on the positions in file "itpone.itp". The connection between both files is the column with the values "O4", "C19", "C21", ... (= your keys). You've already succesfully built a dictionary in which you saved the position for every key. For the sorting you could now build a list of tuples of all lines in "pdbone.pdb" you want to sort where the first element in the tuple is the position and the second the line itself. Then you can easily sort this temporary list and write the new ordered lines back to the file: def sortoneblock(cID): text = fetchonefiledata(INFILENAME) temp = [] # create an empty temporary list for line in text: blocks = line.strip().split() if len(blocks) == 11 and blocks[3] == "CUR" and blocks[4] == cID and blocks[2] in mapping.keys(): temp.append((mapping[blocks[2]], line)) # add a tuple to the list which has the following format: (position from the dictionary, complete line) # the following line just shows you, what we have done so far. You can delete it without consequences. for line in temp: print(line) temp.sort() # this sorts the list based on the position # the following line prints the sorted list (just the original line without the position elements). If you want to write the result back to the file you have to exchange "print()" for line in temp: print(line[1]) Bye, Andreas From gerhardus.geldenhuis at gmail.com Wed Oct 12 15:41:37 2011 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Wed, 12 Oct 2011 14:41:37 +0100 Subject: [Tutor] Parsing /etc/passwd Message-ID: Hi I wrote the following code: f = open('/etc/passwd', 'r') users = f.read() userelements = re.findall(r'(\w+):(\w+):(\w+):(\w+):(\w+):(\w+):(\w+)', users) print userelements for user in userelements: (username, encrypwd, uid, gid, gecos, homedir, usershell) = user # unpack the tuple into 7 vars print username but I get no results so my parsing must be wrong but I am not sure why. Incidentally while googling I found the module http://docs.python.org/library/pwd.html which I will eventually use but I am first curious to fix and understand the problem before I throw away this code. Regards -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Wed Oct 12 15:49:43 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 12 Oct 2011 15:49:43 +0200 Subject: [Tutor] Parsing /etc/passwd In-Reply-To: References: Message-ID: On Wed, Oct 12, 2011 at 3:41 PM, Gerhardus Geldenhuis wrote: > Hi > I wrote the following code: > ? f = open('/etc/passwd', 'r') > ? users = f.read() > ? userelements = re.findall(r'(\w+):(\w+):(\w+):(\w+):(\w+):(\w+):(\w+)', > users) > ? print userelements > ? for user in userelements: > ? ? (username, encrypwd, uid, gid, gecos, homedir, usershell) = user ?# > unpack the tuple into 7 vars > ? ? print username > > but I get no results so my parsing must be wrong but I am not sure why. > Incidentally while googling I found the > module?http://docs.python.org/library/pwd.html which I will eventually use > but I am first curious to fix and understand the problem before I throw away > this code. > Regards > the homedir and usershell parts are paths. Paths will contain slashes. The \w character class captures only [A-Za-z0-9_], that is, letters, numbers, and the underscore. That means slashes will not match, and so the entire match fails. On another note, the structure of the /etc/passwd file is pretty simple, I don't think you need regexes. Simply use split: users = f.readlines() for user in users: (username, encrypwd, uid, gid, gecos, homedir, usershell) = user.split(':') HTH, Hugo From gerhardus.geldenhuis at gmail.com Wed Oct 12 15:54:41 2011 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Wed, 12 Oct 2011 14:54:41 +0100 Subject: [Tutor] Parsing /etc/passwd In-Reply-To: References: Message-ID: Fantastic, Thanks Hugo that makes 100% sense now! Testing both regex for including / and doing split and when done throwing both away and using the default module. Regards On Wed, Oct 12, 2011 at 2:49 PM, Hugo Arts wrote: > On Wed, Oct 12, 2011 at 3:41 PM, Gerhardus Geldenhuis > wrote: > > Hi > > I wrote the following code: > > f = open('/etc/passwd', 'r') > > users = f.read() > > userelements = re.findall(r'(\w+):(\w+):(\w+):(\w+):(\w+):(\w+):(\w+)', > > users) > > print userelements > > for user in userelements: > > (username, encrypwd, uid, gid, gecos, homedir, usershell) = user # > > unpack the tuple into 7 vars > > print username > > > > but I get no results so my parsing must be wrong but I am not sure why. > > Incidentally while googling I found the > > module http://docs.python.org/library/pwd.html which I will eventually > use > > but I am first curious to fix and understand the problem before I throw > away > > this code. > > Regards > > > > the homedir and usershell parts are paths. Paths will contain slashes. > The \w character class captures only [A-Za-z0-9_], that is, letters, > numbers, and the underscore. That means slashes will not match, and so > the entire match fails. > > On another note, the structure of the /etc/passwd file is pretty > simple, I don't think you need regexes. Simply use split: > > users = f.readlines() > for user in users: > (username, encrypwd, uid, gid, gecos, homedir, usershell) = > user.split(':') > > HTH, > Hugo > -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Wed Oct 12 15:57:36 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 12 Oct 2011 21:57:36 +0800 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <4E958D12.4060607@gmx.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E90A2@EMARC112VS01.exchad.jpmchase.net> <4E9541E4.6050609@gmx.net> <4E958D12.4060607@gmx.net> Message-ID: On Wed, Oct 12, 2011 at 8:50 PM, Andreas Perstinger < andreas.perstinger at gmx.net> wrote: > On 2011-10-12 10:27, lina wrote: > >> $ python3 map-to-itp.py >> {'O4': '2', 'C19': '3', 'C21': '1'} >> {'C': '3'} >> {'C': '2'} >> {'C': '1'} >> >> for print(mapping) part, {'O4': '2', 'C19': '3', 'C21': '1'} the value >> doesn't keep the 1, 2, 3 order any more. >> > > That's fine, because "mapping" is a dictionary which has no order. From the > tutorial (http://docs.python.org/py3k/**tutorial/datastructures.html#** > dictionaries > ): > "It is best to think of a dictionary as an unordered set of key: value > pairs, with the requirement that the keys are unique (within one > dictionary)." > > What you want (as far as I understand it) is sorting the lines in > "pdbone.pdb" based on the positions in file "itpone.itp". The connection > between both files is the column with the values "O4", "C19", "C21", ... (= > your keys). You've already succesfully built a dictionary in which you saved > the position for every key. > > For the sorting you could now build a list of tuples of all lines in > "pdbone.pdb" you want to sort where the first element in the tuple is the > position and the second the line itself. Then you can easily sort this > temporary list and write the new ordered lines back to the file: > > def sortoneblock(cID): > text = fetchonefiledata(INFILENAME) > temp = [] # create an empty temporary list > > for line in text: > blocks = line.strip().split() > if len(blocks) == 11 and blocks[3] == "CUR" and blocks[4] == cID and > blocks[2] in mapping.keys(): > > temp.append((mapping[blocks[2]**], line)) # add a tuple to the > list which has the following format: (position from the dictionary, complete > line) > > # the following line just shows you, what we have done so far. You can > delete it without consequences. > > for line in temp: print(line) > > temp.sort() # this sorts the list based on the position > > # the following line prints the sorted list (just the original line > without the position elements). If you want to write the result back to the > file you have to exchange "print()" > I do have problems to write each blocks (differentiated by chainID) back one by one, but this will leave it at the end. at present I still have following problems Q1: why the D E F G H I stopped being processed. > > for line in temp: print(line[1]) Thanks. $ python3 map-to-itp.py {'O4': '2', 'C19': '3', 'C21': '1'} C ATOM 832 C21 CUR C 85 32.823 27.366 0.801 1.00 0.00 ATOM 831 O4 CUR C 85 31.865 28.248 0.183 1.00 0.00 ATOM 827 C19 CUR C 85 31.891 29.624 0.280 1.00 0.00 D E F G H I #!/usr/bin/python3 import os.path LINESTOSKIP=0 CHAINID="CDEFGHI" INFILENAME="pdbone.pdb" DICTIONARYFILE="itpone.itp" mapping={} valuefromdict={} def sortfile(): for chainid in CHAINID: print(chainid) sortoneblock(chainid) def sortoneblock(cID): text=fetchonefiledata(INFILENAME) ## Q2: How to avoid read this file every time. actually it only need read once. temp = [] for line in text: blocks=line.strip().split() if len(blocks)== 11 and blocks[3] == "CUR" and blocks[4] == cID and blocks[2] in mapping.keys(): temp.append((mapping[blocks[2]],line)) temp.sort() for line in temp: print(line[1].strip()) def generatedictionary(dictfilename): text=fetchonefiledata(DICTIONARYFILE) for line in text: parts=line.strip().split() if len(parts)==8: mapping[parts[4]]=parts[0] print(mapping) def fetchonefiledata(infilename): text=open(infilename).readlines() if os.path.splitext(infilename)[1]==".itp": return text if os.path.splitext(infilename)[1]==".pdb": return text[LINESTOSKIP:] if __name__=="__main__": generatedictionary(DICTIONARYFILE) sortfile() Thanks. > > > Bye, Andreas > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Oct 12 16:27:13 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Oct 2011 16:27:13 +0200 Subject: [Tutor] Parsing /etc/passwd References: Message-ID: Hugo Arts wrote: >> f = open('/etc/passwd', 'r') > users = f.readlines() > for user in users: ... You can iterate over the file directly: for user in f: ... The version using readlines() reads the whole file into a list of lines where the alternative just has to remember the current line. While it doesn't matter much for small files iterating over the file directly will save a lot of memory if the input file is large. Therefore avoiding readlines() is a good habit to get into. From d at davea.name Wed Oct 12 16:55:10 2011 From: d at davea.name (Dave Angel) Date: Wed, 12 Oct 2011 10:55:10 -0400 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E90A2@EMARC112VS01.exchad.jpmchase.net> <4E9541E4.6050609@gmx.net> <4E958D12.4060607@gmx.net> Message-ID: <4E95AA4E.4020804@davea.name> On 10/12/2011 09:57 AM, lina wrote: > > I do have problems to write each blocks (differentiated by chainID) back > one by one, but this will leave it at the end. at present I still have > following problems > Q1: why the D E F G H I stopped being processed. > In what sense do you mean stopped? There are no records in pdbone.pdb that have column 4 equal to any of the remaining CID values, D, E, F, etc. So they don't print anything. You can see that 3 of them matched cID of "C" >> for line in temp: print(line[1]) > Thanks. > > $ python3 map-to-itp.py > {'O4': '2', 'C19': '3', 'C21': '1'} > C > ATOM 832 C21 CUR C 85 32.823 27.366 0.801 1.00 > 0.00 > ATOM 831 O4 CUR C 85 31.865 28.248 0.183 1.00 > 0.00 > ATOM 827 C19 CUR C 85 31.891 29.624 0.280 1.00 > 0.00 > > D > E > F > G > H > I > > > > > #!/usr/bin/python3 > > import os.path > > LINESTOSKIP=0 > CHAINID="CDEFGHI" > INFILENAME="pdbone.pdb" > DICTIONARYFILE="itpone.itp" > mapping={} > valuefromdict={} > > def sortfile(): > for chainid in CHAINID: > print(chainid) > sortoneblock(chainid) > > > > def sortoneblock(cID): > text=fetchonefiledata(INFILENAME) ## Q2: How to avoid read this file > every time. actually it only need read once. Simple. Move this line into sortfile (before the for loop), and pass text as an argument when it calls sortoneblock(cID, text) Naturally, you'd then add the parameter to sortoneblock(cID, text). Once you try to create the output file, you'll also be adding the open() call for that into sortfile(), and passing its file object into sortoneblock(cID, text, outfile) > temp = [] > for line in text: > blocks=line.strip().split() > if len(blocks)== 11 and blocks[3] == "CUR" and blocks[4] == cID and > blocks[2] in mapping.keys(): > temp.append((mapping[blocks[2]],line)) > temp.sort() > for line in temp: > print(line[1].strip()) > > > def generatedictionary(dictfilename): > text=fetchonefiledata(DICTIONARYFILE) > for line in text: > parts=line.strip().split() > if len(parts)==8: > mapping[parts[4]]=parts[0] > print(mapping) > > > > def fetchonefiledata(infilename): > text=open(infilename).readlines() > if os.path.splitext(infilename)[1]==".itp": > return text > if os.path.splitext(infilename)[1]==".pdb": > return text[LINESTOSKIP:] > > > if __name__=="__main__": > generatedictionary(DICTIONARYFILE) > sortfile() > > Thanks. > > I think your final version of sortfile() might look something like: def sortfile(infilename=INFILENAME, outfilename=OUTFILENAME): infile = open(infilename, "r") intext = infile.readlines() outfile = open(OUTFILENAME, "w") for chainid in CHAINID: print("chain id = ",chainid) sortoneblock(chainid, intext, outfile) infile.close() outfile.close() -- DaveA From ramit.prasad at jpmorgan.com Wed Oct 12 16:54:38 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 12 Oct 2011 10:54:38 -0400 Subject: [Tutor] I am trying to print list elements but i am getting 'none' In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F215C838C@EMARC112VS01.exchad.jpmchase.net> > for item in list: > print item Or you could do this inline with: print ' '.join( myList ) # Change ' ' to be the separator you desire if you want something other than a space between elements? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From olofsson_anna585 at hotmail.com Wed Oct 12 19:21:35 2011 From: olofsson_anna585 at hotmail.com (Anna Olofsson) Date: Wed, 12 Oct 2011 19:21:35 +0200 Subject: [Tutor] extract specific column Message-ID: Hi, I'm a beginner at python and I'm trying to extract a specific column from a txt file ( see attached file). In the attached file I want to extract the entire column pph2_prob (i.e. column 16). But I want to get all the values from that column without the headline pph2_prob. How do I accomplish that? Best, Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: From olofsson_anna585 at hotmail.com Wed Oct 12 21:28:12 2011 From: olofsson_anna585 at hotmail.com (Anna Olofsson) Date: Wed, 12 Oct 2011 21:28:12 +0200 Subject: [Tutor] extract specific column In-Reply-To: References: Message-ID: Hi, I'm a beginner at python and I'm trying to extract a specific column from a txt file ( see attached file). In the attached file I want to extract the entire column pph2_prob (i.e. column 16). But I want to get all the values from that column without the headline pph2_prob. How do I accomplish that? Best, Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Q8WZ55.pph2.txt URL: From waynejwerner at gmail.com Wed Oct 12 21:54:42 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 12 Oct 2011 14:54:42 -0500 Subject: [Tutor] extract specific column In-Reply-To: References: Message-ID: On Wed, Oct 12, 2011 at 12:21 PM, Anna Olofsson < olofsson_anna585 at hotmail.com> wrote: > Hi, > > I'm a beginner at python and I'm trying to extract a specific column from a > txt file ( see attached file). > > In the attached file I want to extract the entire column* pph2_prob *(i.e. > column 16). But I want to get all the values from that column without the > headline * pph2_prob. > > *How do I accomplish that? > Hi Anna, We're more than happy to help, but we also would love to see what you've done so far. What have you tried so far? Can you get the entire column *with* the headline? When you show the effort that you've taken, you'll find people are much more inclined to help - very few people here will do your work for you, but most of us are perfectly willing to point you in the right direction! HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhw at doctors.org.uk Wed Oct 12 21:57:42 2011 From: mhw at doctors.org.uk (Matt Williams) Date: Wed, 12 Oct 2011 20:57:42 +0100 Subject: [Tutor] extract specific column In-Reply-To: References: Message-ID: <4E95F136.2060600@doctors.org.uk> On 12/10/2011 18:21, Anna Olofsson wrote: > Hi, > > I'm a beginner at python and I'm trying to extract a specific column > from a txt file ( see attached file). > > In the attached file I want to extract the entire column/pph2_prob > /(i.e. column 16). But I want to get all the values from that column > without the headline /pph2_prob. > > /How do I accomplish that? > > Best, > Anna > Dear Anna, Using the CSV module should work. Something along the lines of (untested): inLines = CSV.DictReader("/path/to/myfile.csv") data = [] for a in inLines: data.append(a) for line in data: print line["/pph2_prob/"] Once you've got that working you just need to put the results in a file, instead of printing them. On a practical note (and there may be many reasons why not to), it might be easier to open in a spreadsheet and take the data from there.... HTH, Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: From olofsson_anna585 at hotmail.com Wed Oct 12 21:59:34 2011 From: olofsson_anna585 at hotmail.com (Anna Olofsson) Date: Wed, 12 Oct 2011 21:59:34 +0200 Subject: [Tutor] FW: extract specific column In-Reply-To: References: , Message-ID: The thing is, I don't know where to start. I know how to open the attached file, but I don't know how to work inside the file. Is this a csv file? Do I need to use a split function? In what way should I look at the file? As a string? As lines? Best, Anna From: waynejwerner at gmail.com Date: Wed, 12 Oct 2011 14:54:42 -0500 Subject: Re: [Tutor] extract specific column To: olofsson_anna585 at hotmail.com CC: tutor at python.org On Wed, Oct 12, 2011 at 12:21 PM, Anna Olofsson wrote: Hi, I'm a beginner at python and I'm trying to extract a specific column from a txt file ( see attached file). In the attached file I want to extract the entire column pph2_prob (i.e. column 16). But I want to get all the values from that column without the headline pph2_prob. How do I accomplish that? Hi Anna, We're more than happy to help, but we also would love to see what you've done so far. What have you tried so far? Can you get the entire column *with* the headline? When you show the effort that you've taken, you'll find people are much more inclined to help - very few people here will do your work for you, but most of us are perfectly willing to point you in the right direction! HTH,Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From olofsson_anna585 at hotmail.com Wed Oct 12 21:59:58 2011 From: olofsson_anna585 at hotmail.com (Anna Olofsson) Date: Wed, 12 Oct 2011 21:59:58 +0200 Subject: [Tutor] extract specific column In-Reply-To: References: , , Message-ID: From: olofsson_anna585 at hotmail.com To: tutor at python.org Subject: FW: [Tutor] extract specific column Date: Wed, 12 Oct 2011 21:59:34 +0200 The thing is, I don't know where to start. I know how to open the attached file, but I don't know how to work inside the file. Is this a csv file? Do I need to use a split function? In what way should I look at the file? As a string? As lines? Best, Anna From: waynejwerner at gmail.com Date: Wed, 12 Oct 2011 14:54:42 -0500 Subject: Re: [Tutor] extract specific column To: olofsson_anna585 at hotmail.com CC: tutor at python.org On Wed, Oct 12, 2011 at 12:21 PM, Anna Olofsson wrote: Hi, I'm a beginner at python and I'm trying to extract a specific column from a txt file ( see attached file). In the attached file I want to extract the entire column pph2_prob (i.e. column 16). But I want to get all the values from that column without the headline pph2_prob. How do I accomplish that? Hi Anna, We're more than happy to help, but we also would love to see what you've done so far. What have you tried so far? Can you get the entire column *with* the headline? When you show the effort that you've taken, you'll find people are much more inclined to help - very few people here will do your work for you, but most of us are perfectly willing to point you in the right direction! HTH,Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Q8WZ55.pph2.txt URL: From d at davea.name Wed Oct 12 23:16:09 2011 From: d at davea.name (Dave Angel) Date: Wed, 12 Oct 2011 17:16:09 -0400 Subject: [Tutor] extract specific column In-Reply-To: References: , , Message-ID: <4E960399.5050402@davea.name> On 10/12/2011 03:59 PM, Anna Olofsson wrote: > (PLEASE don't top-post. And don't start multiple similar threads a couple of hours apart. Send your message as text without tons of blank lines, and don't assume the attachments will make it. In my case, I haven't a clue to what the file looks like.) > From: olofsson_anna585 at hotmail.com > To: tutor at python.org > Subject: FW: [Tutor] extract specific column > Date: Wed, 12 Oct 2011 21:59:34 +0200 > > > > The thing is, I don't know where to start. I know how to open the attached file, but I don't know how to work inside the file. Is this a csv file? Do I need to use a split function? In what way should I look at the file? As a string? As lines? > If you included about 5 lines of the file in your message, we might have a clue. When I saw the original message, I was going to respond with a message about using [col, col+1], which would give you one character from each line. -- DaveA From steve at pearwood.info Thu Oct 13 01:26:11 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Oct 2011 10:26:11 +1100 Subject: [Tutor] FW: extract specific column In-Reply-To: References: , Message-ID: <4E962213.7020308@pearwood.info> Anna Olofsson wrote: > The thing is, I don't know where to start. I know how to open the > attached file, but I don't know how to work inside the file. Is this > a csv file? Do I need to use a split function? In what way should I > look at the file? As a string? As lines? It looks like a CSV file. Try opening it in Excel or OpenOffice spreadsheet and check that they are happy opening it as CSV. You'll probably need to play with the settings when you do, e.g. change the separator to tab instead of comma, etc. If you can open the file in Excel and get sensible results, you should be able to do the same thing with Python and the csv module. You can learn more about the csv module here: http://effbot.org/librarybook/csv.htm http://www.doughellmann.com/PyMOTW/csv/ After taking a quick glance at the file you provided, it looks to me like fixed width fields (padded with spaces) in a tab-separated format. So you might have to do some post-processing to get rid of the spaces. That's pretty easy: any time you extract a value, just call value.strip() to remove the spaces before doing anything else with it. -- Steven From abraham.miranda.rodriguez at gmail.com Thu Oct 13 01:42:18 2011 From: abraham.miranda.rodriguez at gmail.com (Abe Miranda) Date: Wed, 12 Oct 2011 18:42:18 -0500 Subject: [Tutor] Retrieve data from log file Message-ID: Hi there, I'm sorry to ask this, I tried and example that was posted in 2009 but I couldn't make it work. I'm trying to parse a log file and retrieve what I just need. Hope you can help me with this, this is part of the log file: [2011-10-11 20:43:54:307] INFO [QuoteCompareDaoWSImpl : 24] Se va a invocar el ws de qualitas para comparar cotizaciones [2011-10-11 20:43:55:899] DEBUG [BaseQualitasDaoWS : 79] [http-80-3] wscall - hours:0.0 minutes:0.0 seconds:1.0 [2011-10-11 21:09:42:604] DEBUG [QuoteCompareDaoWSImpl : 25] [http-80-3]Se va a invocar el ws de qualitas para comparar cotizaciones [2011-10-11 21:09:42:708] DEBUG [BaseQualitasDaoWS : 71] [http-80-3] -request: 3519 [2011-10-12 21:02:43:380] DEBUG [BaseQualitasDaoWS : 78] [http-80-1][clientThread-Thread-3] -response: 3519 0 0 7650 2002 VOLKSWAGEN DERBY STD., 05 OCUP. 1 1 4 1250000 2 0000 1091.24 200000 2 0 279.26 500000 2 0 310.0 8560 2 0 260.0 1200000 2 0 0.0 0 N 2011-10-12 2011-10-06 2011-10-09 0 17065 S 1109 1109 1109 14 0.0 1 0 0 14 12 1100.0 0 X000001109 69 79 0 0 62 2 0.0 0 1940.5 400 46.57 262.58 2649.65 15 2011-10-06 2011-10-09 1940.5 400 46.57 262.58 2649.65 291.07 & [2011-10-12 21:02:43:383] DEBUG [BaseQualitasDaoWS : 86] [http-80-1][clientThread-Thread-3] -wscall - hours:0.0 minutes:0.0 seconds:3.0 & [2011-10-12 21:02:43:462] DEBUG [RestController : 81] [http-80-1][clientThread-Thread-3] - hours:0.0 minutes:0.0 seconds:16.0& It repeats itself for every transaction and I need to extract from this lines: [2011-10-12 21:02:43:383] DEBUG [BaseQualitasDaoWS : 86] [http-80-1][clientThread-Thread-3] -wscall - hours:0.0 minutes:0.0 seconds:3.0 & [2011-10-12 21:02:43:462] DEBUG [RestController : 81] [http-80-1][clientThread-Thread-3] - hours:0.0 minutes:0.0 seconds:16.0& this information: 2011-10-12 21:02:43:383 clientThread-Thread-3 hours:0.0 minutes:0.0 seconds:3.0 2011-10-12 21:02:43:462 clientThread-Thread-3 hours:0.0 minutes:0.0 seconds:16.0 Can this be done? Thanks! Abe -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxskywalker1 at gmail.com Thu Oct 13 02:41:24 2011 From: maxskywalker1 at gmail.com (Max S.) Date: Wed, 12 Oct 2011 20:41:24 -0400 Subject: [Tutor] Generic For Loop Message-ID: I've been doing some research into C++, and I've noticed the for loops. Is there a way to use the C++ version of the loops instead of the Python one? For example, I believe that the Python syntax would be: for a=1, a < 11, a += 1: print(a) print("Loop ended.") if the 'for' keyword did it's function as in C++, Actionscript, or most other programming languages. Is there a way to do this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Oct 13 02:56:59 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 12 Oct 2011 20:56:59 -0400 Subject: [Tutor] Generic For Loop In-Reply-To: References: Message-ID: <4E96375B.3090000@gmail.com> On 10/12/2011 8:41 PM, Max S. wrote: > I've been doing some research into C++, and I've noticed the for > loops. Is there a way to use the C++ version of the loops instead of > the Python one? For example, I believe that the Python syntax would be: > for a=1, a < 11, a += 1: > print(a) > print("Loop ended.") > if the 'for' keyword did it's function as in C++, Actionscript, or > most other programming languages. Is there a way to do this? for i in range(1, 11, 1): # the final 1 can be omitted, as it is the default value. loop body OR i = 1 while i < 11: i += 1 loop body Your choice - that's all know of - and the for is easier to read and write than the while. -- Bob Gailer 919-636-4239 Chapel Hill NC From maxskywalker1 at gmail.com Thu Oct 13 03:08:04 2011 From: maxskywalker1 at gmail.com (Max S.) Date: Wed, 12 Oct 2011 21:08:04 -0400 Subject: [Tutor] Generic For Loop In-Reply-To: <4E96375B.3090000@gmail.com> References: <4E96375B.3090000@gmail.com> Message-ID: Thanks! On Wed, Oct 12, 2011 at 8:56 PM, bob gailer wrote: > On 10/12/2011 8:41 PM, Max S. wrote: > >> I've been doing some research into C++, and I've noticed the for loops. >> Is there a way to use the C++ version of the loops instead of the Python >> one? For example, I believe that the Python syntax would be: >> for a=1, a < 11, a += 1: >> print(a) >> print("Loop ended.") >> if the 'for' keyword did it's function as in C++, Actionscript, or most >> other programming languages. Is there a way to do this? >> > > for i in range(1, 11, 1): # the final 1 can be omitted, as it is the > default value. > loop body > > OR > > i = 1 > while i < 11: > i += 1 > loop body > > Your choice - that's all know of - and the for is easier to read and write > than the while. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Oct 13 06:23:32 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Oct 2011 05:23:32 +0100 Subject: [Tutor] Generic For Loop In-Reply-To: References: Message-ID: On 13/10/11 01:41, Max S. wrote: > I've been doing some research into C++, and I've noticed the for loops. If you are trying to program in Python you should probably research Python rather than C++. Any tutorial will provide information about for loops... > Is there a way to use the C++ version of the loops instead of the Python > one? For example, I believe that the Python syntax would be: > for a=1, a < 11, a += 1: > print(a) > print("Loop ended.") for a in range(1,11): print( a ) > if the 'for' keyword did it's function as in C++, Actionscript, or most > other programming languages. Is there a way to do this? Of course, however... Its generally better to think of the Python for lop as being a foreach loop. It iterates over a collection. The C style for loop is a much more primitive loop and is really just a piece of syntactic sugar to implement a while loop: a = 1 while a < 11: a += 1 # loop body here Because it is just a loosely disguised while loop you can put arbitrarily complex expressions into it and to replicate those in Python you need to use the while loop. But generally that kind of obfuscation in C++ is better avoided anyway. The Python style loop is much more powerful than C's in its ability to iterate over lists, dictionaries, strings, files and any other iterable object. C++ introduces iterators as a library class to address this and enable foreach style processing, but at the expense of loop speed. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Thu Oct 13 09:14:56 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Oct 2011 09:14:56 +0200 Subject: [Tutor] Retrieve data from log file References: Message-ID: Abe Miranda wrote: > Hi there, > > I'm sorry to ask this, I tried and example that was posted in 2009 but I > couldn't make it work. I'm trying to parse a log file and retrieve what I > just need. > > Hope you can help me with this, this is part of the log file: > It repeats itself for every transaction and I need to extract from this > lines: > > [2011-10-12 21:02:43:383] DEBUG [BaseQualitasDaoWS : 86] > [http-80-1][clientThread-Thread-3] -wscall - hours:0.0 minutes:0.0 > seconds:3.0 & > [2011-10-12 21:02:43:462] DEBUG [RestController : 81] > [http-80-1][clientThread-Thread-3] - hours:0.0 minutes:0.0 seconds:16.0& > > this information: > > 2011-10-12 21:02:43:383 clientThread-Thread-3 hours:0.0 minutes:0.0 > seconds:3.0 > 2011-10-12 21:02:43:462 clientThread-Thread-3 hours:0.0 minutes:0.0 > seconds:16.0 > > Can this be done? I'd start with a few simple tests like with open("test.log") as instream: for line in instream: if line.startswith("["): parts = line.replace("[", "]").split("]") duration = parts[8].strip("& \n") if "hours" in duration and "minutes" in duration: duration = duration[duration.index("hours"):] time = parts[1] thread = parts[7] print "%s\t%s\t%s" % (time, thread, duration) and see if you get false positives/negatives. Refine as necessary. From lina.lastname at gmail.com Thu Oct 13 15:09:17 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 13 Oct 2011 21:09:17 +0800 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <4E95AA4E.4020804@davea.name> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E90A2@EMARC112VS01.exchad.jpmchase.net> <4E9541E4.6050609@gmx.net> <4E958D12.4060607@gmx.net> <4E95AA4E.4020804@davea.name> Message-ID: > I think your final version of sortfile() might look something like: > > def sortfile(infilename=**INFILENAME, outfilename=OUTFILENAME): > infile = open(infilename, "r") > intext = infile.readlines() > outfile = open(OUTFILENAME, "w") > for chainid in CHAINID: > print("chain id = ",chainid) > sortoneblock(chainid, intext, outfile) > infile.close() > outfile.close() > $ python3 map-to-itp.py {'O4': '2', 'C19': '3', 'C21': '1'} C Traceback (most recent call last): File "map-to-itp.py", line 55, in sortfile() File "map-to-itp.py", line 17, in sortfile sortoneblock(chainid,intext,OUTFILENAME) File "map-to-itp.py", line 29, in sortoneblock f.write(line[1].strip() for line in temp) TypeError: must be str, not generator I don't know how to fix the writing issue. can I write the different chainID one into the same OUTFILE? Thanks, I attached the code I used below: #!/usr/bin/python3 import os.path LINESTOSKIP=0 CHAINID="CDEFGHI" INFILENAME="pdbone.pdb" OUTFILENAME="sortedone.pdb" DICTIONARYFILE="itpone.itp" mapping={} valuefromdict={} def sortfile(): intext=fetchonefiledata(INFILENAME) for chainid in CHAINID: print(chainid) sortoneblock(chainid,intext,OUTFILENAME) def sortoneblock(cID,TEXT,OUTFILE): temp = [] for line in TEXT: blocks=line.strip().split() if len(blocks)== 11 and blocks[3] == "CUR" and blocks[4] == cID and blocks[2] in mapping.keys(): temp.append((mapping[blocks[2]],line)) temp.sort() with open(OUTFILE,"w") as f: f.write(line[1].strip() for line in temp) def generatedictionary(dictfilename): text=fetchonefiledata(DICTIONARYFILE) for line in text: parts=line.strip().split() if len(parts)==8: mapping[parts[4]]=parts[0] print(mapping) def fetchonefiledata(infilename): text=open(infilename).readlines() if os.path.splitext(infilename)[1]==".itp": return text if os.path.splitext(infilename)[1]==".pdb": return text[LINESTOSKIP:] infilename.close() if __name__=="__main__": generatedictionary(DICTIONARYFILE) sortfile() > > > -- > > DaveA > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From c2praveen30jun at gmail.com Thu Oct 13 16:44:53 2011 From: c2praveen30jun at gmail.com (Praveen Singh) Date: Thu, 13 Oct 2011 10:44:53 -0400 Subject: [Tutor] problem with using set Message-ID: i have two questions- 1.>>> removeLetter("hello", "l") >>>'heo' To tackle this problem i am using set so that i can remove duplicates. def removeLetter(word,letter) ????set(word).remove(letter) ????return ''.join(set(word)) I am not getting right answer.I think i am not using sets correctly.please help!!! Approach:- >>> a='hello' >>> set(a) set(['h', 'e', 'l', 'o']), so i am thinking somehow if i remove 'l' and i join the string, i will get the desired output. 2. >>> a='microsoft' >>> set(a) set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>> print ''.join(set(a)) cfimosrt When i print "Hello", i get the output as "helo"(in same sequence) but when i write "microsoft" i get this-"cfimosrt". So, it means i can't predict the outcome of set(a)?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Thu Oct 13 16:50:03 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Thu, 13 Oct 2011 14:50:03 +0000 Subject: [Tutor] problem with using set In-Reply-To: References: Message-ID: <1592504842-1318517402-cardhu_decombobulator_blackberry.rim.net-1239140016-@b18.c12.bise7.blackberry> What exactly do you intend to get as an output? Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Praveen Singh Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Thu, 13 Oct 2011 10:44:53 To: Subject: [Tutor] problem with using set _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From andreas.perstinger at gmx.net Thu Oct 13 16:52:20 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 13 Oct 2011 16:52:20 +0200 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E90A2@EMARC112VS01.exchad.jpmchase.net> <4E9541E4.6050609@gmx.net> <4E958D12.4060607@gmx.net> <4E95AA4E.4020804@davea.name> Message-ID: <4E96FB24.2050607@gmx.net> On 2011-10-13 15:09, lina wrote: > $ python3 map-to-itp.py > {'O4': '2', 'C19': '3', 'C21': '1'} > C > Traceback (most recent call last): > File "map-to-itp.py", line 55, in > sortfile() > File "map-to-itp.py", line 17, in sortfile > sortoneblock(chainid,intext,OUTFILENAME) > File "map-to-itp.py", line 29, in sortoneblock > f.write(line[1].strip() for line in temp) > TypeError: must be str, not generator > > I don't know how to fix the writing issue. You should start to learn how to read the error messages :-). "write" just writes strings into files ("must be str") but you are calling it with an generator. I guess you wanted to use a list comprehension, but this is surrounded by square brackets: f.write([line[1].strip() for line in temp]) But list comprehensions create lists so you would have to convert the list to a string: f.write(str([line[1].strip() for line in temp])) But this would convert the whole list into one single string which you probably don't want (try it for yourself). IMHO it would be easier to iterate through "temp" and write each line separately: for line in temp: f.write(line[1]) "line[1]" is already a string including the newline ("\n"), so str() and strip() aren't necessary (remeber: "write" writes without automatic newlines). Is that what you want? > can I write the different chainID one into the same OUTFILE? I'm not sure what you mean. Do you want something like: C xxxxxxxx xxxxxxxx xxxxxxxx D xxxxxxx xxxxxxx ... ("xxxxxxx" meaning the different lines)? Then you just have to write the corresponding chainID before the for-loop: f.write(cID + "\n") And you have to open the file in mode "a" (to append to an existing file) because otherwise you will overwrite the file with every new chainID you are processing: with open(OUTFILE, "a") as f: > def sortoneblock(cID,TEXT,OUTFILE): ^^^^^^^^^^^^ Just a stylistic remark: It's better to use just lowercase for variable names and parameters. Uppercase names are usually just used for constants. Thus it's easier to distinguish them while reading the code. Bye, Andreas From ramit.prasad at jpmorgan.com Thu Oct 13 17:09:24 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 13 Oct 2011 11:09:24 -0400 Subject: [Tutor] problem with using set In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2165DDC3@EMARC112VS01.exchad.jpmchase.net> Approach:- >>> a='hello' >>> set(a) set(['h', 'e', 'l', 'o']), so i am thinking somehow if i remove 'l' and i join the string, i will get the desired output. 2. >>> a='microsoft' >>> set(a) set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>> print ''.join(set(a)) cfimosrt When i print "Hello", i get the output as "helo"(in same sequence) but when i write "microsoft" i get this-"cfimosrt". So, it means i can't predict the outcome of set(a)?? ========================================================================= Are you required to use set? If you are not, I think the following will be easier. >>> 'hello'.replace( 'l', '' ) 'heo' >>> 'microsoft'.replace( 'o', '' ) 'micrsft' If you require set, you can do: >>> s = set("microsoft") >>> s set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>> s.remove('o') >>> string = [] >>> for letter in 'microsoft': ... if letter in s: ... string.append( letter ) ... >>> ''.join( string ) 'micrsft' Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From delegbede at dudupay.com Thu Oct 13 17:18:24 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Thu, 13 Oct 2011 15:18:24 +0000 Subject: [Tutor] problem with using set In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2165DDC3@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2165DDC3@EMARC112VS01.exchad.jpmchase.net> Message-ID: <263695032-1318519103-cardhu_decombobulator_blackberry.rim.net-1700908878-@b18.c12.bise7.blackberry> +1 Ramit. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: "Prasad, Ramit" Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Thu, 13 Oct 2011 11:09:24 To: tutor at python.org Subject: Re: [Tutor] problem with using set Approach:- >>> a='hello' >>> set(a) set(['h', 'e', 'l', 'o']), so i am thinking somehow if i remove 'l' and i join the string, i will get the desired output. 2. >>> a='microsoft' >>> set(a) set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>> print ''.join(set(a)) cfimosrt When i print "Hello", i get the output as "helo"(in same sequence) but when i write "microsoft" i get this-"cfimosrt". So, it means i can't predict the outcome of set(a)?? ========================================================================= Are you required to use set? If you are not, I think the following will be easier. >>> 'hello'.replace( 'l', '' ) 'heo' >>> 'microsoft'.replace( 'o', '' ) 'micrsft' If you require set, you can do: >>> s = set("microsoft") >>> s set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>> s.remove('o') >>> string = [] >>> for letter in 'microsoft': ... if letter in s: ... string.append( letter ) ... >>> ''.join( string ) 'micrsft' Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From d at davea.name Thu Oct 13 17:43:15 2011 From: d at davea.name (Dave Angel) Date: Thu, 13 Oct 2011 11:43:15 -0400 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E8E15@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212E90A2@EMARC112VS01.exchad.jpmchase.net> <4E9541E4.6050609@gmx.net> <4E958D12.4060607@gmx.net> <4E95AA4E.4020804@davea.name> Message-ID: <4E970713.6020001@davea.name> On 10/13/2011 09:09 AM, lina wrote: > > >> I think your final version of sortfile() might look something like: >> >> def sortfile(infilename=**INFILENAME, outfilename=OUTFILENAME): >> infile = open(infilename, "r") >> intext = infile.readlines() >> outfile = open(OUTFILENAME, "w") >> for chainid in CHAINID: >> print("chain id = ",chainid) >> sortoneblock(chainid, intext, outfile) >> infile.close() >> outfile.close() >> > > $ python3 map-to-itp.py > {'O4': '2', 'C19': '3', 'C21': '1'} > C > Traceback (most recent call last): > File "map-to-itp.py", line 55, in > sortfile() > File "map-to-itp.py", line 17, in sortfile > sortoneblock(chainid,intext,OUTFILENAME) > File "map-to-itp.py", line 29, in sortoneblock > f.write(line[1].strip() for line in temp) > TypeError: must be str, not generator > > When you see an error message that describes a generator, it means you usually have a for-expression used as a value. At your stage of learning you probably be ignoring generators and list comprehensions, and just write simple for loops. So you should replace the f.write with a loop. for item in temp: f.write(something + "\n") One advantage is that you can easily stuff print() functions into the loop, to debug what's really happening. After you're sure it's right, it might be appropriate to use either a generator or a list comprehension. > I don't know how to fix the writing issue. > > can I write the different chainID one into the same OUTFILE? > > Thanks, I attached the code I used below: > > #!/usr/bin/python3 > > import os.path > > LINESTOSKIP=0 > CHAINID="CDEFGHI" > INFILENAME="pdbone.pdb" > OUTFILENAME="sortedone.pdb" > DICTIONARYFILE="itpone.itp" > mapping={} > valuefromdict={} > > def sortfile(): > intext=fetchonefiledata(INFILENAME) > for chainid in CHAINID: > print(chainid) > sortoneblock(chainid,intext,OUTFILENAME) > One way to get all the output into one file is to create the file in sortfile(), and pass the file object. Look again at what I suggested for sortfile(). If you can open the file once, here, you won't have the overhead of constantly opening the same file that nobody closed, and you'll have the side benefit that the old contents of the file will be overwritten. Andreas' suggestion of using append would make more sense if you wanted the output to accumulate over multiple runs of the program. If you don't want the output file to be the history of all the runs, then you'll need to do one open(name, "w"), probably in sortfile(), and then you might as well pass the file object as I suggested. > > > def sortoneblock(cID,TEXT,OUTFILE): If you followed my suggestions for sortfile(), then the last paramter to this function would be outfile., and you could use outfile.write(). As Andreas says, don't use uppercase for non-constants. > temp = [] #this writes the cID to the output file, once per cID outfile.write(cID + "\n") > for line in TEXT: > blocks=line.strip().split() > if len(blocks)== 11 and blocks[3] == "CUR" and blocks[4] == cID and > blocks[2] in mapping.keys(): if (len(blocks)== 11 and blocks[3] == "CUR" and blocks[4] == cID and blocks[2] in mapping ): Having the .keys() in that test is redundant and slows execution down quite a bit. "in" already knows how to look things up efficiently in a dictionary, so there's no use in converting to a slow list before doing the slow lookup. Also, if you put parentheses around the whole if clause, you can span it across multiple lines without doing anything special. > temp.append((mapping[blocks[2]],line)) > temp.sort() > with open(OUTFILE,"w") as f: > f.write(line[1].strip() for line in temp) > See comment above for splitting this write into a loop. You also are going to have to decide what to write, as you have tuple containing both an index number and a string in each item of temp. Probably you want to write the second item of the tuple. Combining these changes, you would have for index, line in temp: outfile.write(line + "\n") Note that the following are equivalent: for item in temp: index, line = item outfile.write(line + "\n") for item in temp: outfile.write(item[1] + "\n") But I like the first form, since it makes it clear what's been stored in temp. That sort of thing is important if you ever change it. > > > > def generatedictionary(dictfilename): > text=fetchonefiledata(DICTIONARYFILE) > for line in text: > parts=line.strip().split() > if len(parts)==8: > mapping[parts[4]]=parts[0] > print(mapping) > > > > def fetchonefiledata(infilename): > text=open(infilename).readlines() > if os.path.splitext(infilename)[1]==".itp": > return text > if os.path.splitext(infilename)[1]==".pdb": > return text[LINESTOSKIP:] > infilename.close() > > > if __name__=="__main__": > generatedictionary(DICTIONARYFILE) > sortfile() > Final note: write() doesn't automatically append a newline, so I tend to add an explicit one in the write() itself. But if you start seeing double spacing, that's presumably because the line already had a newline in it. You could use rstrip() on it (my choice), or remove the + "\n" in the write() method. -- DaveA From d at davea.name Thu Oct 13 18:43:54 2011 From: d at davea.name (Dave Angel) Date: Thu, 13 Oct 2011 12:43:54 -0400 Subject: [Tutor] problem with using set In-Reply-To: References: Message-ID: <4E97154A.2070607@davea.name> On 10/13/2011 10:44 AM, Praveen Singh wrote: > > > 2. >>>> a='microsoft' >>>> set(a) > set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>>> print ''.join(set(a)) > cfimosrt > > When i print "Hello", i get the output as "helo"(in same sequence) but when > i write "microsoft" i get this-"cfimosrt". So, it means i can't predict the > outcome of set(a)?? > The set() function converts its input into a set. A set is not ordered in the usual way, but in such a way as to rapidly find whether a particular item exists already in the set, and insert it if not. Inserting a new item might totally rearrange the existing ones, set doesn't promise anything at all about the order. (Dictionaries are similar, but while set has only a key, dict has both key and value) A set has no value to the assignment as stated. Stick to lists. -- DaveA From ramit.prasad at jpmorgan.com Thu Oct 13 19:31:53 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 13 Oct 2011 13:31:53 -0400 Subject: [Tutor] problem with using set In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2165DDC3@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2165DDC3@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2165E19A@EMARC112VS01.exchad.jpmchase.net> ----Original Message----- From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Prasad, Ramit Sent: Thursday, October 13, 2011 10:09 AM To: tutor at python.org Subject: Re: [Tutor] problem with using set Approach:- >>> a='hello' >>> set(a) set(['h', 'e', 'l', 'o']), so i am thinking somehow if i remove 'l' and i join the string, i will get the desired output. 2. >>> a='microsoft' >>> set(a) set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>> print ''.join(set(a)) cfimosrt When i print "Hello", i get the output as "helo"(in same sequence) but when i write "microsoft" i get this-"cfimosrt". So, it means i can't predict the outcome of set(a)?? ========================================================================= Are you required to use set? If you are not, I think the following will be easier. >>> 'hello'.replace( 'l', '' ) 'heo' >>> 'microsoft'.replace( 'o', '' ) 'micrsft' If you require set, you can do: >>> s = set("microsoft") >>> s set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>> s.remove('o') >>> string = [] >>> for letter in 'microsoft': ... if letter in s: ... string.append( letter ) ... >>> ''.join( string ) 'micrsft' ============================================== After further thought, I think you might want to keep one of each character and not remove them all. If so, see below. >>> string = 'microsoft' >>> dct = {} >>> for letter in string: ... dct[ letter ] = string.count( letter ) ... >>> for letter, count in dct.iteritems(): ... reversed_string = string[::-1] # reverse string to leave first occurrence ... reversed_string = reversed_string.replace( letter, '', count-1 ) ... string = reversed_string[::-1] # return it to normal ... >>> string 'microsft' If you do not care which duplicate character is left you can skip the lines with [::-1] and it will leave the last one in the string. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From fomcl at yahoo.com Thu Oct 13 21:25:52 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 13 Oct 2011 12:25:52 -0700 (PDT) Subject: [Tutor] ctypes and arrays of pointers Message-ID: <1318533952.55365.YahooMailNeo@web110716.mail.gq1.yahoo.com> Hi, I have a question about ctypes. I am trying to call a C function but I am not able to construct the arguments in ctypes. I need to construct two pointers. Each is a pointer to an array of pointers to character values. I did it like this (I tried numerous ways; this seemed the cleanest way): >>> MAXSIZE = 10 >>> valueArrayPtr = ctypes.POINTER(ctypes.c_char_p) * MAXSIZE >>> valueArrayPtr >>> valueArrayPtrPtr = ctypes.POINTER(valueArrayPtr) >>> valueArrayPtrPtr >>> But this yields an error: : Don't know how to convert parameter .. Any idea what I am doing wrong? Below is more complete code. And once it works, can I simply use the ctypes as an iterable to retrieve the values? Thanks in advance! Albert-Jan import ctypes def getValueLabels(self, varName): ??? MAXSIZE = 10 ??? # Pointer to array of pointers to values ??? valueArrayPtr = ctypes.POINTER(ctypes.c_char_p) * MAXSIZE ??? valueArrayPtrPtr = ctypes.POINTER(valueArrayPtr) ??? ??? # Pointer to array of pointers to labels ??? labelArrayPtr = ctypes.POINTER(ctypes.c_char_p) * MAXSIZE ??? labelArrayPtrPtr = ctypes.POINTER(labelArrayPtr) ??? # Pointer to number of values or labels ??? numLabels = ctypes.c_int() ??? numLabelsPtr = ctypes.byref(numLabels) ??? ??? # call C function with the following prototype: ??? # int GetValueLabels(int handle, const char *varName, char ***values, char ***labels, int *numLabels) ??? retcode = self.theLib.GetValueLabels(self.fh, varName, valueArrayPtrPtr, labelArrayPtrPtr, numLabelsPtr) ??? # yields ArgumentError: argument 3: : Don't know how to convert parameter 3 Description This function gets the set of labeled values and associated labels for a short string variable. The number of values is returned as *numLabels. Values are stored into an array of *numLabels pointers, each pointing to a char string containing a nullterminated value, and *values is set to point to the first element of the array. Each value string is as long as the variable. The corresponding labels are structured as an array of *numLabels pointers, each pointing to a char string containing a null-terminated label, and *labels is set to point to the first element of the array. Parameter Description handle Handle to the data file varName Variable name values Pointer to array of pointers to values labels Pointer to array of pointers to labels numLabels Pointer to number of values or labels ? Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From geonyoro at gmail.com Thu Oct 13 21:54:41 2011 From: geonyoro at gmail.com (George Nyoro) Date: Thu, 13 Oct 2011 16:54:41 -0300 Subject: [Tutor] Pyinstaller Database Message-ID: Hi guys: Im a beginner in coding and wanted to distribute some of my code to friends on linux distros. Pyinstaller works well enough. Theres a situation where I use pickle module to save data to an external file. The file is not a py file and when I use pyinstaller, it does nt compile the file too. Is there anyway I can make a none *.py file or use a databse file s that it is compiled too? On 13/10/2011, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: problem with using set (delegbede at dudupay.com) > 2. Re: map one file and print it out following the sequence > (Dave Angel) > 3. Re: problem with using set (Dave Angel) > 4. Re: problem with using set (Prasad, Ramit) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 13 Oct 2011 15:18:24 +0000 > From: delegbede at dudupay.com > To: "tutor at python.org" > Subject: Re: [Tutor] problem with using set > Message-ID: > <263695032-1318519103-cardhu_decombobulator_blackberry.rim.net-1700908878- at b18.c12.bise7.blackberry> > > Content-Type: text/plain > > +1 Ramit. > Sent from my BlackBerry wireless device from MTN > > -----Original Message----- > From: "Prasad, Ramit" > Sender: tutor-bounces+delegbede=dudupay.com at python.org > Date: Thu, 13 Oct 2011 11:09:24 > To: tutor at python.org > Subject: Re: [Tutor] problem with using set > > Approach:- >>>> a='hello' >>>> set(a) > set(['h', 'e', 'l', 'o']), so i am thinking somehow if i remove 'l' and i > join the string, i will get the desired output. > > 2. >>>> a='microsoft' >>>> set(a) > set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>>> print ''.join(set(a)) > cfimosrt > > When i print "Hello", i get the output as "helo"(in same sequence) but when > i write "microsoft" i get this-"cfimosrt". So, it means i can't predict the > outcome of set(a)?? > ========================================================================= > > Are you required to use set? If you are not, I think the following will be > easier. >>>> 'hello'.replace( 'l', '' ) > 'heo' >>>> 'microsoft'.replace( 'o', '' ) > 'micrsft' > > If you require set, you can do: > >>>> s = set("microsoft") >>>> s > set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>>> s.remove('o') >>>> string = [] >>>> for letter in 'microsoft': > ... if letter in s: > ... string.append( letter ) > ... >>>> ''.join( string ) > 'micrsft' > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------ > > Message: 2 > Date: Thu, 13 Oct 2011 11:43:15 -0400 > From: Dave Angel > To: lina > Cc: tutor at python.org > Subject: Re: [Tutor] map one file and print it out following the > sequence > Message-ID: <4E970713.6020001 at davea.name> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 10/13/2011 09:09 AM, lina wrote: >> >> >>> I think your final version of sortfile() might look something like: >>> >>> def sortfile(infilename=**INFILENAME, outfilename=OUTFILENAME): >>> infile = open(infilename, "r") >>> intext = infile.readlines() >>> outfile = open(OUTFILENAME, "w") >>> for chainid in CHAINID: >>> print("chain id = ",chainid) >>> sortoneblock(chainid, intext, outfile) >>> infile.close() >>> outfile.close() >>> >> >> $ python3 map-to-itp.py >> {'O4': '2', 'C19': '3', 'C21': '1'} >> C >> Traceback (most recent call last): >> File "map-to-itp.py", line 55, in >> sortfile() >> File "map-to-itp.py", line 17, in sortfile >> sortoneblock(chainid,intext,OUTFILENAME) >> File "map-to-itp.py", line 29, in sortoneblock >> f.write(line[1].strip() for line in temp) >> TypeError: must be str, not generator >> >> > > When you see an error message that describes a generator, it means you > usually have a for-expression used as a value. > > At your stage of learning you probably be ignoring generators and list > comprehensions, and just write simple for loops. So you should replace > the f.write with a loop. > > > for item in temp: > f.write(something + "\n") > > One advantage is that you can easily stuff print() functions into the > loop, to debug what's really happening. After you're sure it's right, > it might be appropriate to use either a generator or a list comprehension. > >> I don't know how to fix the writing issue. >> >> can I write the different chainID one into the same OUTFILE? >> >> Thanks, I attached the code I used below: >> >> #!/usr/bin/python3 >> >> import os.path >> >> LINESTOSKIP=0 >> CHAINID="CDEFGHI" >> INFILENAME="pdbone.pdb" >> OUTFILENAME="sortedone.pdb" >> DICTIONARYFILE="itpone.itp" >> mapping={} >> valuefromdict={} >> >> def sortfile(): >> intext=fetchonefiledata(INFILENAME) >> for chainid in CHAINID: >> print(chainid) >> sortoneblock(chainid,intext,OUTFILENAME) >> > One way to get all the output into one file is to create the file in > sortfile(), and pass the file object. Look again at what I suggested > for sortfile(). If you can open the file once, here, you won't have the > overhead of constantly opening the same file that nobody closed, and > you'll have the side benefit that the old contents of the file will be > overwritten. > > Andreas' suggestion of using append would make more sense if you wanted > the output to accumulate over multiple runs of the program. If you > don't want the output file to be the history of all the runs, then > you'll need to do one open(name, "w"), probably in sortfile(), and then > you might as well pass the file object as I suggested. > > >> >> >> def sortoneblock(cID,TEXT,OUTFILE): > > If you followed my suggestions for sortfile(), then the last paramter to > this function would be outfile., and you could use outfile.write(). > As Andreas says, don't use uppercase for non-constants. > >> temp = [] > > #this writes the cID to the output file, once per cID > outfile.write(cID + "\n") > >> for line in TEXT: >> blocks=line.strip().split() >> if len(blocks)== 11 and blocks[3] == "CUR" and blocks[4] == cID >> and >> blocks[2] in mapping.keys(): > > if (len(blocks)== 11 and blocks[3] == "CUR" > and blocks[4] == cID and blocks[2] in mapping ): > > Having the .keys() in that test is redundant and slows execution down > quite a bit. "in" already knows how to look things up efficiently in a > dictionary, so there's no use in converting to a slow list before doing > the slow lookup. > Also, if you put parentheses around the whole if clause, you can span it > across multiple lines without doing anything special. > > >> temp.append((mapping[blocks[2]],line)) >> temp.sort() >> with open(OUTFILE,"w") as f: >> f.write(line[1].strip() for line in temp) >> > See comment above for splitting this write into a loop. You also are > going to have to decide what to write, as you have tuple containing both > an index number and a string in each item of temp. Probably you want to > write the second item of the tuple. Combining these changes, you > would have > for index, line in temp: > outfile.write(line + "\n") > > Note that the following are equivalent: > for item in temp: > index, line = item > outfile.write(line + "\n") > > for item in temp: > outfile.write(item[1] + "\n") > > But I like the first form, since it makes it clear what's been stored in > temp. That sort of thing is important if you ever change it. >> >> >> >> def generatedictionary(dictfilename): >> text=fetchonefiledata(DICTIONARYFILE) >> for line in text: >> parts=line.strip().split() >> if len(parts)==8: >> mapping[parts[4]]=parts[0] >> print(mapping) >> >> >> >> def fetchonefiledata(infilename): >> text=open(infilename).readlines() >> if os.path.splitext(infilename)[1]==".itp": >> return text >> if os.path.splitext(infilename)[1]==".pdb": >> return text[LINESTOSKIP:] >> infilename.close() >> >> >> if __name__=="__main__": >> generatedictionary(DICTIONARYFILE) >> sortfile() >> > > Final note: write() doesn't automatically append a newline, so I tend to > add an explicit one in the write() itself. But if you start seeing > double spacing, that's presumably because the line already had a newline > in it. You could use rstrip() on it (my choice), or remove the + "\n" > in the write() method. > > -- > > DaveA > > > ------------------------------ > > Message: 3 > Date: Thu, 13 Oct 2011 12:43:54 -0400 > From: Dave Angel > To: Praveen Singh > Cc: tutor at python.org > Subject: Re: [Tutor] problem with using set > Message-ID: <4E97154A.2070607 at davea.name> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 10/13/2011 10:44 AM, Praveen Singh wrote: >> >> >> 2. >>>>> a='microsoft' >>>>> set(a) >> set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>>>> print ''.join(set(a)) >> cfimosrt >> >> When i print "Hello", i get the output as "helo"(in same sequence) but >> when >> i write "microsoft" i get this-"cfimosrt". So, it means i can't predict >> the >> outcome of set(a)?? >> > The set() function converts its input into a set. A set is not ordered > in the usual way, but in such a way as to rapidly find whether a > particular item exists already in the set, and insert it if not. > Inserting a new item might totally rearrange the existing ones, set > doesn't promise anything at all about the order. (Dictionaries are > similar, but while set has only a key, dict has both key and value) > > A set has no value to the assignment as stated. Stick to lists. > > > -- > > DaveA > > > > ------------------------------ > > Message: 4 > Date: Thu, 13 Oct 2011 13:31:53 -0400 > From: "Prasad, Ramit" > To: "tutor at python.org" > Subject: Re: [Tutor] problem with using set > Message-ID: > <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2165E19A at EMARC112VS01.exchad.jpmchase.net> > > Content-Type: text/plain; charset="us-ascii" > > ----Original Message----- > From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org > [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of > Prasad, Ramit > Sent: Thursday, October 13, 2011 10:09 AM > To: tutor at python.org > Subject: Re: [Tutor] problem with using set > > Approach:- >>>> a='hello' >>>> set(a) > set(['h', 'e', 'l', 'o']), so i am thinking somehow if i remove 'l' and i > join the string, i will get the desired output. > > 2. >>>> a='microsoft' >>>> set(a) > set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>>> print ''.join(set(a)) > cfimosrt > > When i print "Hello", i get the output as "helo"(in same sequence) but when > i write "microsoft" i get this-"cfimosrt". So, it means i can't predict the > outcome of set(a)?? > ========================================================================= > > Are you required to use set? If you are not, I think the following will be > easier. >>>> 'hello'.replace( 'l', '' ) > 'heo' >>>> 'microsoft'.replace( 'o', '' ) > 'micrsft' > > If you require set, you can do: > >>>> s = set("microsoft") >>>> s > set(['c', 'f', 'i', 'm', 'o', 's', 'r', 't']) >>>> s.remove('o') >>>> string = [] >>>> for letter in 'microsoft': > ... if letter in s: > ... string.append( letter ) > ... >>>> ''.join( string ) > 'micrsft' > ============================================== > After further thought, I think you might want to keep one of each character > and not remove them all. If so, see below. > > >>>> string = 'microsoft' >>>> dct = {} >>>> for letter in string: > ... dct[ letter ] = string.count( letter ) > ... >>>> for letter, count in dct.iteritems(): > ... reversed_string = string[::-1] # reverse string to leave first > occurrence > ... reversed_string = reversed_string.replace( letter, '', count-1 ) > ... string = reversed_string[::-1] # return it to normal > ... >>>> string > 'microsft' > > If you do not care which duplicate character is left you can skip the lines > with [::-1] and it will leave the last one in the string. > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 92, Issue 67 > ************************************* > From geonyoro at gmail.com Thu Oct 13 21:54:45 2011 From: geonyoro at gmail.com (George Nyoro) Date: Thu, 13 Oct 2011 16:54:45 -0300 Subject: [Tutor] Pyinstaller Database Message-ID: Hi guys: Im a beginner in coding and wanted to distribute some of my code to friends on linux distros. Pyinstaller works well enough. Theres a situation where I use pickle module to save data to an external file. The file is not a py file and when I use pyinstaller, it does nt compile the file too. Is there anyway I can make a none *.py file or use a databse file s that it is compiled too? From ramit.prasad at jpmorgan.com Thu Oct 13 23:35:32 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 13 Oct 2011 17:35:32 -0400 Subject: [Tutor] Pyinstaller Database In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F216FA73A@EMARC112VS01.exchad.jpmchase.net> >Hi guys: >Im a beginner in coding and wanted to distribute some of my code to >friends on linux distros. Pyinstaller works well enough. Theres a >situation where I use pickle module to save data to an external file. >The file is not a py file and when I use pyinstaller, it does nt >compile the file too. Is there anyway I can make a none *.py file or >use a databse file s that it is compiled too? You can send them your entire source directory and it should work as long as they use a compatible Python version. Unless you have you need to ship/install libraries or complicated project, I see no reason to create an installer. That way you can send your pickled files without any issues. I know some projects (e.g. Sickbeard) do this; you just download from svn/github and run. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From harishbansal.83 at gmail.com Thu Oct 13 11:53:04 2011 From: harishbansal.83 at gmail.com (harish bansal) Date: Thu, 13 Oct 2011 15:23:04 +0530 Subject: [Tutor] Python Job Scheduling package Message-ID: Has anyone seen a python job scheduling framework that could provide the following features - Add/remove job from the queue - View job list - check job status - Run concurrent jobs. I am looking for something similar to coalition( http://code.google.com/p/coalition/) -- Harry -------------- next part -------------- An HTML attachment was scrubbed... URL: From vince at vinces.ca Thu Oct 13 23:48:56 2011 From: vince at vinces.ca (Vince Spicer) Date: Thu, 13 Oct 2011 15:48:56 -0600 Subject: [Tutor] Python Job Scheduling package In-Reply-To: References: Message-ID: You could take a peak at these. Both work without external dependencies http://packages.python.org/APScheduler/#features http://pypi.python.org/pypi/TGScheduler/1.6.2 VInce On Thu, Oct 13, 2011 at 3:53 AM, harish bansal wrote: > Has anyone seen a?python job?scheduling framework that could provide the > following features > > Add/remove job from the queue > View job list > check job status > Run concurrent jobs. > > I am looking for something similar to > coalition(http://code.google.com/p/coalition/) > -- > Harry > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Vince Spicer From bodsda at googlemail.com Fri Oct 14 09:50:17 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Fri, 14 Oct 2011 07:50:17 +0000 Subject: [Tutor] Python Job Scheduling package In-Reply-To: References: Message-ID: <119989285-1318578621-cardhu_decombobulator_blackberry.rim.net-1224795483-@b4.c12.bise7.blackberry> Have you thought about writing your own? Others have posted some useful links, but in all honesty you could hack something together to achieve that in next to no time Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: harish bansal Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Thu, 13 Oct 2011 15:23:04 To: Subject: [Tutor] Python Job Scheduling package _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From maxskywalker1 at gmail.com Fri Oct 14 16:01:32 2011 From: maxskywalker1 at gmail.com (Max S.) Date: Fri, 14 Oct 2011 10:01:32 -0400 Subject: [Tutor] 'object' class Message-ID: I have seen classes created with 'class Class_Name:' and 'class Class_Name(object):'. I'm using the latter, just in case it has some sort of method that could be useful that I don't know about, but *are *there any methods in the 'object' class? And if so, what are they? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafadurancastaneda at gmail.com Fri Oct 14 16:17:31 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Fri, 14 Oct 2011 16:17:31 +0200 Subject: [Tutor] 'object' class In-Reply-To: References: Message-ID: 2011/10/14 Max S. > I have seen classes created with 'class Class_Name:' and 'class > Class_Name(object):'. I'm using the latter, just in case it has some sort > of method that could be useful that I don't know about, but *are *there > any methods in the 'object' class? And if so, what are they? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > This new style vs old styleclasses question, you can find a lot of information if you search about it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tony.pelletier at gmail.com Fri Oct 14 18:45:57 2011 From: tony.pelletier at gmail.com (Tony Pelletier) Date: Fri, 14 Oct 2011 12:45:57 -0400 Subject: [Tutor] Windows vs Linux processing speed. Message-ID: Hi, I have a question regarding the speed of my program on linux in comparison to windows. I'm using geopy and contacting Google for geocodes for records in a csv I created. Like such: try: reader = csv.reader(open(filename, "r")) for row in reader: if row: # Checking to see if it's a valid row so it doesn't blow up on an empty row. username, address, address2, city, state, zip, country = row[0:7] location = address + ', ' + city + ' ' + state + ' ' + zip + ' ' + country try: place, (lat, lng) = g.geocode(location) # Contact Google for Geocodes I mainly use windows, but I tend to use Arch Linux at home. When I run it via windows, it's relatively slow and didn't really bother me, but when I ran it at home I got through 15 or so and got a message back from google saying I was exceeding the allowed amount. Or something to that effect. Basically, I was exceeding the 10 per second that's allowed. So, my question is. Why is it running so much faster on linux? Is it the way that linux is handling the socket? Does windows open and close it whereas linux might leave it open and just pump data through? It's not really a problem since I just added sleep time, but I'm curious. Thanks Tony -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Oct 14 19:15:40 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 14 Oct 2011 13:15:40 -0400 Subject: [Tutor] Windows vs Linux processing speed. In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F216FB12F@EMARC112VS01.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Tony Pelletier Sent: Friday, October 14, 2011 11:46 AM To: tutor at python.org Subject: [Tutor] Windows vs Linux processing speed. Hi,? I have a question regarding the speed of my program on linux in comparison to windows. I'm using geopy and contacting Google for geocodes for records in a csv I created. ?Like such: ?try: ? ? ? ? reader = csv.reader(open(filename, "r")) ? ? ? ? for row in reader: ? ? ? ? ? ? if row: # Checking to see if it's a valid row so it doesn't blow up on an empty row. ? ? ? ? ? ? ? ? username, address, address2, city, state, zip, country = row[0:7] ? ? ? ? ? ? ? ? location = address + ', ' + city + ' ' + state + ' ' + zip + ' ' + country ? ? ? ? ? ? ? ? try: ? ? ? ? ? ? ? ? ? ? place, (lat, lng) = ?g.geocode(location) # Contact Google for Geocodes I mainly use windows, but I tend to use Arch Linux at home. ?When I run it via windows, it's relatively slow and didn't really bother me, but when I ran it at home I got through 15 or so and got a message back from google saying ?I was exceeding the allowed amount. ?Or something to that effect. ?Basically, I was exceeding the 10 per second that's allowed. ? So, my question is. ?Why is it running so much faster on linux? ?Is it the way that linux is handling the socket? ?Does windows open and close it whereas linux might leave it open and just pump data through? ? It's not really a problem since I just added sleep time, but I'm curious. Thanks Tony ================================================================================== I think you might get a better response for this question on the main Python list. You say that at home you use Arch Linux, which implies you are running it from Windows in a different physical location. My initial thought is that your original run might have been from a location "far" from Google or with network congestion. Have you tried Windows and Linux from the same location? What version of Windows and Python for each? Not sure location should make *that* much of a difference though. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From johnf at jfcomputer.com Fri Oct 14 19:39:46 2011 From: johnf at jfcomputer.com (John Fabiani) Date: Fri, 14 Oct 2011 10:39:46 -0700 Subject: [Tutor] Windows vs Linux processing speed. In-Reply-To: References: Message-ID: <201110141039.46642.johnf@jfcomputer.com> On Friday, October 14, 2011 09:45:57 am Tony Pelletier wrote: > Hi, > > I have a question regarding the speed of my program on linux in comparison > to windows. > > I'm using geopy and contacting Google for geocodes for records in a csv I > created. Like such: > > try: > reader = csv.reader(open(filename, "r")) > for row in reader: > if row: # Checking to see if it's a valid row so it doesn't > blow up on an empty row. > username, address, address2, city, state, zip, country = > row[0:7] > location = address + ', ' + city + ' ' + state + ' ' + zip > + ' ' + country > try: > place, (lat, lng) = g.geocode(location) # Contact > Google for Geocodes > > I mainly use windows, but I tend to use Arch Linux at home. When I run it > via windows, it's relatively slow and didn't really bother me, but when I > ran it at home I got through 15 or so and got a message back from google > saying I was exceeding the allowed amount. Or something to that effect. > Basically, I was exceeding the 10 per second that's allowed. > > So, my question is. Why is it running so much faster on linux? Is it the > way that linux is handling the socket? Does windows open and close it > whereas linux might leave it open and just pump data through? > > It's not really a problem since I just added sleep time, but I'm curious. > > Thanks > Tony It's a very good question that I'd like to hear the answer too. When ever I run pure python on linux is always runs faster (this has been my experience). I of course have not a clue as to why (or I might not be monitoring this list). But I bet other do know! Johnf From bgailer at gmail.com Fri Oct 14 21:41:36 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 14 Oct 2011 15:41:36 -0400 Subject: [Tutor] Windows vs Linux processing speed. In-Reply-To: References: Message-ID: <4E989070.4030800@gmail.com> On 10/14/2011 12:45 PM, Tony Pelletier wrote: > Hi, > > I have a question regarding the speed of my program on linux in > comparison to windows. [snip] Speed of a pure Python program depends on * processor speed * competition for resources from other processes * perhaps RAM A good starting point -create a benchmark program that uses only CPU - no disk, no internet. Example: import time n = 100000 # a guess start = time.time() for i in range(n):pass print time.time() - start Be sure n is large enough to create a run time of at least several seconds. Run it on Linux and on Windows. Do a speed check on your internet connections. Then modify the program to open & read the csv file inside the loop. You will have to reduce n when you add disk i/o import time, csv n = 10000 # a guess start = time.time() for i in range(n): for line in csv.reader(open(filename, "r")):pass print time.time() - start HTH -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Oct 14 23:21:48 2011 From: d at davea.name (Dave Angel) Date: Fri, 14 Oct 2011 17:21:48 -0400 Subject: [Tutor] 'object' class In-Reply-To: References: Message-ID: <4E98A7EC.8020707@davea.name> On 10/14/2011 10:17 AM, Rafael Dur?n Casta?eda wrote: > 2011/10/14 Max S. > >> I have seen classes created with 'class Class_Name:' and 'class >> Class_Name(object):'. I'm using the latter, just in case it has some sort >> of method that could be useful that I don't know about, but *are *there >> any methods in the 'object' class? And if so, what are they? >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> This new style vs old styleclasses question, you can find a lot of information if you search about it. Things not covered by that wiki page, 1) in Python 3.x, all classes are new-style, regardless of which syntax you use. 2) I believe super() is new to new-style classes. In any case the documentation for it seem to assume new-style. 3) you could have answered your own question about methods in a particular class. Just use 'dir' >>> dir(object) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] >>> -- DaveA From steve at pearwood.info Sat Oct 15 00:28:19 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Oct 2011 09:28:19 +1100 Subject: [Tutor] Windows vs Linux processing speed. In-Reply-To: <4E989070.4030800@gmail.com> References: <4E989070.4030800@gmail.com> Message-ID: <4E98B783.1020301@pearwood.info> bob gailer wrote: > On 10/14/2011 12:45 PM, Tony Pelletier wrote: >> Hi, >> >> I have a question regarding the speed of my program on linux in >> comparison to windows. > [snip] > > Speed of a pure Python program depends on > > * processor speed > * competition for resources from other processes > * perhaps RAM "Perhaps" RAM? The amount of memory is close to the easiest, cheapest way to speed up a program: more RAM means it is easier and faster to allocate memory in the process, which means more time performing *your* code and less time hunting for blocks of memory. More RAM means less chances you will start using virtual memory, that is, paging blocks of memory out of RAM onto the hard drive, which is around a *thousand* times slower than RAM. You can never have too much RAM :) Very few program's speed are greatly dependent on raw processor speed. Processor speed is one of the great marketing gimmicks of all time. Of course it has *some* effect, but the bottleneck is almost never the CPU, and usually the speed of getting data and/or code out of RAM and onto the CPU and from their into the core for the instructions to be executed. CPU cache faults are really, really expensive, so the bigger the pipeline into the core, the fewer the cache faults. But the most important factor determining the speed of a program is what it actually does, and the algorithm it uses to do it. -- Steven From steve at pearwood.info Sat Oct 15 00:34:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Oct 2011 09:34:47 +1100 Subject: [Tutor] 'object' class In-Reply-To: <4E98A7EC.8020707@davea.name> References: <4E98A7EC.8020707@davea.name> Message-ID: <4E98B907.4090908@pearwood.info> Dave Angel wrote: > 2) I believe super() is new to new-style classes. In any case the > documentation for it seem to assume new-style. Yes, super() only works for new style classes. >>> class Test: ... def method(self): ... super(Test, self).method() ... >>> t = Test() >>> t.method() Traceback (most recent call last): File "", line 1, in File "", line 3, in method TypeError: super() argument 1 must be type, not classobj Likewise for property(). property is particularly tricky, because it *appears* to work for old style classes: >>> class Test: ... def __init__(self, value): ... self._x = value ... def getx(self): ... print "Getting x" ... return self._x ... def setx(self, value): ... print "Setting x" ... self._x = value ... x = property(getx, setx) ... >>> t = Test(42) >>> t.x Getting x 42 but actually doesn't work correctly: >>> t.x = 12 >>> t.x 12 -- Steven From steve at pearwood.info Sat Oct 15 01:01:11 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Oct 2011 10:01:11 +1100 Subject: [Tutor] Windows vs Linux processing speed. In-Reply-To: References: Message-ID: <4E98BF37.8040400@pearwood.info> Tony Pelletier wrote: > So, my question is. Why is it running so much faster on linux? Is it the > way that linux is handling the socket? Does windows open and close it > whereas linux might leave it open and just pump data through? Perhaps; you'll have to read the source code to see if there are differences in geopy, or in the code that it relies on. But I suspect you *might* be seeing this bug: http://www.mail-archive.com/python-dev at python.org/msg40692.html It's a long thread, but the summary is: reading data over the Internet on Windows using some versions of Python is *sometimes* EXTREMELY slow compared to Linux or third party tools. This is due to a bug in the httplib module, which used a naive way of concatenating many little strings. Most of the time, Python has an optimization that can disguise how slow this is, but occasionally the optimization can fail. -- Steven From tony.pelletier at gmail.com Sat Oct 15 05:24:51 2011 From: tony.pelletier at gmail.com (Tony Pelletier) Date: Fri, 14 Oct 2011 23:24:51 -0400 Subject: [Tutor] Windows vs Linux processing speed. In-Reply-To: <4E98BF37.8040400@pearwood.info> References: <4E98BF37.8040400@pearwood.info> Message-ID: Thanks everyone. Well, I've added a timer to the code and I'm running it from my house. I'm getting the same times here from both laptops which I didn't expect at all. I guess I'll have to take my linux laptop to work and see what my tests produce there. And as an FYI, my windows laptop is actually much more capable than my linux laptop. Linux is an IBM Thinkpad T61 Windows is an Alienware M11x R2( i7 with 4gb of ram) Thanks again. Tony On Fri, Oct 14, 2011 at 7:01 PM, Steven D'Aprano wrote: > Tony Pelletier wrote: > > So, my question is. Why is it running so much faster on linux? Is it the >> way that linux is handling the socket? Does windows open and close it >> whereas linux might leave it open and just pump data through? >> > > Perhaps; you'll have to read the source code to see if there are > differences in geopy, or in the code that it relies on. But I suspect you > *might* be seeing this bug: > > http://www.mail-archive.com/**python-dev at python.org/**msg40692.html > > It's a long thread, but the summary is: reading data over the Internet on > Windows using some versions of Python is *sometimes* EXTREMELY slow compared > to Linux or third party tools. This is due to a bug in the httplib module, > which used a naive way of concatenating many little strings. Most of the > time, Python has an optimization that can disguise how slow this is, but > occasionally the optimization can fail. > > > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From japhy at pearachute.com Sat Oct 15 01:21:51 2011 From: japhy at pearachute.com (Japhy Bartlett) Date: Fri, 14 Oct 2011 19:21:51 -0400 Subject: [Tutor] Python Job Scheduling package In-Reply-To: <119989285-1318578621-cardhu_decombobulator_blackberry.rim.net-1224795483-@b4.c12.bise7.blackberry> References: <119989285-1318578621-cardhu_decombobulator_blackberry.rim.net-1224795483-@b4.c12.bise7.blackberry> Message-ID: Is this a thing people would use? I've built this as part of a larger project.. do you think it'd be worth splitting out and polishing up? On Oct 14, 2011 3:55 AM, wrote: Have you thought about writing your own? Others have posted some useful links, but in all honesty you could hack something together to achieve that in next to no time Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: harish bansal Sender: tutor-bounces+bo... -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Oct 15 08:25:14 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Oct 2011 07:25:14 +0100 Subject: [Tutor] Windows vs Linux processing speed. In-Reply-To: References: Message-ID: On 14/10/11 17:45, Tony Pelletier wrote: > Hi, > > I have a question regarding the speed of my program on linux in > comparison to windows. > > I'm using geopy and contacting Google for geocodes for records in a csv > I created. > ....snip... > > I mainly use windows, but I tend to use Arch Linux at home... > > So, my question is. Why is it running so much faster on linux? Its impossible to tell from what you've told us. Is the hardware identical? What about the network connections? In your application I'd expect network delays to be by far the biggest factor in program speed and dwarf the PC/OS issues, (unless there was a huge issue with the networking code - see Steven's post re httplib) Have you tried profiling the code to see how the time is spent on each system? Is there contention on your network at one of the locations? That could account for large differences too. Whatever the reason its unlike;y to be a Linux v Windows issue per se, its much ore likely to be either a difference in Python implementation or a difference in network configuration. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From japhy at pearachute.com Sat Oct 15 08:23:44 2011 From: japhy at pearachute.com (Japhy Bartlett) Date: Sat, 15 Oct 2011 02:23:44 -0400 Subject: [Tutor] Windows vs Linux processing speed. In-Reply-To: References: <4E98BF37.8040400@pearwood.info> Message-ID: In this situation, the network connection is almost certainly the bottleneck; maybe CPU speed, if they are drastically different, but it seems like you're running relatively comparable hardware. RAM is almost never a *speed* bottleneck, until you start working with datasets larger than you can hold in memory and start dealing with disk i/o. If it's not that, I think that Steven is probably on the right track. - Japhy On Fri, Oct 14, 2011 at 11:24 PM, Tony Pelletier wrote: > Thanks everyone. > Well, I've added a timer to the code and I'm running it from my house. ?I'm > getting the same times here from both laptops which I didn't expect at all. > ?I guess I'll have to take my linux laptop to work and see what my tests > produce there. > And as an FYI, my windows laptop is actually much more capable than my linux > laptop. > Linux is an IBM Thinkpad T61 > Windows is an Alienware M11x R2( i7 with 4gb of ram) > Thanks again. > Tony > On Fri, Oct 14, 2011 at 7:01 PM, Steven D'Aprano > wrote: >> >> Tony Pelletier wrote: >> >>> So, my question is. ?Why is it running so much faster on linux? ?Is it >>> the >>> way that linux is handling the socket? ?Does windows open and close it >>> whereas linux might leave it open and just pump data through? >> >> Perhaps; you'll have to read the source code to see if there are >> differences in geopy, or in the code that it relies on. But I suspect you >> *might* be seeing this bug: >> >> http://www.mail-archive.com/python-dev at python.org/msg40692.html >> >> It's a long thread, but the summary is: reading data over the Internet on >> Windows using some versions of Python is *sometimes* EXTREMELY slow compared >> to Linux or third party tools. This is due to a bug in the httplib module, >> which used a naive way of concatenating many little strings. Most of the >> time, Python has an optimization that can disguise how slow this is, but >> occasionally the optimization can fail. >> >> >> >> -- >> Steven >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From fomcl at yahoo.com Sat Oct 15 09:39:46 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 15 Oct 2011 00:39:46 -0700 (PDT) Subject: [Tutor] ctypes and arrays of pointers In-Reply-To: <1318533952.55365.YahooMailNeo@web110716.mail.gq1.yahoo.com> References: <1318533952.55365.YahooMailNeo@web110716.mail.gq1.yahoo.com> Message-ID: <1318664386.10316.YahooMailNeo@web110701.mail.gq1.yahoo.com> ?Hi, Got it already. Here's some incomplete code that shows how it could be done: # Pointer to array of pointers to labels labelsPtr = ctypes.pointer((ctypes.POINTER(ctypes.c_char_p) * MAX_ARRAY_SIZE)()) retcode = self.theLib.GetValueLabels(self.fh, varName, valuesPtr, labelsPtr, numLabelsPtr) labels = [unicode(labelsPtr.contents[0][i], "utf-8") for i in range(numLabels.value)] Thought I might share this with you ;-) Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >________________________________ >From: Albert-Jan Roskam >To: Python Mailing List >Sent: Thursday, October 13, 2011 9:25 PM >Subject: [Tutor] ctypes and arrays of pointers > > >Hi, > > >I have a question about ctypes. I am trying to call a C function but I am not able to construct the arguments in ctypes. I need to construct two pointers. Each is a pointer to an array of pointers to character values. I did it like this (I tried numerous ways; this seemed the cleanest way): >>>> MAXSIZE = 10 >>>> valueArrayPtr = ctypes.POINTER(ctypes.c_char_p) * MAXSIZE >>>> valueArrayPtr > >>>> valueArrayPtrPtr = ctypes.POINTER(valueArrayPtr) >>>> valueArrayPtrPtr > >>>> > > > >But this yields an error: : Don't know how to convert parameter .. > > >Any idea what I am doing wrong? Below is more complete code. >And once it works, can I simply use the ctypes as an iterable to retrieve the values? > > > >Thanks in advance! >Albert-Jan > > > >import ctypes > >def getValueLabels(self, varName): > >??? MAXSIZE = 10 > >??? # Pointer to array of pointers to values >??? valueArrayPtr = ctypes.POINTER(ctypes.c_char_p) * MAXSIZE >??? valueArrayPtrPtr = ctypes.POINTER(valueArrayPtr) >??? >??? # Pointer to array of pointers to labels >??? labelArrayPtr = ctypes.POINTER(ctypes.c_char_p) * MAXSIZE >??? labelArrayPtrPtr = ctypes.POINTER(labelArrayPtr) > >??? # Pointer to number of values or labels >??? numLabels = ctypes.c_int() >??? numLabelsPtr = ctypes.byref(numLabels) >??? >??? # call C function with the following prototype: >??? # int GetValueLabels(int handle, const char *varName, char ***values, char ***labels, int *numLabels) >??? retcode = self.theLib.GetValueLabels(self.fh, varName, valueArrayPtrPtr, labelArrayPtrPtr, numLabelsPtr) >??? # yields ArgumentError: argument 3: : Don't know how to convert parameter 3 > > >Description > >This function gets the set of labeled values and associated labels for a short string >variable. The number of values is returned as *numLabels. Values are stored into an >array of *numLabels pointers, each pointing to a char string containing a nullterminated >value, and *values is set to point to the first element of the array. Each value >string is as long as the variable. The corresponding labels are structured as an array of >*numLabels pointers, each pointing to a char string containing a null-terminated label, >and *labels is set to point to the first element of the array. >Parameter Description >handle Handle to the data file >varName Variable name >values Pointer to array of pointers to values >labels Pointer to array of pointers to labels >numLabels Pointer to number of values or labels > >? >Cheers!! >Albert-Jan > > >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Oct 15 15:52:37 2011 From: emile at fenx.com (Emile van Sebille) Date: Sat, 15 Oct 2011 06:52:37 -0700 Subject: [Tutor] Windows vs Linux processing speed. In-Reply-To: References: Message-ID: On 10/14/2011 9:45 AM Tony Pelletier said... > I have a question regarding the speed of my program on linux in > comparison to windows. > I mainly use windows, but I tend to use Arch Linux at home. When I run > it via windows, it's relatively slow and didn't really bother me, but > when I ran it at home I got through 15 or so and got a message back from > google saying I was exceeding the allowed amount. Or something to that > effect. Basically, I was exceeding the 10 per second that's allowed. > > So, my question is. Why is it running so much faster on linux? Following up on Steven's reference to the py-dev thread, here's the link to the patch that details the simple changes that Chris Withers applied to httplib to improve his testcase performance from ~20 minutes to <3 seconds. http://svn.python.org/view/python/trunk/Lib/httplib.py?r1=74523&r2=74655 Emile From barry3295 at gmail.com Sat Oct 15 17:58:18 2011 From: barry3295 at gmail.com (Jason Barry) Date: Sat, 15 Oct 2011 11:58:18 -0400 Subject: [Tutor] Running a loop Message-ID: <00c601cc8b53$420aeb20$c620c160$@gmail.com> I am using Windows 7 and python 3.1. This is a block from a slot machine code. It takes the random generated words and indicates if it wins or loses. I can't figure out why it wants to print the last print statement 'Loser' no matter if the elif statements are true. import random wheel1=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] wheel2=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] wheel3=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] wheel1index='' wheel2index='' wheel3index='' #decide images for each slot wheel1index=wheel1[random.randint(0, len(wheel1) - 1)] wheel2index=wheel2[random.randint(0, len(wheel2) - 1)] wheel3index=wheel3[random.randint(0, len(wheel3) - 1)] print(wheel1index) print(wheel2index) print(wheel3index) #gets the player bet #Winning bets winning=0 #winning combonations def checkwin (wheel1index, wheel2index, wheel3index): if wheel1index=='zombie' and wheel2index=='zombie' and wheel3index== 'zombie': return print ('wins Zombies.') elif wheel1index=='witch' and wheel2index=='witch' and wheel3index== 'witch': print ('wins witch.') elif wheel1index=='cat' and wheel2index=='cat' and wheel3index== 'cat': print ('wins cats.') elif wheel1index=='pumpkin' and wheel2index=='pumpkin' and wheel3index== 'pumpkin': print ('wins pumpkins.') elif wheel1index=='ghost' and wheel2index=='ghost' and wheel3index== 'ghost': print ('wins ghosts.') elif wheel1index=='candy' and wheel2index=='candy' and wheel3index== 'candy': print ('wins candies.') elif wheel1index=='witch' and wheel2index=='witch' and wheel3index== 'cat': print ('wins witchs and cat.') elif wheel1index=='cat' and wheel2index=='witch' and wheel3index== 'witch': print ('wins witchs and cat.') elif wheel1index=='witch' and wheel2index=='cat' and wheel3index== 'witch': print ('wins witchs and cat.') #pumpkin ghost winner elif wheel1index=='pumpkin' and wheel2index=='pumpkin' and wheel3index== 'ghost': print ('wins pumpkins and ghost.') elif wheel1index=='ghost' and wheel2index=='pumpkin' and wheel3index== 'pumpkin': print ('wins pumpkins and ghost.') elif wheel1index=='pumpkin' and wheel2index=='ghost' and wheel3index== 'pumpkin': print ('wins pumpkins and ghost.') #single combo winner elif wheel1index=='candy' and wheel2index=='pumpkin' and wheel3index== 'ghost': print ('wins pumpkin, ghost, and candy.') elif wheel1index=='candy' and wheel2index=='ghost' and wheel3index== 'pumpkin': print ('wins pumpkin, ghost, and candy..') elif wheel1index=='ghost' and wheel2index=='pumpkin' and wheel3index== 'candie': print ('wins pumpkin, ghost, and candy.') elif wheel1index=='ghost' and wheel2index=='candy' and wheel3index== 'pumpkin': print ('wins pumpkin, ghost, and candy.') elif wheel1index=='pumpkin' and wheel2index=='candy' and wheel3index== 'ghost': print ('wins pumpkin, ghost, and candy.') elif wheel1index=='pumpkin' and wheel2index=='ghost' and wheel3index== 'candy': print('wins pumpkin, ghost, and candy.') else: print ('Loser') checkwin (wheel1index, wheel2index, wheel3index) Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Oct 15 21:18:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Oct 2011 20:18:45 +0100 Subject: [Tutor] Running a loop In-Reply-To: <00c601cc8b53$420aeb20$c620c160$@gmail.com> References: <00c601cc8b53$420aeb20$c620c160$@gmail.com> Message-ID: On 15/10/11 16:58, Jason Barry wrote: > wheel1=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', > 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] > def checkwin (wheel1index, wheel2index, wheel3index): > > if wheel1index=='zombie' and wheel2index=='zombie' and wheel3index== > 'zombie': The values are defined as uppercase(eg 'ZOMBIE') but the tests are for lowercase ('zombie'). Those are two entirely different things so far as Python is concerned. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Sat Oct 15 21:51:32 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 15 Oct 2011 12:51:32 -0700 (PDT) Subject: [Tutor] Can I set LD_LIBRARY_PATH within a .py file? Message-ID: <1318708292.1621.YahooMailNeo@web110701.mail.gq1.yahoo.com> Hello, Can I set the LD_LIBRARY_PATH environment variable (on-the-fly) within a .py file? I would like to use an .so-file that lives in a non-standard location. This does not work: try: ?? os.environ["LD_LIBRARY_PATH"]? += (":" + path) except KeyError: ?? os.environ["LD_LIBRARY_PATH"] = path Currently, I can only run the program in the terminal: export LD_LIBRARY_PATH=/home/dude/Desktop/test python /home/dude/Desktop/testLoadLibLinux.py This works (yaaayy!), but I'd like to run the .py file directly. Is this possible? I also don't? like the fact that I can't test the .py file in Idle. Perhaps a complicating factor is a bug in LD_LIBRARY_PATH in Linux Ubuntu 10 (the version I'm using):https://bugs.edge.launchpad.net/ubuntu/+source/xorg/+bug/366728 https://bugs.launchpad.net/ubuntu/+source/xorg/+bug/366728/comments/21 solution: sudo gedit /etc/X11/Xsession.options (change "use-ssh-agent" into "no-use-ssh-agent") Thank you in advance for your thoughts! ? Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Sat Oct 15 22:07:41 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sat, 15 Oct 2011 22:07:41 +0200 Subject: [Tutor] Running a loop Message-ID: > Subject: [Tutor] Running a loop > I am using Windows 7 and python 3.1. This is a block from a slot machine > code. It takes the random generated words and indicates if it wins or loses. > I can't figure out why it wants to print the last print statement 'Loser' no > matter if the elif statements are true. Let's begin with saying "never mind that, you have other issues". First of all, whitespace is great in moderation. I don't know if it's your mail client or your code that's messed up, but the kind of whitespace you're sending along is just horrible and nigh on unreadable. This leads to the second issue: you're misspelling strings and comparing uppercase strings to lowercase ones (which will automatically fail). > import random > > wheel1=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', > 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] > > wheel2=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', > 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] > > wheel3=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', > 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] You don't really need 3 different wheels if they're all identical, instead having one wheel is enough: wheel = ["ZOMBIE", "WITCH", "CAT" #and so on] > wheel1index='' > wheel2index='' > wheel3index='' > #decide images for each slot > wheel1index=wheel1[random.randint(0, len(wheel1) - 1)] > wheel2index=wheel2[random.randint(0, len(wheel2) - 1)] > wheel3index=wheel3[random.randint(0, len(wheel3) - 1)] Here you can just do wheel1index = wheel[random.randint(o, len(wheel) - 1)], then wheel2index = wheel[... and so on. > print(wheel1index) > print(wheel2index) > print(wheel3index) > #winning combonations > def checkwin (wheel1index, wheel2index, wheel3index): > ? ?if wheel1index=='zombie' and wheel2index=='zombie' and wheel3index== > 'zombie': > ? ? ? ?return print ('wins Zombies.') I suspect that it's your mail client that makes it look horrible. You can also do: if wheel1index == wheel2index == wheel3index: return print("Wins {0}".format(wheel1index)) or something similar for all of the cases where each wheel shows the same. However, you won't get any results unless you change the case to match what you've actually assigned to the wheels (remember, we assign "WITCH" and "CAT" but it checks for "witch" and "cat" and will never, ever find them). > ? ?elif wheel1index=='ghost' and wheel2index=='pumpkin' and wheel3index== > 'candie': > > ? ? ? ?print ('wins pumpkin, ghost, and candy.') Here you've misspelled "candy" as well as having it in the wrong case. ANYWAY, I'm sure there's some better way to compare stuff like: Pumpkin, Pumpkin, Ghost Pumpkin, Ghost, Pumpkin Ghost, Pumpkin, Pumpkin (I mean, it's the SAME SITUATION, and the same goes for almost all the rest of the elif structures), but I'm in a hurry so I can't really come up with a good way to check for that. Possibly have one index (a list with three "wheel" items) and do some cool list comprehensions on it, as it is I'm 100% sure that your if-elif-else structure can be optimized a lot. Also, no need to have a new line between each elif, makes it hard to read, and they're all part of the same code block. -- best regards, Robert S. From hugo.yoshi at gmail.com Sun Oct 16 01:22:02 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 16 Oct 2011 01:22:02 +0200 Subject: [Tutor] Can I set LD_LIBRARY_PATH within a .py file? In-Reply-To: <1318708292.1621.YahooMailNeo@web110701.mail.gq1.yahoo.com> References: <1318708292.1621.YahooMailNeo@web110701.mail.gq1.yahoo.com> Message-ID: On Sat, Oct 15, 2011 at 9:51 PM, Albert-Jan Roskam wrote: > Hello, > Can I set the LD_LIBRARY_PATH environment variable (on-the-fly) within a .py > file? > I would like to use an .so-file that lives in a non-standard location. > > This does not work: > try: > ?? os.environ["LD_LIBRARY_PATH"]? += (":" + path) > except KeyError: > ?? os.environ["LD_LIBRARY_PATH"] = path > Currently, I can only run the program in the terminal: > export LD_LIBRARY_PATH=/home/dude/Desktop/test > python /home/dude/Desktop/testLoadLibLinux.py > This works (yaaayy!), but I'd like to run the .py file directly. > Is this possible? I also don't? like the fact that I can't test the .py file > in Idle. > Perhaps a complicating factor is a bug in LD_LIBRARY_PATH > in Linux Ubuntu 10 (the version I'm using): > https://bugs.edge.launchpad.net/ubuntu/+source/xorg/+bug/366728 > https://bugs.launchpad.net/ubuntu/+source/xorg/+bug/366728/comments/21 > solution: > sudo gedit /etc/X11/Xsession.options > (change "use-ssh-agent" into "no-use-ssh-agent") > > Thank you in advance for your thoughts! > > Cheers!! > Albert-Jan > Alright, I'm not going to pretend to be an expert on this one, a bit of this is speculation and inference from what I know about dynamic linking. In short, I don't think you can modify LD_LIBRARY_PATH on the fly and have it actually work. The reason for this is that the linker runs and finds all the libraries *before* the python process actually starts. So by the time you go and modify the environment, all libraries have already been linked, and your modified variable is never even read by the linker. So the best you can do is write a tiny wrapper to set LD_LIBRARY_PATH and then run your actual script through it. Or you could set the environment variable and then fork(), I suppose, since the child will inherit the modified environment. But the wrapper is your simplest option. HTH, Hugo From steve at pearwood.info Sun Oct 16 06:01:20 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Oct 2011 15:01:20 +1100 Subject: [Tutor] Running a loop In-Reply-To: <00c601cc8b53$420aeb20$c620c160$@gmail.com> References: <00c601cc8b53$420aeb20$c620c160$@gmail.com> Message-ID: <4E9A5710.6050206@pearwood.info> Jason Barry wrote: > I am using Windows 7 and python 3.1. This is a block from a slot machine > code. It takes the random generated words and indicates if it wins or loses. > I can't figure out why it wants to print the last print statement 'Loser' no > matter if the elif statements are true. Alan has already explained that you are comparing UPPERCASE strings to lowercase strings, and they are not equal. A few other comments below: > import random > wheel1=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', > 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] > > wheel2=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', > 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] > > wheel3=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', > 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] Rather than duplicating values each time, it is better to do this: images = tuple('''ZOMBIE WITCH CAT GHOST CANDY PUMPKIN PUMPKIN CANDY GHOST CANDY'''.split()) wheel1 = list(images) wheel2 = list(images) wheel3 = list(images) (Note: I call list(images) instead of just images to ensure that each of the wheels has its own independent list of images, rather than all sharing the same one.) Checking for winning sets also can be simplified a lot: def checkwin (wheel1index, wheel2index, wheel3index): combo = [wheel1index, wheel2index, wheel3index] if combo.count('ZOMBIE') == 3: print('wins zombies') elif combo.count('WITCH') == 3: print('wins witchs') elif combo.count('CAT') == 3: print('wins cats') elif combo.count('PUMPKIN') == 3: print('wins pumpkins') elif combo.count('GHOST') == 3: print('wins ghosts') elif combo.count('CANDY') == 3: print('wins candies') elif combo.count('WITCH') == 2 and combo.count('CAT') == 1: print('wins witches and cat') elif combo.count('PUMPKIN') == 2 and combo.count('GHOST') == 1: print('wins pumpkins and ghost') # check for single combo winner elif set(combo) = set(['CANDY', 'PUMPKIN', 'GHOST']): print('wins pumpkin, ghost and candy') else: print('loses') -- Steven From steve at pearwood.info Sun Oct 16 06:13:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Oct 2011 15:13:50 +1100 Subject: [Tutor] Windows vs Linux processing speed. In-Reply-To: <4E98B783.1020301@pearwood.info> References: <4E989070.4030800@gmail.com> <4E98B783.1020301@pearwood.info> Message-ID: <4E9A59FE.2080501@pearwood.info> Steven D'Aprano wrote: > Very few program's speed are greatly dependent on raw processor speed. > Processor speed is one of the great marketing gimmicks of all time. Of > course it has *some* effect, but the bottleneck is almost never the CPU, > and usually the speed of getting data and/or code out of RAM and onto > the CPU and from their into the core for the instructions to be Sigh. /s/their/there > executed. CPU cache faults are really, really expensive, so the bigger > the pipeline into the core, the fewer the cache faults. And double sigh. Obviously I wasn't paying too much attention to what I was writing. Obviously the number of cache faults is determined by the size of the cache, not the size of the pipeline. Generally speaking, a processor with a fast core but a small cache will not perform as well as a processor with a slower core but a bigger cache. Within reason -- obviously it depends on the nature of the code being executed, some code doesn't benefit much from a processor cache. -- Steven From steve at pearwood.info Sun Oct 16 08:48:04 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Oct 2011 17:48:04 +1100 Subject: [Tutor] Python Job Scheduling package In-Reply-To: <119989285-1318578621-cardhu_decombobulator_blackberry.rim.net-1224795483-@b4.c12.bise7.blackberry> References: <119989285-1318578621-cardhu_decombobulator_blackberry.rim.net-1224795483-@b4.c12.bise7.blackberry> Message-ID: <4E9A7E24.2030803@pearwood.info> bodsda at googlemail.com wrote: > Have you thought about writing your own? Others have posted some > useful links, but in all honesty you could hack something together to > achieve that in next to no time Anyone can "hack something together" in next to no time, but getting a quality package that is well-written, thoroughly tested and debugged may take a bit longer. -- Steven From __peter__ at web.de Sun Oct 16 11:11:26 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 16 Oct 2011 11:11:26 +0200 Subject: [Tutor] Running a loop References: <00c601cc8b53$420aeb20$c620c160$@gmail.com> Message-ID: Jason Barry wrote: > I am using Windows 7 and python 3.1. This is a block from a slot machine > code. It takes the random generated words and indicates if it wins or > loses. I can't figure out why it wants to print the last print statement > 'Loser' no matter if the elif statements are true. > > import random > > wheel1=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', > 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] > > wheel2=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', > 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] > > wheel3=['ZOMBIE', 'WITCH', 'CAT', 'GHOST', > 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY'] The wheels are all the same and you don't plan to modify them; therefore you can use a single wheel variable for all wheels in the slot machine > wheel1index='' No need to initialise the variable with a dummy value when you proceed to see the real value immediately afterwards. > wheel1index=wheel1[random.randint(0, len(wheel1) - 1)] > wheel2index=wheel2[random.randint(0, len(wheel2) - 1)] > wheel3index=wheel3[random.randint(0, len(wheel3) - 1)] Have a look at random.choice() which has the same effect. Also, consider putting the results into a list as in chosen = [random.choice(wheel) for dummy in range(3)] > winning=0 Unused variable. > def checkwin (wheel1index, wheel2index, wheel3index): You can shorten this function considerably with the help of sets and dicts. A complete example script: import random from collections import Counter wheel = ['zombie', 'witch', 'cat', 'ghost', 'candy','pumpkin','pumpkin','candy', 'ghost','candy'] _plurals = { "witch": "witches", "candy": "candies"} def plural(word): return _plurals.get(word, word + "s") def checkwin (chosen): chosen_dict = Counter(chosen) if len(chosen_dict) == 1: print("wins {}.".format(plural(chosen[0]))) elif chosen_dict == {"witch": 2, "cat": 1}: print("wins witches and cat") elif chosen_dict == {"pumpkin": 2, "ghost": 1}: print("wins pumpkins and ghost") elif chosen_dict.keys() == {"candy", "pumpkin", "ghost"}: print("wins pumpkin, ghost, and candy.") else: print("Loser") for i in range(1000): chosen = [random.choice(wheel) for wheel_index in range(3)] print(" ".join(chosen).ljust(25), end=" --> ") checkwin(chosen) From rafadurancastaneda at gmail.com Sun Oct 16 12:09:50 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Sun, 16 Oct 2011 12:09:50 +0200 Subject: [Tutor] Python Job Scheduling package In-Reply-To: <4E9A7E24.2030803@pearwood.info> References: <119989285-1318578621-cardhu_decombobulator_blackberry.rim.net-1224795483-@b4.c12.bise7.blackberry> <4E9A7E24.2030803@pearwood.info> Message-ID: And what about celery??? 2011/10/16 Steven D'Aprano > bodsda at googlemail.com wrote: > >> Have you thought about writing your own? Others have posted some >> useful links, but in all honesty you could hack something together to >> achieve that in next to no time >> > > Anyone can "hack something together" in next to no time, but getting a > quality package that is well-written, thoroughly tested and debugged may > take a bit longer. > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benderjacob44 at gmail.com Sun Oct 16 14:28:32 2011 From: benderjacob44 at gmail.com (Jacob Bender) Date: Sun, 16 Oct 2011 08:28:32 -0400 Subject: [Tutor] Socket and Ports Message-ID: Dear Tutors, I've been having an issue with socket. I wanted to use it for transmitting strings over the Internet. The problem is that my friend insists that allowing python to transmit and receive information via an Internet port is a bad idea. He claimed that I could(and probably would) receive information that wouldn't necessarily do my computer any good(in a nutshell). First of all, I thought that you could specify where the message was supposed to come from via an IP address, while you were in the process of creating your clients(or server). That way, I shouldn't be receiving all kinds of random stuff from people on the same port that don't have that IP address. My friend also claims that hackers could use my python distribution to hack other programs on my system(all without my permission, of course). And ultimately steal information or bring down my system. All via socket, because I'd allow only that program to access the port. In conclusion, basically my friend says that whatever I do, hackers can and probably will somehow take control of my computer in some way, shape, or form. I, however think this to be untrue because I'm specifying where the information is supposed to come from and I'm not going to open my entire computer to the port, I'm ONLY allowing python to receive and transmit information. Please help. Thanks, Jacob Bender -------------- next part -------------- An HTML attachment was scrubbed... URL: From toganm at users.sourceforge.net Sun Oct 16 15:18:29 2011 From: toganm at users.sourceforge.net (toganm at users.sourceforge.net) Date: Sun, 16 Oct 2011 15:18:29 +0200 Subject: [Tutor] Bounded Linear Search Message-ID: Hi, I am trying to learn programming and python and one of the books I use has an exercise for "Bounded Linear Search algorithm" under the heading in Accumulating Unique Values at I have coded the exercises as below and what I can not figure it out is the code works along as spin[0] and spine[-1] are not same but when it is the code does not work. What am I missing ? spin=[18, 10, 2, 19, 20, 10, 2, 7, 26, 10,2,2,18] uniq=[] for v in spin: i=0 uniq.append(v) while uniq[i]!=v: i+=1 if uniq[i]==v: if i!=len(uniq)-1: uniq.pop(-1) print(uniq) Thanks Togan From bgailer at gmail.com Sun Oct 16 16:20:48 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 16 Oct 2011 10:20:48 -0400 Subject: [Tutor] Socket and Ports In-Reply-To: References: Message-ID: <4E9AE840.7030608@gmail.com> On 10/16/2011 8:28 AM, Jacob Bender wrote: > Dear Tutors, > > I've been having an issue with socket. I wanted to use it for > transmitting strings over the Internet. That's good, because strings is all you can transmit. > The problem is that my friend insists that allowing python to transmit > and receive information via an Internet port is a bad idea. He claimed > that I could(and probably would) receive information that wouldn't > necessarily do my computer any good(in a nutshell). I am not the expert on this issue. My view: once you establish a socket connection then you wait to receive data. All the socket software (Python or other) does is receive a string. What you do with it is up to you. If you apply eval or exec to it than anything could happen. No one can IMHO cause any action via socket. [snip] -- Bob Gailer 919-636-4239 Chapel Hill NC From __peter__ at web.de Sun Oct 16 16:30:07 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 16 Oct 2011 16:30:07 +0200 Subject: [Tutor] Bounded Linear Search References: Message-ID: toganm at users.sourceforge.net wrote: > Hi, > I am trying to learn programming and python and one of the books I use has > an exercise for "Bounded Linear Search algorithm" under the heading in > Accumulating Unique Values at > exercises> > > I have coded the exercises as below and what I can not figure it out is > the code works along as spin[0] and spine[-1] are not same but when it is > the code does not work. What am I missing ? > > > spin=[18, 10, 2, 19, 20, 10, 2, 7, 26, 10,2,2,18] > > uniq=[] > > for v in spin: > i=0 > uniq.append(v) > while uniq[i]!=v: > i+=1 > if uniq[i]==v: > if i!=len(uniq)-1: > uniq.pop(-1) > > print(uniq) Consider the simple example spin = [42, 42] First iteration of the for loop: v = 42 i = 0 uniq = [42] while uniq[0] != 42: # False, while loop will not be entered ... Second iteration of the for loop: v = 42 i = 0 uniq = [42, 42] while uniq[0] != 42 # False, while loop while not be entered The fix is to move the if ... check out of the while loop for v in spin: i = 0 uniq.append(v) while uniq[i] != v: i += 1 # at this point uniq[i] == v is guaranteed, so we don't need the outer if if i != len(uniq) - 1: uniq.pop(-1) # or: del uniq[-1] First iteration of the for loop: v = 42 i = 0 uniq = [42] while uniq[0] != v: # False, while loop will not be entered if 0 != len([42]) - 1 # 0 != 0, False, last item of uniq will not be removed Second iteration of the for loop: v = 42 i = 0 uniq = [42, 42] while uniq[0] != 42: # False, while loop will not be entered if 0 != len([42, 42]) -1: # 0 != 1, True, last item of uniq will be removed To verify that the algorithm is correct now you could walk through increasingly more complex sample data, which may be possible in this case, but rarely ever for an entire script. Instead the common approach is to pick a few samples along with the expected outcomes, feed them to your function and verify that they give the expected output def unique_values(items): ... return uniq assert unique_values([42, 42]) == [42] assert unique_values([1, 2, 3, 2]) == [1, 2, 3] ... From hugo.yoshi at gmail.com Sun Oct 16 16:48:18 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 16 Oct 2011 16:48:18 +0200 Subject: [Tutor] Socket and Ports In-Reply-To: <4E9AE840.7030608@gmail.com> References: <4E9AE840.7030608@gmail.com> Message-ID: On Sun, Oct 16, 2011 at 4:20 PM, bob gailer wrote: > On 10/16/2011 8:28 AM, Jacob Bender wrote: >> >> Dear Tutors, >> >> ? ? I've been having an issue with socket. I wanted to use it for >> transmitting strings over the Internet. > > That's good, because strings is all you can transmit. > >> The problem is that my friend insists that allowing python to transmit and >> receive information via an Internet port is a bad idea. He claimed that I >> could(and probably would) receive information that wouldn't necessarily do >> my computer any good(in a nutshell). > > I am not the expert on this issue. My view: > > once you establish a socket connection then you wait to receive data. All > the socket software (Python or other) does is receive a string. What you do > with it is up to you. If you apply eval or exec to it than anything could > happen. No one can IMHO cause any action via socket. > vulnerabilities in the lower level stack notwithstanding, of course. But in essence, using sockets in python is not any more dangerous than using sockets in any other language. You have to watch what you're doing and be careful with the data you receive, but as long as you do that you shouldn't be in any danger. Hugo From toganm at users.sourceforge.net Sun Oct 16 19:04:41 2011 From: toganm at users.sourceforge.net (toganm at users.sourceforge.net) Date: Sun, 16 Oct 2011 19:04:41 +0200 Subject: [Tutor] Bounded Linear Search References: Message-ID: Peter Otten wrote: > To verify that the algorithm is correct now you could walk through > increasingly more complex sample data, which may be possible in this case, > but rarely ever for an entire script. Instead the common approach is to > pick a few samples along with the expected outcomes, feed them to your > function and verify that they give the expected output > > def unique_values(items): > ... > return uniq > > assert unique_values([42, 42]) == [42] > assert unique_values([1, 2, 3, 2]) == [1, 2, 3] Thanks for the tip and where I was failing to see Togan From fomcl at yahoo.com Sun Oct 16 20:25:44 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 16 Oct 2011 11:25:44 -0700 (PDT) Subject: [Tutor] Can I set LD_LIBRARY_PATH within a .py file? In-Reply-To: References: <1318708292.1621.YahooMailNeo@web110701.mail.gq1.yahoo.com> Message-ID: <1318789544.84883.YahooMailNeo@web110709.mail.gq1.yahoo.com> Hi Hugo, ? You are absolutely right. Thank you! It took me a lot of reading and tinkering to find out that typing the following in the terminal works: export LD_LIBRARY_PATH=\path\to\the\lib python main.py # contains import to my program + calls to the functions in it. ? I find it strange though, that ctypes.CDLL() does not accept library names *with the full path*. In Linux, you could do it, but it seems that all the dependencies of the libary in that non-standard location are looked for ONLY in that non-standard location. Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From: Hugo Arts >To: Albert-Jan Roskam >Cc: Python Mailing List >Sent: Sunday, October 16, 2011 1:22 AM >Subject: Re: [Tutor] Can I set LD_LIBRARY_PATH within a .py file? > >On Sat, Oct 15, 2011 at 9:51 PM, Albert-Jan Roskam wrote: >> Hello, >> Can I set the LD_LIBRARY_PATH environment variable (on-the-fly) within a .py >> file? >> I would like to use an .so-file that lives in a non-standard location. >> >> This does not work: >> try: >> ?? os.environ["LD_LIBRARY_PATH"]? += (":" + path) >> except KeyError: >> ?? os.environ["LD_LIBRARY_PATH"] = path >> Currently, I can only run the program in the terminal: >> export LD_LIBRARY_PATH=/home/dude/Desktop/test >> python /home/dude/Desktop/testLoadLibLinux.py >> This works (yaaayy!), but I'd like to run the .py file directly. >> Is this possible? I also don't? like the fact that I can't test the .py file >> in Idle. >> Perhaps a complicating factor is a bug in LD_LIBRARY_PATH >> in Linux Ubuntu 10 (the version I'm using): >> https://bugs.edge.launchpad.net/ubuntu/+source/xorg/+bug/366728 >> https://bugs.launchpad.net/ubuntu/+source/xorg/+bug/366728/comments/21 >> solution: >> sudo gedit /etc/X11/Xsession.options >> (change "use-ssh-agent" into "no-use-ssh-agent") >> >> Thank you in advance for your thoughts! >> >> Cheers!! >> Albert-Jan >> > >Alright, I'm not going to pretend to be an expert on this one, a bit >of this is speculation and inference from what I know about dynamic >linking. In short, I don't think you can modify LD_LIBRARY_PATH on the >fly and have it actually work. The reason for this is that the linker >runs and finds all the libraries *before* the python process actually >starts. So by the time you go and modify the environment, all >libraries have already been linked, and your modified variable is >never even read by the linker. > >So the best you can do is write a tiny wrapper to set LD_LIBRARY_PATH >and then run your actual script through it. Or you could set the >environment variable and then fork(), I suppose, since the child will >inherit the modified environment. But the wrapper is your simplest >option. > >HTH, >Hugo > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benderjacob44 at gmail.com Sun Oct 16 21:00:04 2011 From: benderjacob44 at gmail.com (Jacob Bender) Date: Sun, 16 Oct 2011 15:00:04 -0400 Subject: [Tutor] Socket and Ports In-Reply-To: References: <4E9AE840.7030608@gmail.com> Message-ID: Thank you, and I'm not planning on executing any data I receive from anybody. So I should be pretty safe... On Sun, Oct 16, 2011 at 10:48 AM, Hugo Arts wrote: > On Sun, Oct 16, 2011 at 4:20 PM, bob gailer wrote: > > On 10/16/2011 8:28 AM, Jacob Bender wrote: > >> > >> Dear Tutors, > >> > >> I've been having an issue with socket. I wanted to use it for > >> transmitting strings over the Internet. > > > > That's good, because strings is all you can transmit. > > > >> The problem is that my friend insists that allowing python to transmit > and > >> receive information via an Internet port is a bad idea. He claimed that > I > >> could(and probably would) receive information that wouldn't necessarily > do > >> my computer any good(in a nutshell). > > > > I am not the expert on this issue. My view: > > > > once you establish a socket connection then you wait to receive data. All > > the socket software (Python or other) does is receive a string. What you > do > > with it is up to you. If you apply eval or exec to it than anything could > > happen. No one can IMHO cause any action via socket. > > > > vulnerabilities in the lower level stack notwithstanding, of course. > But in essence, using sockets in python is not any more dangerous than > using sockets in any other language. You have to watch what you're > doing and be careful with the data you receive, but as long as you do > that you shouldn't be in any danger. > > Hugo > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Sun Oct 16 21:43:06 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Sun, 16 Oct 2011 19:43:06 +0000 Subject: [Tutor] 6 random numbers Message-ID: hello all, anyone know how i would go about printing 6 random numbers, i know i could copy and paste 6 times (which would work) but i was thinking about a while loop, ie. while lottery_numbers.count is <7. Is it possible to code this? is it possible to count random variables? i am trying to keep the program as simple as possible, cheers any help would be welcome, import random lottery_numbers=random.randrange(1,42) print lottery_numbers -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxskywalker1 at gmail.com Sun Oct 16 22:10:32 2011 From: maxskywalker1 at gmail.com (Max S.) Date: Sun, 16 Oct 2011 16:10:32 -0400 Subject: [Tutor] Tutor Digest, Vol 92, Issue 77 In-Reply-To: References: Message-ID: On Sun, Oct 16, 2011 at 3:44 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Bounded Linear Search (toganm at users.sourceforge.net) > 2. Re: Can I set LD_LIBRARY_PATH within a .py file? > (Albert-Jan Roskam) > 3. Re: Socket and Ports (Jacob Bender) > 4. 6 random numbers (ADRIAN KELLY) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sun, 16 Oct 2011 19:04:41 +0200 > From: toganm at users.sourceforge.net > To: tutor at python.org > Subject: Re: [Tutor] Bounded Linear Search > Message-ID: > Content-Type: text/plain; charset="ISO-8859-1" > > Peter Otten wrote: > > > To verify that the algorithm is correct now you could walk through > > increasingly more complex sample data, which may be possible in this > case, > > but rarely ever for an entire script. Instead the common approach is to > > pick a few samples along with the expected outcomes, feed them to your > > function and verify that they give the expected output > > > > def unique_values(items): > > ... > > return uniq > > > > assert unique_values([42, 42]) == [42] > > assert unique_values([1, 2, 3, 2]) == [1, 2, 3] > > Thanks for the tip and where I was failing to see > > Togan > > > > ------------------------------ > > Message: 2 > Date: Sun, 16 Oct 2011 11:25:44 -0700 (PDT) > From: Albert-Jan Roskam > To: Hugo Arts > Cc: Python Mailing List > Subject: Re: [Tutor] Can I set LD_LIBRARY_PATH within a .py file? > Message-ID: > <1318789544.84883.YahooMailNeo at web110709.mail.gq1.yahoo.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi Hugo, > ? > You are absolutely right. Thank you! It took me a lot of reading and > tinkering to find out that typing the following in the terminal works: > export LD_LIBRARY_PATH=\path\to\the\lib > python main.py # contains import to my program + calls to the functions in > it. > ? > I find it strange though, that ctypes.CDLL() does not accept library names > *with the full path*. In Linux, you could do it, but it seems that all the > dependencies of the libary in that non-standard location are looked for ONLY > in that non-standard location. > > Cheers!! > Albert-Jan > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > All right, but apart from the sanitation, the medicine, education, wine, > public order, irrigation, roads, a fresh water system, and public health, > what have the Romans ever done for us? > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > From: Hugo Arts > >To: Albert-Jan Roskam > >Cc: Python Mailing List > >Sent: Sunday, October 16, 2011 1:22 AM > >Subject: Re: [Tutor] Can I set LD_LIBRARY_PATH within a .py file? > > > >On Sat, Oct 15, 2011 at 9:51 PM, Albert-Jan Roskam > wrote: > >> Hello, > >> Can I set the LD_LIBRARY_PATH environment variable (on-the-fly) within a > .py > >> file? > >> I would like to use an .so-file that lives in a non-standard location. > >> > >> This does not work: > >> try: > >> ?? os.environ["LD_LIBRARY_PATH"]? += (":" + path) > >> except KeyError: > >> ?? os.environ["LD_LIBRARY_PATH"] = path > >> Currently, I can only run the program in the terminal: > >> export LD_LIBRARY_PATH=/home/dude/Desktop/test > >> python /home/dude/Desktop/testLoadLibLinux.py > >> This works (yaaayy!), but I'd like to run the .py file directly. > >> Is this possible? I also don't? like the fact that I can't test the .py > file > >> in Idle. > >> Perhaps a complicating factor is a bug in LD_LIBRARY_PATH > >> in Linux Ubuntu 10 (the version I'm using): > >> https://bugs.edge.launchpad.net/ubuntu/+source/xorg/+bug/366728 > >> https://bugs.launchpad.net/ubuntu/+source/xorg/+bug/366728/comments/21 > >> solution: > >> sudo gedit /etc/X11/Xsession.options > >> (change "use-ssh-agent" into "no-use-ssh-agent") > >> > >> Thank you in advance for your thoughts! > >> > >> Cheers!! > >> Albert-Jan > >> > > > >Alright, I'm not going to pretend to be an expert on this one, a bit > >of this is speculation and inference from what I know about dynamic > >linking. In short, I don't think you can modify LD_LIBRARY_PATH on the > >fly and have it actually work. The reason for this is that the linker > >runs and finds all the libraries *before* the python process actually > >starts. So by the time you go and modify the environment, all > >libraries have already been linked, and your modified variable is > >never even read by the linker. > > > >So the best you can do is write a tiny wrapper to set LD_LIBRARY_PATH > >and then run your actual script through it. Or you could set the > >environment variable and then fork(), I suppose, since the child will > >inherit the modified environment. But the wrapper is your simplest > >option. > > > >HTH, > >Hugo > > > > > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20111016/792dc422/attachment-0001.html > > > > ------------------------------ > > Message: 3 > Date: Sun, 16 Oct 2011 15:00:04 -0400 > From: Jacob Bender > To: Hugo Arts > Cc: Python Tutor , bob gailer > Subject: Re: [Tutor] Socket and Ports > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > Thank you, and I'm not planning on executing any data I receive from > anybody. So I should be pretty safe... > > On Sun, Oct 16, 2011 at 10:48 AM, Hugo Arts wrote: > > > On Sun, Oct 16, 2011 at 4:20 PM, bob gailer wrote: > > > On 10/16/2011 8:28 AM, Jacob Bender wrote: > > >> > > >> Dear Tutors, > > >> > > >> I've been having an issue with socket. I wanted to use it for > > >> transmitting strings over the Internet. > > > > > > That's good, because strings is all you can transmit. > > > > > >> The problem is that my friend insists that allowing python to transmit > > and > > >> receive information via an Internet port is a bad idea. He claimed > that > > I > > >> could(and probably would) receive information that wouldn't > necessarily > > do > > >> my computer any good(in a nutshell). > > > > > > I am not the expert on this issue. My view: > > > > > > once you establish a socket connection then you wait to receive data. > All > > > the socket software (Python or other) does is receive a string. What > you > > do > > > with it is up to you. If you apply eval or exec to it than anything > could > > > happen. No one can IMHO cause any action via socket. > > > > > > > vulnerabilities in the lower level stack notwithstanding, of course. > > But in essence, using sockets in python is not any more dangerous than > > using sockets in any other language. You have to watch what you're > > doing and be careful with the data you receive, but as long as you do > > that you shouldn't be in any danger. > > > > Hugo > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20111016/a2d911bb/attachment-0001.html > > > > ------------------------------ > > >Message: 4 > >Date: Sun, 16 Oct 2011 19:43:06 +0000 > >From: ADRIAN KELLY > >To: > >Subject: [Tutor] 6 random numbers > >Message-ID: > >Content-Type: text/plain; charset="iso-8859-1" > > > > > >hello all, > >anyone know how i would go about printing 6 random numbers, i know i could > copy and paste 6 times (which would work) but i was >thinking about a while > loop, ie. while lottery_numbers.count is <7. > >Is it possible to code this? is it possible to count random variables? i > am trying to keep the program as simple as possible, cheers > > > >any help would be welcome, > > > >import random > >lottery_numbers=random.randrange(1,42) > >print lottery_numbers > In fact it is. I notice, however, that you include 2 arguments in the randrange method, which only takes 1 argument. To do this, this code should work: times = 1 while times < 7: import random lottery_numbers=random.randrange(1, 42) print lottery_numbers times+=1 > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20111016/4c9e4d5c/attachment.html > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 92, Issue 77 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From shantanoo at gmail.com Sun Oct 16 22:23:18 2011 From: shantanoo at gmail.com (=?utf-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Mon, 17 Oct 2011 01:53:18 +0530 Subject: [Tutor] 6 random numbers In-Reply-To: References: Message-ID: <9C4F488E-E932-4EEB-B1E8-98A9B59D62E4@gmail.com> On 17-Oct-2011, at 1:13 AM, ADRIAN KELLY wrote: > hello all, > anyone know how i would go about printing 6 random numbers, i know i could copy and paste 6 times (which would work) but i was thinking about a while loop, ie. while lottery_numbers.count is <7. > Is it possible to code this? is it possible to count random variables? i am trying to keep the program as simple as possible, cheers > > any help would be welcome, > > import random > lottery_numbers=random.randrange(1,42) > print lottery_numbers > Following example may be useful: x = [random.randrange(1, 1+random.randrange(42) for _ in range(100)] Useful read: http://docs.python.org/tutorial/datastructures.html -- shantanoo http://xkcd.com/221/ From eq742 at ncf.ca Mon Oct 17 00:23:45 2011 From: eq742 at ncf.ca (pierre dagenais) Date: Sun, 16 Oct 2011 18:23:45 -0400 Subject: [Tutor] httplib2.RelativeURIError: Only absolute URIs are allowed. uri Message-ID: <4E9B5971.3000909@ncf.ca> Hi, I'm running python 3.2 on Ubuntu 11.04 and have a problem with httplib2. I'm not sure if it's my ignorance or a bug in the code. This code works: #! /usr/bin/python3.2 import urllib.request sock = urllib.request.urlopen("file:///home/pierre/bookmarks.html") htmlSource = sock.read() sock.close() print (htmlSource) and so does this one: #! /usr/bin/python3.2 import httplib2 h = httplib2.Http('.cache') response, content = h.request("http://google.com") print(response) but this one doesn't: #! /usr/bin/python3.2 import httplib2 h = httplib2.Http('.cache') response, content = h.request("file:///home/pierre/bookmarks.html") print(response) I get this error message when I run it: Traceback (most recent call last): File "Meteo5.py", line 6, in response, content = h.request("file:///home/pierre/bookmarks.html") File "/usr/lib/python3/dist-packages/httplib2/__init__.py", line 984, in request (scheme, authority, request_uri, defrag_uri) = urlnorm(uri) File "/usr/lib/python3/dist-packages/httplib2/__init__.py", line 137, in urlnorm raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri) httplib2.RelativeURIError: Only absolute URIs are allowed. uri = file:///home/pierre/bookmarks.html Isn't "file:///home/pierre/bookmarks.html" a valid URI? It works fine with urllib, why not with httplib2? Your help is appreciated, From alan.gauld at btinternet.com Mon Oct 17 01:09:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Oct 2011 00:09:58 +0100 Subject: [Tutor] Randrange [was: Re: Tutor Digest, Vol 92, Issue 77] In-Reply-To: References: Message-ID: On 16/10/11 21:10, Max S. wrote: > > > On Sun, Oct 16, 2011 at 3:44 PM, > wrote: > > Send Tutor mailing list submissions to > tutor at python.org > .... > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." Please follow the instructions. And while you are at it please don't send the entire content of the digest message, edit it down to the bit that is relevant, it's much easier for us to read it that way, and saves bandwidth for those paying by the byte! > > > >import random > >lottery_numbers=random.randrange(1,42) > >print lottery_numbers > > In fact it is. I notice, however, that you include 2 arguments in the > randrange method, which only takes 1 argument. Nope. ------------------------ >>> help(random.randrange) Help on method randrange in module random: randrange(self, start, stop=None, step=1, int=, default=None, maxwidth=9007199254740992) method of random.Random instance Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want. Do not supply the 'int', 'default', and 'maxwidth' arguments. -------------------------- As you can see it takes quite a few more than one... > To do this, this code should work: > times = 1 > while times < 7: > import random > lottery_numbers=random.randrange(1, 42) > print lottery_numbers > times+=1 It would be better to have the import outside the loop. Also for a fixed number of iterations a for loop is more common: import random for n in range(7): print random.randrange(1,42) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From robert.sjoblom at gmail.com Mon Oct 17 01:10:34 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 17 Oct 2011 01:10:34 +0200 Subject: [Tutor] 6 random numbers Message-ID: >> hello all, >> anyone know how i would go about printing 6 random numbers, i know i could copy and paste 6 times (which would work) but i was thinking about a while loop, ie. while lottery_numbers.count is <7. >> Is it possible to code this? is it possible to count random variables? i am trying to keep the program as simple as possible, cheers >> >> any help would be welcome, >> >> import random >> lottery_numbers=random.randrange(1,42) >> print lottery_numbers >> > > Following example may be useful: > x = [random.randrange(1, 1+random.randrange(42) for _ in range(100)] > > Useful read: > http://docs.python.org/tutorial/datastructures.html This wouldn't work because if you're making a lottery-type program, you can't generate the same number again. A solution would be to check if, say we stored the numbers in a list, len(set(numbers)) == 7 and if it's not append another (random) number. This would be done until len(set(numbers)) == 7. However, it's a bit tedious and the random module offers a much better option: import random numbers = random.sample(range(1,42), 7) random.sample returns k unique random elements from a population sequence; in this case the population sequence is range(1, 42) (I think python 2.x it'd be xrange()?) and the second argument would be the number of elements we want. >>>random.sample(range(1,42), 7) [16, 29, 17, 2, 12, 36, 10] #this list is in selection order! -- best regards, Robert S. From steve at pearwood.info Mon Oct 17 01:27:54 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 17 Oct 2011 10:27:54 +1100 Subject: [Tutor] httplib2.RelativeURIError: Only absolute URIs are allowed. uri In-Reply-To: <4E9B5971.3000909@ncf.ca> References: <4E9B5971.3000909@ncf.ca> Message-ID: <4E9B687A.2050909@pearwood.info> pierre dagenais wrote: > Isn't "file:///home/pierre/bookmarks.html" a valid URI? It works fine > with urllib, why not with httplib2? "file://..." is not a HTTP resource. -- Steven From steve at pearwood.info Mon Oct 17 01:33:16 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 17 Oct 2011 10:33:16 +1100 Subject: [Tutor] 6 random numbers In-Reply-To: References: Message-ID: <4E9B69BC.5030401@pearwood.info> ADRIAN KELLY wrote: > hello all, > anyone know how i would go about printing 6 random numbers, i know i could copy and paste 6 times (which would work) but i was thinking about a while loop, ie. while lottery_numbers.count is <7. > Is it possible to code this? is it possible to count random variables? i am trying to keep the program as simple as possible, cheers > > any help would be welcome, > > import random > lottery_numbers=random.randrange(1,42) > print lottery_numbers Whenever you want to do something repeatedly, a for-loop or while-loop is usually the answer. If you know how many times you need to do it, use a for-loop: for i in range(6): print random.randrange(1,42) If you don't know how many times, use a while-loop: total = 0 while total < 100: total += random.randrange(1,42) print total If you want to collect the intermediate results, either store them in a list: results = [] for i in range(6): results.append(random.randrange(1,42)) or use a list comprehension, which is syntactic sugar for a for-loop: results = [random.randrange(1,42) for i in range(6)] -- Steven From stefan_ml at behnel.de Mon Oct 17 07:54:46 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 17 Oct 2011 07:54:46 +0200 Subject: [Tutor] 6 random numbers In-Reply-To: References: Message-ID: ADRIAN KELLY, 16.10.2011 21:43: > anyone know how i would go about printing 6 random numbers print(75, 45, 6, 35, 36472, 632) Numbers were generated by typing randomly on my keyboard. Sorry-for-taking-it-all-too-literally-ly, Stefan From sagar at scubed.in Mon Oct 17 12:31:24 2011 From: sagar at scubed.in (Sagar Shankar) Date: Mon, 17 Oct 2011 16:01:24 +0530 Subject: [Tutor] A better way to estimate the value of Pi? Message-ID: Hi, this is my first question to this group. I'm a beginner to computer science and programming in Python. Am currently using John Zelle's book - Python Programming: An introduction to computer science to teach myself. In the book, there is an exercise to create a program that approximates the value of Pi by using the series [image: image.png] Now, the only way I've been able to figure out how to do this is by creating pairs of 4/x - 4/x+2 and calculating the series. The problem is that the exercise asks to prompt the user for the number of terms to sum, and then output the sum. So if an user inputs just 1, then his answer should be 4/1, whereas in my version it will 4/1-4/3 Is there anyway I can implement this without using my current pair method? I don't want to us if-else statements as it has not been introduced at this level of the book and I really want to know if there is an algorithmic way I'm missing. My program is copied below for your reference. Thanks a lot for your help! Regards, Sagar import math def main(): counter = 0.0 y = 1.0 seed = input("Please enter the number of pairs to calculate: ") for i in range(1, seed+1): z = y + 2 approx = 4.0/(y) - 4.0/(z) counter = counter + approx y = z + 2 print "The difference between computed value of Pi and actual value is ", math.pi-counter main() -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image.png Type: image/png Size: 1843 bytes Desc: not available URL: From steve at pearwood.info Mon Oct 17 13:06:25 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 17 Oct 2011 22:06:25 +1100 Subject: [Tutor] A better way to estimate the value of Pi? In-Reply-To: References: Message-ID: <4E9C0C31.4050909@pearwood.info> Sagar Shankar wrote: > Hi, this is my first question to this group. I'm a beginner to computer > science and programming in Python. Am currently using John Zelle's book - > Python Programming: An introduction to computer science to teach myself. Hi Sagar, and welcome. Can I ask you to please post code using plain text rather than HTML email (also known as "rich text"), as HTML email messes up the formatting? In this case, I can reverse-engineer the correct formatting, so no harm done other than a waste of time, but that won't always be so easy. > In the book, there is an exercise to create a program that approximates the > value of Pi by using the series [image: image.png] > > Now, the only way I've been able to figure out how to do this is by creating > pairs of 4/x - 4/x+2 and calculating the series. The problem is that the > exercise asks to prompt the user for the number of terms to sum, and then > output the sum. So if an user inputs just 1, then his answer should be 4/1, > whereas in my version it will 4/1-4/3 The series looks like: 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 +- ... Three things stand out: (1) The *numerator* of each term is always 4. (2) The *denominator* of the terms are 1, 3, 5, ... or to put it another way, the term in position i has denominator 2*i+1 (starting with i=0). (3) The *sign* of the terms are +1, -1, +1, -1, +1, ... If you remember your high school maths, (-1)**0 = +1, (-1)**1 = -1, (-1)**2 = +1, etc. So the term in position i has denominator (-1)**i. Putting those three things together, the term in position i (starting with i=0) has value 4.0*(-1)**i/(2*i+1). Does that help? One other thing: > import math > seed = input("Please enter the number of pairs to calculate: ") In Python 2, you shouldn't use input() for user input. It was a design mistake, which has now been fixed in Python 3, but in Python 2 you should use raw_input() instead. The problem with input() is that it takes the user's input and *executes it as code*, which could have all sorts of bad side-effects starting with errors and just getting worse: >>> name = input("What is your name? ") What is your name? Steven Traceback (most recent call last): File "", line 1, in ? File "", line 0, in ? NameError: name 'Steven' is not defined Instead, you should say this: seed = int(raw_input("How many terms would you like? ")) -- Steven From robert.sjoblom at gmail.com Mon Oct 17 13:35:57 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 17 Oct 2011 13:35:57 +0200 Subject: [Tutor] 6 random numbers Message-ID: > ? ? print random.randrange(1,42) > If you want to collect the intermediate results, either store them in a > list: > > results = [] > for i in range(6): > ? ? results.append(random.randrange(1,42)) Gmail has removed the "Reply All" function for some ABSOLUTELY RIDICULOUS REASON, so I think people missed my reply on this. randrange is a horrible way to generate lottery numbers because it doesn't generate unique numbers, and as for lotteries I don't think I've seen a single one where they put the balls back before selecting a new. random.sample is better because it does (for this purpose, at least) and it stores the result in a list automatically. Let's hope this email goes to the right thread. :/ -- best regards, Robert S. From bgailer at gmail.com Mon Oct 17 17:40:39 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 17 Oct 2011 11:40:39 -0400 Subject: [Tutor] A better way to estimate the value of Pi? In-Reply-To: References: Message-ID: <4E9C4C77.6080708@gmail.com> On 10/17/2011 6:31 AM, Sagar Shankar wrote: > Hi, this is my first question to this group. I'm a beginner to > computer science and programming in Python. Am currently using John > Zelle's book - Python Programming: An introduction to computer science > to teach myself. > > In the book, there is an exercise to create a program that > approximates the value of Pi by using the series image.png It is not crucial here - but you must recognize that your program uses floating point numbers, which almost always are an approximation to the "real" value. For example (assuming decimal numbers): >>> 4/3.0 1.3333333333333333 (followed by an unending number of 0's). The "real" value of 4/3.0 is 1 followed by an unending number of 3's. Each successive fraction's floating point value will be "off" by some relatively small value. Those errors will probably add up. Another limitation of floating point numbers is that there is a maximum and a minimum exponent. Eventually the fractions will be too small to convert to float, raising an overflow exception. Allof this raises the question - what computer algorithms successively approximate pi exactly? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/png Size: 1843 bytes Desc: not available URL: From sagar at scubed.in Mon Oct 17 17:55:51 2011 From: sagar at scubed.in (Sagar Shankar) Date: Mon, 17 Oct 2011 21:25:51 +0530 Subject: [Tutor] A better way to estimate the value of Pi? In-Reply-To: <4E9C4C77.6080708@gmail.com> References: <4E9C4C77.6080708@gmail.com> Message-ID: Hi Bob, I did use floating point numbers by using 4.0/1.0 - 4.0/3.0 etc., though I did not declare it explicitly. Do you think it's better form/practice to explicitly declare it? Regards, Sagar On Mon, Oct 17, 2011 at 9:10 PM, bob gailer wrote: > On 10/17/2011 6:31 AM, Sagar Shankar wrote: > > Hi, this is my first question to this group. I'm a beginner to computer > science and programming in Python. Am currently using John Zelle's book - > Python Programming: An introduction to computer science to teach myself. > > In the book, there is an exercise to create a program that approximates > the value of Pi by using the series [image: image.png] > > > It is not crucial here - but you must recognize that your program uses > floating point numbers, which almost always are an approximation to the > "real" value. > > For example (assuming decimal numbers): > > >>> 4/3.0 > 1.3333333333333333 (followed by an unending number of 0's). > > The "real" value of 4/3.0 is 1 followed by an unending number of 3's. > > Each successive fraction's floating point value will be "off" by some > relatively small value. Those errors will probably add up. > > Another limitation of floating point numbers is that there is a maximum and > a minimum exponent. Eventually the fractions will be too small to convert to > float, raising an overflow exception. > > Allof this raises the question - what computer algorithms successively > approximate pi exactly? > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/png Size: 1843 bytes Desc: not available URL: From steve at pearwood.info Mon Oct 17 18:00:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 18 Oct 2011 03:00:27 +1100 Subject: [Tutor] A better way to estimate the value of Pi? In-Reply-To: References: <4E9C4C77.6080708@gmail.com> Message-ID: <4E9C511B.2070002@pearwood.info> Sagar Shankar wrote: > Hi Bob, > > I did use floating point numbers by using 4.0/1.0 - 4.0/3.0 etc., though I > did not declare it explicitly. Do you think it's better form/practice to > explicitly declare it? Python doesn't use type declarations. 4.0 is already explicitly a float, there's no need to do anything else to make it a float. -- Steven From ashish.gec at gmail.com Mon Oct 17 18:13:13 2011 From: ashish.gec at gmail.com (Ashish Gaonker) Date: Mon, 17 Oct 2011 21:43:13 +0530 Subject: [Tutor] Jython for mutlithreading and on multicore system Message-ID: Does Jython improve GIL issues of python by using JVM based threads? Will code work faster on Jython then CPython? Can anybody help me to understand this? -- Thanks & Regards Ashish Gaonker -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Oct 17 18:23:21 2011 From: d at davea.name (Dave Angel) Date: Mon, 17 Oct 2011 12:23:21 -0400 Subject: [Tutor] A better way to estimate the value of Pi? In-Reply-To: References: <4E9C4C77.6080708@gmail.com> Message-ID: <4E9C5679.7000405@davea.name> On 10/17/2011 11:55 AM, Sagar Shankar wrote: > >> The "real" value of 4/3.0 is 1 followed by an unending number of 3's. >> >> Each successive fraction's floating point value will be "off" by some >> relatively small value. Those errors will probably add up. >> >> Another limitation of floating point numbers is that there is a maximum and >> a minimum exponent. Eventually the fractions will be too small to convert to >> float, raising an overflow exception. >> >> Allof this raises the question - what computer algorithms successively >> approximate pi exactly? >> >> -- >> Bob Gailer >> 919-636-4239 >> Chapel Hill NC >> >> There are two separate problems with doing this operation in floats. One is that the final answer can be no closer than a float knows how to represent. But the second is the cumulative error caused by adding a bunch of values of differing magnitudes. You can at least reduce the second by adding them in reverse order. In other words, build a list of floats for the terms of the series, then reverse the list and sum it. -- DaveA From steve at pearwood.info Mon Oct 17 18:47:02 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 18 Oct 2011 03:47:02 +1100 Subject: [Tutor] A better way to estimate the value of Pi? In-Reply-To: <4E9C4C77.6080708@gmail.com> References: <4E9C4C77.6080708@gmail.com> Message-ID: <4E9C5C06.2000709@pearwood.info> bob gailer wrote: > It is not crucial here - but you must recognize that your program uses floating > point numbers, which almost always are an approximation to the > "real" value. > > For example (assuming decimal numbers): > > >>> 4/3.0 > 1.3333333333333333 (followed by an unending number of 0's). Actually no, it is not followed by an unending number of zeroes. That would imply that floats had infinite precision, but 4/3.0 was merely calculated inaccurately. That's not the case: floats have a finite precision, but are (or at least, should be) accurate to within the limitations of that precision. The exact value for 4.0/3 is actually: 1.3333333333333332593184650249895639717578887939453125 which is the closest possible binary fraction to 4/3. > The "real" value of 4/3.0 is 1 followed by an unending number of 3's. > > Each successive fraction's floating point value will be "off" by some relatively > small value. Those errors will probably add up. > > Another limitation of floating point numbers is that there is a maximum and a > minimum exponent. Eventually the fractions will be too small to convert to > float, raising an overflow exception. I don't think you need to worry about that. It takes a pretty big denominator before overflow will occur: a googol won't do it: >>> 4.0/10**100 4.0000000000000001e-100 Even though the series given is very slow to converge (3000000 terms is only accurate to 6 decimal places), I expect that it will converge before the terms overflow. It might take many hours or days of processing though. > Allof this raises the question - what computer algorithms successively > approximate pi exactly? Er, by definition you can't APPROXIMATE something EXACTLY. But see here for more approximations to ? http://en.wikipedia.org/wiki/Approximations_of_%CF%80 -- Steven From alan.gauld at btinternet.com Mon Oct 17 19:03:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Oct 2011 18:03:35 +0100 Subject: [Tutor] Jython for mutlithreading and on multicore system In-Reply-To: References: Message-ID: On 17/10/11 17:13, Ashish Gaonker wrote: > Does Jython improve GIL issues of python by using JVM based threads? > Will code work faster on Jython then CPython? Can anybody help me to > understand this? Speaking personally I've always fond CPython to be faster than equivalent code in Jython. But that's purely anecdotal, I haven't performed any extensive tests. However, I'd certainly not be rushing to port code to Jython as a speed improvement - Cython now, that's a different story... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kellyadrian at hotmail.com Mon Oct 17 20:24:18 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Mon, 17 Oct 2011 18:24:18 +0000 Subject: [Tutor] FW: 6 random numbers(again) In-Reply-To: <9C4F488E-E932-4EEB-B1E8-98A9B59D62E4@gmail.com> References: , <9C4F488E-E932-4EEB-B1E8-98A9B59D62E4@gmail.com> Message-ID: > Subject: Re: [Tutor] 6 random numbers > From: shantanoo at gmail.com > Date: Mon, 17 Oct 2011 01:53:18 +0530 > CC: tutor at python.org > To: kellyadrian at hotmail.com > > On 17-Oct-2011, at 1:13 AM, ADRIAN KELLY wrote: > > > hello all, > > anyone know how i would go about printing 6 random numbers, i know i could copy and paste 6 times (which would work) but i was thinking about a while loop, ie. while lottery_numbers.count is <7. > > Is it possible to code this? is it possible to count random variables? i am trying to keep the program as simple as possible, cheers > > > > any help would be welcome, > > > > import random > > lottery_numbers=random.randrange(1,42) > > print lottery_numbers > > > > Following example may be useful: > x = [random.randrange(1, 1+random.randrange(42) for _ in range(100)] > > Useful read: > http://docs.python.org/tutorial/datastructures.html > > -- > shantanoo > http://xkcd.com/221/ > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Oct 17 20:52:11 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 17 Oct 2011 13:52:11 -0500 Subject: [Tutor] Jython for mutlithreading and on multicore system In-Reply-To: References: Message-ID: On Mon, Oct 17, 2011 at 11:13 AM, Ashish Gaonker wrote: > Does Jython improve GIL issues of python by using JVM based threads? > Will code work faster on Jython then CPython? Can anybody help me to > understand this? You can use the multiprocessing module ( http://docs.python.org/library/multiprocessing.html) that was developed to sidestep the issue of the GIL, if you'd prefer to stay in pure Python. I believe Jython does use JVM threads, and I have read that IronPython also uses true threading, bypassing the GIL. As far as what code runs faster, well that depends on your Python code! The main reason that you would see a speedup between the two implementations, as far as threading goes, is if you were really spending a lot of time waiting on the GIL. Just doing a quick Google search for "python threading" results in several good articles. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Mon Oct 17 22:01:19 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Mon, 17 Oct 2011 20:01:19 +0000 Subject: [Tutor] (no subject) Message-ID: Hello world, can anyone tell me how i can perfect the program below. it works find (prints 6 random numbers within a range) but on occasions the numbers are repeated. Thanks so much everyone #program that will allow the user to generate random numbers #from a range that they select. import random #set values number=0 base=input ("Enter the bottom of the range? ") upper=input ("Enter the upper limit of your range: ") quantity=input ("How many numbers do you want to select: ") number =0 while number From jacktradespublic at gmail.com Mon Oct 17 22:42:47 2011 From: jacktradespublic at gmail.com (Nick Zarr) Date: Mon, 17 Oct 2011 15:42:47 -0500 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: I think this was already mentioned in the replies to your other post: from random import sample base = int(input("Enter the bottom of the range? ")) upper = int(input("Enter the upper limit of your range: ")) quantity = int(input("How many numbers do you want to select: ")) sample(range(base, upper), quantity) http://docs.python.org/library/random.html#random.sample -- Nick Zarczynski Blog 4 -------------- next part -------------- An HTML attachment was scrubbed... URL: From ryan.strunk at gmail.com Tue Oct 18 03:25:13 2011 From: ryan.strunk at gmail.com (Ryan Strunk) Date: Mon, 17 Oct 2011 20:25:13 -0500 Subject: [Tutor] Keyboard Module In-Reply-To: References: <017d01cc887e$e02a7f00$a07f7d00$@gmail.com> Message-ID: <001201cc8d34$ca1a9fa0$5e4fdee0$@gmail.com> > So use raw wx key events. They include key down,up and press events. I'll give this a shot. Thank you. > Bloated carries the connotation of unnecessary code, but pygame provides a lot of functionality. You may not need it all, and using pygame may require you to import more than you need. But thats not quite the same as saying pygame is bloated. > And its not that huge that it should stop you using it. > If it works, why not? Thanks for the clarification on that. Would there be any benefit to using Pygame in addition to other libraries for game development, or is it robust enough that it should be able to stand on its own? Thanks as always, Ryan From sagar at scubed.in Tue Oct 18 07:28:36 2011 From: sagar at scubed.in (Sagar Shankar) Date: Tue, 18 Oct 2011 10:58:36 +0530 Subject: [Tutor] A better way to estimate the value of Pi? Message-ID: Hi Steven, > Can I ask you to please post code using plain text rather than HTML > email (also known as "rich text"), as HTML email messes up the > formatting? In this case, I can reverse-engineer the correct formatting, > so no harm done other than a waste of time, but that won't always be so > easy. Sure Steve, will do so from now on > > Three things stand out: > > (1) The *numerator* of each term is always 4. > > (2) The *denominator* of the terms are 1, 3, 5, ... or to put it another > way, the term in position i has denominator 2*i+1 (starting with i=0). > > (3) The *sign* of the terms are +1, -1, +1, -1, +1, ... If you remember > your high school maths, (-1)**0 = +1, (-1)**1 = -1, (-1)**2 = +1, etc. > So the term in position i has denominator (-1)**i. > > Putting those three things together, the term in position i (starting > with i=0) has value 4.0*(-1)**i/(2*i+1). > > Does that help? It does! I wonder why this simplification never occurred to me. Will implement this and try it out > One other thing: > > > import math > > seed = input("Please enter the number of pairs to calculate: ") > > In Python 2, you shouldn't use input() for user input. It was a design > mistake, which has now been fixed in Python 3, but in Python 2 you > should use raw_input() instead. > > The problem with input() is that it takes the user's input and *executes > it as code*, which could have all sorts of bad side-effects starting > with errors and just getting worse: > > ?>>> name = input("What is your name? ") > What is your name? Steven > Traceback (most recent call last): > ? File "", line 1, in ? > ? File "", line 0, in ? > NameError: name 'Steven' is not defined > > Instead, you should say this: > > > seed = int(raw_input("How many terms would you like? ")) > Absolutely. I was just following Zelle's book and he introduces raw_input in the 4th chapter only. I will definitely use the raw_input method, especially as using "input" alone trips up string input Thanks a lot for the help Steve, Sagar From ashish.gec at gmail.com Tue Oct 18 10:49:47 2011 From: ashish.gec at gmail.com (Ashish Gaonker) Date: Tue, 18 Oct 2011 14:19:47 +0530 Subject: [Tutor] Performance measurement tools Message-ID: Hi Can you suggest the best performance measurent tools for python programs. specifically thread based python modules. -- Thanks & Regards Ashish Gaonker -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Tue Oct 18 14:34:29 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 18 Oct 2011 14:34:29 +0200 Subject: [Tutor] Performance measurement tools In-Reply-To: References: Message-ID: On Tue, Oct 18, 2011 at 10:49 AM, Ashish Gaonker wrote: > Hi > Can you suggest the best?performance?measurent tools for python programs. > specifically thread based python modules. > -- > Thanks & Regards > Ashish Gaonker I've heard very good things about yappi: http://code.google.com/p/yappi/ From waynejwerner at gmail.com Tue Oct 18 18:08:50 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 18 Oct 2011 11:08:50 -0500 Subject: [Tutor] Keyboard Module In-Reply-To: <001201cc8d34$ca1a9fa0$5e4fdee0$@gmail.com> References: <017d01cc887e$e02a7f00$a07f7d00$@gmail.com> <001201cc8d34$ca1a9fa0$5e4fdee0$@gmail.com> Message-ID: On Mon, Oct 17, 2011 at 8:25 PM, Ryan Strunk wrote: > > Bloated carries the connotation of unnecessary code, but pygame provides > a lot of functionality. You may not need it all, and using pygame may > require you to import more than you need. But thats not quite the same > as saying pygame is bloated. > > And its not that huge that it should stop you using it. > > If it works, why not? > Thanks for the clarification on that. Would there be any benefit to using > Pygame in addition to other libraries for game development, or is it robust > enough that it should be able to stand on its own? > If you're just worried about game development, Pygame is a very strong toolkit. My recommendation would be to use it, and see if it suits your needs. If you discover that there are things that Pygame doesn't make fairly easy, that's when you should start looking for other solutions. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Oct 18 19:14:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Oct 2011 18:14:08 +0100 Subject: [Tutor] Keyboard Module In-Reply-To: <001201cc8d34$ca1a9fa0$5e4fdee0$@gmail.com> References: <017d01cc887e$e02a7f00$a07f7d00$@gmail.com> <001201cc8d34$ca1a9fa0$5e4fdee0$@gmail.com> Message-ID: On 18/10/11 02:25, Ryan Strunk wrote: >> And its not that huge that it should stop you using it. > Thanks for the clarification on that. Would there be any benefit to using > Pygame in addition to other libraries for game development, It would not be unusual to use other libraries with PyGame. But those would not normally include another gaming framework. > ...is it robust enough that it should be able to stand on its own? If by "robust enough" you mean is it complete in and of itself, then the answer is probably no. PyGame tackles one subset of tasks, those commonly encountered building games. But if you need to access web pages, or databases etc then you would need to use other modules. If you mean robust in the sense of being reliable, not buggy, then yes I believe PyGame is as robust as most Python libraries. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From 0101amt at gmail.com Tue Oct 18 19:58:28 2011 From: 0101amt at gmail.com (amt) Date: Tue, 18 Oct 2011 20:58:28 +0300 Subject: [Tutor] Other ways to use raw_input function Message-ID: Greetings! I got stuck at an exercise from the book learn python the hard way about raw_input function.(exercise 11.2) After reading from docs.python.org I found out that this function can perform standard output without a trailing newline.Also it can take an input line, convert it as a string( stripping a trailing newline) and return it. The exercise question is : Can you find other ways to use it? Here is the original code from the book: print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight) Now, the only different way I was able to use raw_input is: age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input("How much do you weigh? ") print "So, you're %r old, %r tall and %r heavy." % (age, height, weight) Are there any other ways of using it? If yes can you please give me a detailed example so I can understand. Thanks in advance, amt. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rocklearnpython at gmail.com Tue Oct 18 19:59:50 2011 From: rocklearnpython at gmail.com (Navneet) Date: Tue, 18 Oct 2011 23:29:50 +0530 Subject: [Tutor] close failed in file object destructor: In-Reply-To: <4E9DBDBE.30503@gmail.com> References: <4E9DBDBE.30503@gmail.com> Message-ID: <4E9DBE96.2000700@gmail.com> Hi, I am trying to search a list for prime numbers but it's throwing me an error at line no.25. I am not able to figure what exactly is the prob ne help ??? Error is this: $ python "prime1 - Copy.py" Unhandled exception in thread started by Traceback (most recent call last): File "prime1 - Copy.py", line 25, in findPrime close failed in file object destructor: Error in sys.excepthook: program is below: Numberlist is number range from 1..1000 import sys import threading import thread import time class FindPno(): c = [] f = open("A;\Numberlist.txt") for i in f: c.append(i) f.close() ##print len(c) ##Thread should start here def __init__(self): thread.start_new_thread(self.findPrime,(1,)) def findPrime(self,tid): global tlock ## print "I am here" tlock = thread.allocate_lock() ## print "I am here" tlock.acquire() ## print "I am here" for i1 in range(len(c)): ##this is the 25th line for i2 in range(2,int(c[i1])): if int(c[i1]) == 1: print "I am here" tlock.release() break if int(c[i1]) == 2: print c print "I am here" tlock.release() break rem = int(c[i1])%i2 if rem == 0: print "I am here" tlock.release() break if i2 == int(c[i1])-1: print int(c[i1]), "This is the Thread",tid print "I am here" tlock.release() tlock.release() if __name__ == '__main__': a = FindPno() -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Oct 18 20:09:11 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 18 Oct 2011 13:09:11 -0500 Subject: [Tutor] Other ways to use raw_input function In-Reply-To: References: Message-ID: On Tue, Oct 18, 2011 at 12:58 PM, amt <0101amt at gmail.com> wrote: > Greetings! I got stuck at an exercise from the book learn python the hard > way about raw_input function.(exercise 11.2) > > After reading from docs.python.org I found out that this function can > perform standard output without a trailing newline.Also it can take an input > line, convert it as a string( stripping a trailing newline) and return it. > > > The exercise question is : Can you find other ways to use it? > Are there any other ways of using it? If yes can you please give me > a detailed example so I can understand. > The most common other way that I use it is on Windows. If you want the terminal to stay open after your program has finished executing you can do something like this: # print_odds.py # Prints some odd numbers for x in xrange(1, 20, 2): print x raw_input("Press to continue") I've done similar things when debugging in a loop - instead of using print, I use raw_input and it lets me see the output and waits for me to hit enter to continue the loop. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Oct 18 21:06:09 2011 From: d at davea.name (Dave Angel) Date: Tue, 18 Oct 2011 15:06:09 -0400 Subject: [Tutor] close failed in file object destructor: In-Reply-To: <4E9DBE96.2000700@gmail.com> References: <4E9DBDBE.30503@gmail.com> <4E9DBE96.2000700@gmail.com> Message-ID: <4E9DCE21.30702@davea.name> On 10/18/2011 01:59 PM, Navneet wrote: > Hi, > > I am trying to search a list for prime numbers but it's throwing me an > error at line no.25. > I am not able to figure what exactly is the prob > ne help ??? Error is this: > $ python "prime1 - Copy.py" > Unhandled exception in thread started by > Traceback (most recent call last): > File "prime1 - Copy.py", line 25, in findPrime > close failed in file object destructor: > Error in sys.excepthook: > > program is below: Numberlist is number range from 1..1000 > > > import sys > import threading > import thread > import time > > class FindPno(): > > c = [] > f = open("A;\Numberlist.txt") > for i in f: > c.append(i) > f.close() > ##print len(c) > ##Thread should start here > def __init__(self): > thread.start_new_thread(self.findPrime,(1,)) > > def findPrime(self,tid): > global tlock > ## print "I am here" > tlock = thread.allocate_lock() > ## print "I am here" > tlock.acquire() > ## print "I am here" > for i1 in range(len(c)): ##this is the 25th line > for i2 in range(2,int(c[i1])): > > if int(c[i1]) == 1: > print "I am here" > tlock.release() > break > if int(c[i1]) == 2: > print c > print "I am here" > tlock.release() > break > rem = int(c[i1])%i2 > if rem == 0: > print "I am here" > tlock.release() > break > if i2 == int(c[i1])-1: > print int(c[i1]), "This is the Thread",tid > print "I am here" > tlock.release() > > tlock.release() > > if __name__ == '__main__': > a = FindPno() > I have no idea what you're trying to accomplish here. The code is far too complex to solve the problem you've described, and very inefficient besides. And threads won't help speed up a CPU-bound Python program of this type. I also have no idea how you got the traceback you showed. After I cleaned up a lot of other stuff, I get the error: Traceback (most recent call last): File "prim.py", line 52, in a = FindPno() File "prim.py", line 19, in __init__ self.findPrime(0) File "prim.py", line 28, in findPrime for i2 in range(2,int(c[i1])): NameError: global name 'c' is not defined And the problem with that is that the class attribute 'c' would need a prefix to address it in a method. Simplest would be to say self.c each place you have c. or else just declare global c inside the class scope. Is this program transliterated from some other language? Or were there some strange constraints in the original assignment? After cleanup, the program does work, but I had to get rid of the thread stuff to make it work here. As written, the program terminates before the extra thread does any work. -- DaveA From bgailer at gmail.com Tue Oct 18 22:53:47 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 18 Oct 2011 16:53:47 -0400 Subject: [Tutor] close failed in file object destructor: In-Reply-To: <4E9DBE96.2000700@gmail.com> References: <4E9DBDBE.30503@gmail.com> <4E9DBE96.2000700@gmail.com> Message-ID: <4E9DE75B.3040801@gmail.com> Following written before Dave Angel's post but sent afterwards. On 10/18/2011 1:59 PM, Navneet wrote: > Hi, > > I am trying to search a list for prime numbers but it's throwing me an > error at line no.25. > I am not able to figure what exactly is the prob > ne help ??? Error is this: > $ python "prime1 - Copy.py" > Unhandled exception in thread started by > Traceback (most recent call last): > File "prime1 - Copy.py", line 25, in findPrime > close failed in file object destructor: > Error in sys.excepthook: > > program is below: This program could not produce the above exception. Run it. You should get: f = open("A;\Numberlist.txt") IOError: [Errno 2] No such file or directory: 'A;\\Numberlist.txt' due to the ; in the path name. If you fix that then you should get: Traceback (most recent call last): File "N:\python\findprime.py", line 25, in findPrime for i1 in range(len(c)): ##this is the 25th line NameError: global name 'c' is not defined Please fix these problems and return with a new program and the output from that program. > Numberlist is number range from 1..1000 Huh? What is Numberlist? I only see Numberlist.txt, which I assume is a file. How can a file be number range from 1..1000? Please instead post a sample of the actual file. My *guess* is the file looks like: 1 2 3 etc. My guess may be correct, but having to guess wastes all our time. > > > import sys > import threading > import thread > import time > > class FindPno(): > > c = [] > f = open("A;\Numberlist.txt") > for i in f: > c.append(i) > f.close() replace the above 5 lines with c = open(corrected path).readlines() or even better c = {int(x) for x in ("A;\corrected path)] then you can dispense with > ##print len(c) > ##Thread should start here > def __init__(self): > thread.start_new_thread(self.findPrime,(1,)) > > def findPrime(self,tid): > global tlock > ## print "I am here" > tlock = thread.allocate_lock() > ## print "I am here" > tlock.acquire() > ## print "I am here" > for i1 in range(len(c)): ##this is the 25th line > for i2 in range(2,int(c[i1])): > > if int(c[i1]) == 1: > print "I am here" > tlock.release() > break > if int(c[i1]) == 2: > print c Why print the entire list? > print "I am here" > tlock.release() > break > rem = int(c[i1])%i2 > if rem == 0: > print "I am here" > tlock.release() > break > if i2 == int(c[i1])-1: > print int(c[i1]), "This is the Thread",tid > print "I am here" > tlock.release() > > tlock.release() > > if __name__ == '__main__': > a = FindPno() Why did you use a class? You don't need it, and it complicates things. Why put some of the code in the mainline of the class and some in __init__. I see no need for that separation. Since you use print statements to monitor progress how about addind something so you know which print statement was called. Perhaps print "I am here 1", print "I am here 2", etc. Why have the file at all? Why not just start with c = range(1,1000)? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Oct 18 23:00:28 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 18 Oct 2011 17:00:28 -0400 Subject: [Tutor] close failed in file object destructor: In-Reply-To: <4E9DBE96.2000700@gmail.com> References: <4E9DBDBE.30503@gmail.com> <4E9DBE96.2000700@gmail.com> Message-ID: <4E9DE8EC.8060207@gmail.com> One more thing - tlock = thread.allocate_lock() should be executed once before starting threads. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Oct 19 01:14:13 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Oct 2011 00:14:13 +0100 Subject: [Tutor] Other ways to use raw_input function In-Reply-To: References: Message-ID: On 18/10/11 18:58, amt wrote: > After reading from docs.python.org I found out > that this function can perform standard output without a trailing > newline. It can print a prompt message, yes. > Also it can take an input line, convert it as a string It doesn't convert it to a string, it reads a string. Specifically it reads the raw character string input by the user. Thats why its called raw_input() > stripping a trailing newline) and return it. > The exercise question is : Can you find other ways to use it? There are many ways to use it just as there are many ways to use any function. But the function will always do the same thing. For example you can wrap the function in a type conversion to get numbers instead of strings: quantity = int( raw_input("How many? ") ) Or you can use it to pause a program, for example if displaying a text file a page/screen at a time, or while debugging. > Here is the original code from the book: > > print "How old are you?", > age = raw_input() > print "How tall are you?", > height = raw_input() > print "How much do you weigh?", > weight = raw_input() > print "So, you're%r old,%r tall and%r heavy." % ( > age, height, weight) Obviously you can remove the print statements. And you could convert the height and weight values to numerical ones (probably floats). > Now, the only different way I was able to use raw_input is: > > age =raw_input("How old are you? ") > height= raw_input("How tall are you?") > weight= raw_input("How much do you weigh?") > > print "So, you're %r old, %r tall and %r heavy." % (age, height, weight) Yes, that would be the normal way to do it, or with type conversion: age = int( raw_input("How old are you? ") ) height = float( raw_input("How tall are you?") ) weight = float( raw_input("How much do you weigh?") ) print "So, you're %d old, %f tall and %f heavy." % (age, height, weight) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From benderjacob44 at gmail.com Wed Oct 19 01:26:19 2011 From: benderjacob44 at gmail.com (Jacob Bender) Date: Tue, 18 Oct 2011 19:26:19 -0400 Subject: [Tutor] Socket not connecting Message-ID: Dear Tutors, I'm the same person who asked about intruders getting into my computer via socket. I tried copying a socket program from online, that worked on my computer, and executed perfectly. However, I did not open a port for python, but I do have an exception in my firewall. Anyhow, I called the same friend and had him run a client program when I was running the host program. The host program did absolutely nothing and my IP was programmed into the client as the "Host IP". I took all necessary steps and even turned off my antivirus, which didn't help at all. I also told my friend and now he has an exception on his antivirus, but still nothing is working. I've been using port 80 the whole time. Is there anything I did wrong, or a step I've missed? Here is the source code for both the server and the client I was talking about: *Client:* * * # Echo client program import socket HOST = '# my IP was once here' # The remote host PORT = 80 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send('Hello, world') data = s.recv(1024) s.close() print 'Received', repr(data) * * *Server:* * * # Echo server program import socket HOST = '' # Symbolic name meaning all available interfaces PORT = 80 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Oct 19 02:07:01 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 19 Oct 2011 01:07:01 +0100 Subject: [Tutor] Socket not connecting In-Reply-To: References: Message-ID: Hi Jacob, On 19 October 2011 00:26, Jacob Bender wrote: > > I'm the same person who asked about intruders getting into my computer > via socket. I tried copying a socket program from online, that worked on my > computer, and executed perfectly. However, I did not open a port for python, > but I do have an exception in my firewall. Anyhow, I called the same friend > and had him run a client program when I was running the host program. The > host program did absolutely nothing and my IP was programmed into the client > as the "Host IP". I took all necessary steps and even turned off my > antivirus, which didn't help at all. I also told my friend and now he has an > exception on his antivirus, but still nothing is working. I've been using > port 80 the whole time. Is there anything I did wrong, or a step I've > missed? Here is the source code for both the server and the client I was > talking about: > I presume you tried to make this work over the internet. If so, a few questions: Do you (or rather, does your PC) have a public IP address? If not, then did you configure your router to port forward port 80 from its IP address (which is your public IP address) to your PC's (impliedly) local private address? And did you program your router's public IP address into the client as the IP address to connect to? Cheers, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From dadfar.narguess at gmail.com Wed Oct 19 06:06:37 2011 From: dadfar.narguess at gmail.com (Narguess Dadfar) Date: Tue, 18 Oct 2011 21:06:37 -0700 Subject: [Tutor] Project Message-ID: I have to project all shapefiles to NAD_1983_UTM_Zone_10N I use Python 2.6 what codes I have used is as follow: import arcpy inFolder = arcpy.GetParameterAsText(0) outC = arcpy.GetParameterAsText(1) arcpy.env.workspace = inFolder fcList = arcpy.ListFeatureClasses() try: desc = arcpy.Describe(outC) spatialRef = desc.SpatialReference for featureClass in fcList: arcpy.Project_management (inFolder, outC) rootName = " " if fc.endswith[".shp]: rootName + fc[:4] arcpy.AddMessage("\n" + "The files " + projectedFeatureClasses[:2] + "have successfully been reprojected" + "\n") except: arcpy.AddMessage ("This project is incomplete") arcpy.AddMessage(arcpy.Getmessage()) Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Oct 19 10:33:59 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Oct 2011 09:33:59 +0100 Subject: [Tutor] Socket not connecting In-Reply-To: References: Message-ID: On 19/10/11 00:26, Jacob Bender wrote: > worked on my computer, and executed perfectly. OK, So it probably a networking config issue. > running the host program. The host program did absolutely nothing and my > IP was programmed into the client as the "Host IP". Is it a DHCP generated IP address created by your router/swuitch or is it the IP address assigned by your internet service provider? Your friend will only see the external one. > I've been using port 80 the whole time. While it shouldn't affect whether it works or not you probably should use another port. Port 80 is the "well known port" for http web traffic. It's better to avoid low numbered ports and go for something above 2000 > the source code for both the server and the client I was talking about: They look ok and if they worked with localhost on your PC then they should work over the wider network. (I might try increasing the listen value to say 3 or 5 but it shouldn't really be necessary) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Oct 19 10:37:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Oct 2011 09:37:28 +0100 Subject: [Tutor] Project In-Reply-To: References: Message-ID: On 19/10/11 05:06, Narguess Dadfar wrote: > I have to project all shapefiles to NAD_1983_UTM_Zone_10N > Means nothing to me... > I use Python 2.6 > > what codes I have used is as follow: > Well done. Does it work? If not what doesn't work? Do you get error messages? What do they say? Is the data different to what you expect? Or are you simply sharing your success? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From elwin.estle at gmail.com Wed Oct 19 16:05:17 2011 From: elwin.estle at gmail.com (Elwin Estle) Date: Wed, 19 Oct 2011 10:05:17 -0400 Subject: [Tutor] tkinter binding issues Message-ID: I have a couple of bugs in a program I am working on that I can't quite figure out what is going on. Both are related to the same lines of code, and neither really render the program non-functional, they are just annoying. Attached is the program, zipped together with a couple of abbreviated data files it references. I am using python 2.7. In lines 221, 224, and 226, I use binding on an entry widget to validate the data entered. If the data is invalid, the background color of the widget is changed to red and the foreground to white. The callbacks for these lines are further down in the program starting on lines 302, 317, and 346, respectively. So, here is the first 'bug'. In all three of the callback functions, I added an extra dummy parameter because I kept getting an error message about the callback wanting two parameters, even though I do not pass any parameters and don't really need to. The dummy parameter does nothing and isn't referenced in the function code. But without it, why do I get the error message? The second bug has to do with the routine starting on line 385, which resets all the widgets in the input form to their starting values. If just click inside the three entry widgets, without inputting any data, the backgrounds turn red, as they should. However, when I click the clear form button, which calls the function on line 385, it doesn't always reset these entry boxes back to their original state. It only will do so if the cursor is in the "clock number" entry box. If it is in one of the other two boxes, it will clear all the boxes but that one. If I comment out the first line of the reset form function (the one that sets focus back to the clock number entry widget, then all three are cleared, but the cursor isn't where I want it to be. I get the idea that when focus shifts from whatever box the cursor is in, to the 'yes' button in the tkmessagebox, that it triggers my validation callback and turns the background red, but shouldn't my clear form function still clear it out? Thanks in advance for any assistance. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: CMM_LOG_PY.zip Type: application/zip Size: 4420 bytes Desc: not available URL: From 0101amt at gmail.com Wed Oct 19 16:46:05 2011 From: 0101amt at gmail.com (amt) Date: Wed, 19 Oct 2011 17:46:05 +0300 Subject: [Tutor] Other ways to use raw_input function In-Reply-To: References: Message-ID: Thanks a lot Alan for helping me out every time. Also thanks Wayne! Regards, amt. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Oct 19 19:05:20 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 19 Oct 2011 13:05:20 -0400 Subject: [Tutor] close failed in file object destructor: In-Reply-To: <4E9EF1C6.7020209@gmail.com> References: <4E9DBDBE.30503@gmail.com> <4E9DBE96.2000700@gmail.com> <4E9DE75B.3040801@gmail.com> <4E9EF1C6.7020209@gmail.com> Message-ID: <4E9F0350.3080802@gmail.com> On 10/19/2011 11:50 AM, Navneet wrote: > > Thank you Bob and Dave, > Yes the file is as you expected, I don't understand that comment. > I thought it is easy to figure out that you have to change the file > location in program Don't make that assumption. Of course we can figure that out, but you should use something like that is obviously to be replaced rather than an invalid filename. > > Problem:I am trying to find prime numbers from a file which contains a > list of number and each thread(say 5) is suppose to work on different > number, in short I am applying round-robin method via thread. What does (say 5) mean? Your program will start > > I'll try one more time > BTW I have attached the file :D Please don't attach large files. All I wanted was a sample. We will await your next attempt. Fix the program, Run it. If you don't get the desired results think about why, then either continue fixing or post a new program with a new question. Did you think about all the questions I asked. I did not see any answers. I repeat them here. Please answer. * Why did you use a class? You don't need it, and it complicates things. * Why put some of the code in the mainline of the class and some in __init__. I see no need for that separation. * Since you use print statements to monitor progress how about addind something so you know which print statement was called. Perhaps print "I am here 1", print "I am here 2", etc. * Why have the file at all? Why not just start with c = range(1,1000)? * Why print the entire list? (print c)? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Oct 19 19:53:21 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 19 Oct 2011 13:53:21 -0400 Subject: [Tutor] close failed in file object destructor: In-Reply-To: <4E9F0497.7080103@gmail.com> References: <4E9DBDBE.30503@gmail.com> <4E9DBE96.2000700@gmail.com> <4E9DE75B.3040801@gmail.com> <4E9EF1C6.7020209@gmail.com> <4E9F0350.3080802@gmail.com> <4E9F0497.7080103@gmail.com> Message-ID: <4E9F0E91.7040400@gmail.com> On 10/19/2011 1:10 PM, Navneet wrote: > dude you are rude yaar :)...just chill I am new to python.... and > programming ...but one thing ...you must be a damn good trainer :) > Thanks for your reply. Please always reply-all so a copy goes to the list, I hear you are new to Python, and want to be respected for that. This email list is monitored by a few volunteers. We donate our time trying to help others get more comfortable with Python. When I saw your program (with lots of complexity) I assumed you were more advanced, My fault. I recommend you start with something very simple, get is working, then add (one at a time) something new. For example, write a function that tests a number for primality Apply it to a small list of small numbers. Get it working correctly. Forget (for now) about classes and threads. They just complicate things. > I'll try and will let you know the complete program ...just give me some time .. > > On 10/19/2011 10:35 PM, bob gailer wrote: >> On 10/19/2011 11:50 AM, Navneet wrote: >>> >>> Thank you Bob and Dave, >>> Yes the file is as you expected, >> >> I don't understand that comment. >> >>> I thought it is easy to figure out that you have to change the file >>> location in program >> >> Don't make that assumption. Of course we can figure that out, but you >> should use something like that is obviously to be replaced >> rather than an invalid filename. >>> >>> Problem:I am trying to find prime numbers from a file which contains >>> a list of number and each thread(say 5) is suppose to work on >>> different number, in short I am applying round-robin method via thread. >> >> What does (say 5) mean? Your program will start >>> >>> I'll try one more time >> > BTW I have attached the file :D >> >> Please don't attach large files. All I wanted was a sample. >> >> We will await your next attempt. >> >> Fix the program, Run it. If you don't get the desired results think >> about why, then either continue fixing or post a new program with a >> new question. >> >> Did you think about all the questions I asked. I did not see any >> answers. I repeat them here. Please answer. >> >> * Why did you use a class? You don't need it, and it complicates >> things. >> * Why put some of the code in the mainline of the class and some in >> __init__. I see no need for that separation. >> * Since you use print statements to monitor progress how about >> addind something so you know which print statement was called. >> Perhaps print "I am here 1", print "I am here 2", etc. >> * Why have the file at all? Why not just start with c = range(1,1000)? >> * Why print the entire list? (print c)? >> >> -- >> Bob Gailer >> 919-636-4239 >> Chapel Hill NC > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From nozarm at triumf.ca Wed Oct 19 19:53:25 2011 From: nozarm at triumf.ca (Mina Nozar) Date: Wed, 19 Oct 2011 10:53:25 -0700 Subject: [Tutor] regex and parsing through a semi-csv file In-Reply-To: References: <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C9DF0.8040805@triumf.ca> Message-ID: <4E9F0E95.6080709@triumf.ca> Hello Wayne, Thank you for your help and sorry for the delay in the response. I was caught up with other simulation jobs and didn't get around to testing what you suggested until yesterday. On 11-10-05 01:24 PM, Wayne Werner wrote: > On Wed, Oct 5, 2011 at 1:12 PM, Mina Nozar > wrote: > I just glanced through your email, but my initial thought would be to just use regex to collect the entire segment > that you're looking for, and then string methods to split it up: > > pat = re.compile('({name},{number}.*?)[A-Z]{{1,2}}'.format(name='AC', number='225'), re.DOTALL) > > raw_data = re.search(pat, f.read()) > if raw_data is None: > # we didn't find the isotope, so take appropriate actions, quit or tell the user > else: > raw_data = raw_data.string.strip().split('\n') > > Then it depends on how you want to process your data, but you could easily use list comprehensions/generator expressions. > > The most terse syntax I know of: > > data = [[float(x) for x in d.split(',')] for d in raw_data if d[0].isdigit()] > > data will then contain a list of 3-element lists of floating point values. > If you want to "rotate" the list, you can do data = list(zip(*data)). To illustrate: > >>> d = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']] > >>> d = list(zip(*d)) > >>> d > [('a', 'a', 'a', 'a'), ('b', 'b', 'b', 'b'), ('c', 'c', 'c', 'c')] > HTH, > Wayne I tried what you suggested above, but it doesn't work. The search doesn't start at the right place (info. following an isotope choice input by the user and doesn't stop at the info. for the particular isotope. So basically it seems like data gets filled in with the data for all isotopes in a given file. I made a small test file to verify this. Can you please explain what the statement assigned to pat actually does? At the end, I should be getting three lists, one containing the times (column 1), one containing the activities (column 2), and one containing the error in activities (column 3) for a specific isotope requested. Thank you and best wishes, Mina Here is what I tried: #! /usr/bin/env python import re import argparse parser = argparse.ArgumentParser(description='Plot activities for a given isotope') parser.add_argument('-f', action="store", dest="fname", help='The csv file name containing ctivites') parser.add_argument('-i', action="store", dest="isotope", help='Isotope to plot activities for, eg. U-238') args=parser.parse_args() print 'file name:', args.fname print 'isotope:', args.isotope isotope_name,isotope_A = args.isotope.split('-') print isotope_name, isotope_A f = open(args.fname, 'r') pat = re.compile('({name},{number}.*?)[A-Z]{{1,2}}'.format(name=isotope_name, number=isotope_A), re.DOTALL) result = re.search(pat, f.read()) print result.string f.close() if result is None: exit(args.fname+' does not contain info on '+args.isotope) else: result = result.string.strip().split('\n') data = [[float(x) for x in d.split(',')] for d in result if d[0].isdigit()] data = list(zip(*data)) for i in range(0, len(data)): print data[i] Input file: test.csv # element, z, isotope, activity_time, activity, error AC,225,89 3.6000e+03,1.6625e-07,2.4555e-09 8.6400e+04,0.0000e+00,-1.1455e-23 2.5920e+05,3.1615e-07,4.6695e-09 8.6400e+05,3.6457e-05,5.3847e-07 1.8000e+06,5.5137e-04,8.1437e-06 AG,111,47 3.6000e+03,1.7936e+07,3.1191e+05 8.6400e+04,7.9538e+08,1.3800e+07 2.5920e+05,2.2201e+09,3.8519e+07 8.6400e+05,5.5546e+09,9.6372e+07 1.8000e+06,7.8612e+09,1.3639e+08 AG,112,47 3.6000e+03,2.7591e+07,4.9498e+05 8.6400e+04,3.8637e+09,6.9315e+07 2.5920e+05,7.3492e+09,1.3184e+08 8.6400e+05,8.2493e+09,1.4799e+08 1.8000e+06,8.2528e+09,1.4806e+08 and here is what I get when I run the code: python ActivityPlots.py -f test.csv -i AG-111 file name: test.csv isotope: AG-111 AG 111 # element, z, isotope, activity_time, activity, error AC,225,89 3.6000e+03,1.6625e-07,2.4555e-09 8.6400e+04,0.0000e+00,-1.1455e-23 2.5920e+05,3.1615e-07,4.6695e-09 8.6400e+05,3.6457e-05,5.3847e-07 1.8000e+06,5.5137e-04,8.1437e-06 AG,111,47 3.6000e+03,1.7936e+07,3.1191e+05 8.6400e+04,7.9538e+08,1.3800e+07 2.5920e+05,2.2201e+09,3.8519e+07 8.6400e+05,5.5546e+09,9.6372e+07 1.8000e+06,7.8612e+09,1.3639e+08 AG,112,47 3.6000e+03,2.7591e+07,4.9498e+05 8.6400e+04,3.8637e+09,6.9315e+07 2.5920e+05,7.3492e+09,1.3184e+08 8.6400e+05,8.2493e+09,1.4799e+08 1.8000e+06,8.2528e+09,1.4806e+08 (3600.0, 86400.0, 259200.0, 864000.0, 1800000.0, 3600.0, 86400.0, 259200.0, 864000.0, 1800000.0, 3600.0, 86400.0, 259200.0, 864000.0, 1800000.0) (1.6625e-07, 0.0, 3.1615e-07, 3.6457e-05, 0.00055137, 17936000.0, 795380000.0, 2220100000.0, 5554600000.0, 7861200000.0, 27591000.0, 3863700000.0, 7349200000.0, 8249300000.0, 8252800000.0) (2.4555e-09, -1.1455e-23, 4.6695e-09, 5.3847e-07, 8.1437e-06, 311910.0, 13800000.0, 38519000.0, 96372000.0, 136390000.0, 494980.0, 69315000.0, 131840000.0, 147990000.0, 148060000.0) From marc.tompkins at gmail.com Wed Oct 19 21:06:00 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 19 Oct 2011 12:06:00 -0700 Subject: [Tutor] regex and parsing through a semi-csv file In-Reply-To: <4E8C9DF0.8040805@triumf.ca> References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C9DF0.8040805@triumf.ca> Message-ID: On Wed, Oct 5, 2011 at 11:12 AM, Mina Nozar wrote: > Now, I would like to parse through this code and fill out 3 lists: 1) > activity_time, 2) activity, 3) error, and plot the activities as a function > of time using matplotlip. My question specifically is on how to parse > through the lines containing the data (activity time, activity, error) for a > given isotope, stopping before reaching the next isotope's info. Regular expressions certainly are terse, but (IMHO) they're really, really hard to debug and maintain; I find I have to get myself into a Zen state to even unpack them, and that just doesn't feel very Pythonic. Here's an approach I've used in similar situations (a file with arbitrary sequences of differently-formatted lines, where one line determines the "type" of the lines that follow): - create a couple of status variables: currentElement, currentIsotope - read each line and split it into a list, separating on the commas - look at the first item on the line: is it an element? (You could use a list of the 120 symbols, or you could just check to see if it's alphabetic...) - if the first item is an element, then set currentElement and currentIsotope, move on to next line. - if the first item is NOT an element, then this is a data line. - if currentElement and currentIsotope match what the user asked for, - add time, activity, and error to the appropriate lists - if not, move on. This approach also works in the event that the data wasn't all collected in order - i.e. there might be data for Ag111 followed by U235 followed by Ag111 again. Note that the size of the lists will change depending on the number of > activities for a given run of the simulation so I don't want to hard code > '13' as the number of lines to read in followed by the line containing > isotope_name, etc. > This should work for any number of lines or size of file, as long as the data lines are all formatted as you expect. Obviously a bit of error-trapping would be a good thing.... If there is a more graceful way of doing this, please let me know as well. > I am new to python... > > For me, readability and maintainability trump "grace" every time. Nobody's handing out awards for elegance (outside of the classroom), but complexity gets punished (with bugs and wasted time.) More elegant solutions might also run faster, but remember that premature optimization is a Bad Thing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Wed Oct 19 21:08:44 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 19 Oct 2011 12:08:44 -0700 Subject: [Tutor] regex and parsing through a semi-csv file In-Reply-To: References: <4E848401.8060504@davea.name> <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C9DF0.8040805@triumf.ca> Message-ID: On Wed, Oct 19, 2011 at 12:06 PM, Marc Tompkins wrote: > This approach also works in the event that the data wasn't all collected in > order - i.e. there might be data for Ag111 followed by U235 followed by > Ag111 again. > > Ahem... Of course, I meant "Ag47 followed by U235 followed by Ag47 again"... (hides face in shame...) -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Wed Oct 19 21:19:31 2011 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 19 Oct 2011 15:19:31 -0400 Subject: [Tutor] logging question Message-ID: Hi all, I have never done logging before, and I am wondering how it will change my script. Currently, I have something like this: for book in results: try: checkForErrors(book) except Exception, e: print e continue That way I see any errors in a given book, but that book is skipped and the loop continues. Now, though, checkForErrors() logs exceptions instead of raising them, so my try/except won't work, right? There is my question: if a method logs an exception instead of raising it, is that exception still raised by the logging module? Do I have to make checkForErrors() return something, and check for that, instead of using try/except or can I keep my loop how it is? TIA! -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From waynejwerner at gmail.com Wed Oct 19 21:37:40 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 19 Oct 2011 14:37:40 -0500 Subject: [Tutor] tkinter binding issues In-Reply-To: References: Message-ID: On Wed, Oct 19, 2011 at 9:05 AM, Elwin Estle wrote: > So, here is the first 'bug'. In all three of the callback > functions, I added an extra dummy parameter because I kept getting an error > message about the callback wanting two parameters, even though I do not pass > any parameters and don't really need to. The dummy parameter does nothing > and isn't referenced in the function code. But without it, why do I get the > error message? > Tkinter passes the event to your callback, so you can get information such as the keypress and mouse location. If you don't need the event, you can simply wrap the function call in a lambda function,, sort of the inverse of what you do when you want to pass a parameter on a button click: bind("", lambda x: callback()) > The second bug has to do with the routine starting on line 385, which > resets all the widgets in the input form to their starting values. If just > click inside the three entry widgets, without inputting any data, the > backgrounds turn red, as they should. However, when I click the clear form > button, which calls the function on line 385, it doesn't always reset these > entry boxes back to their original state. It only will do so if the cursor > is in the "clock number" entry box. If it is in one of the other two boxes, > it will clear all the boxes but that one. > If I comment out the first line of the reset form function (the one that > sets focus back to the clock number entry widget, then all three are > cleared, but the cursor isn't where I want it to be. I get the idea that > when focus shifts from whatever box the cursor is in, to the 'yes' button in > the tkmessagebox, that it triggers my validation callback and turns the > background red, but shouldn't my clear form function still clear it out? > That's because of the way the events are handled in Tkinter. I believe it's because when you call self.reset_form(), it actually fires that before the event fires, so it goes through that whole reset process, returns focus to your other box and *then* the event. I'd have to throw some print's in to make sure, but I suspect that's the issue. I was able to get around it by simply changing the call to : self.after(10, self.reset_form) self.focus_set() I tried using update_idletasks, but I couldn't get any combination of that working. I suspect that this method works because the after command tells it to wait for at least 10ms, and in that time the event can be called. Alternatively, you could remove focus from the Entry widget before you call the messagebox. If you wanted to get fancy, you could use to keep track of which widget has the focus and return to that widget if the user clicks "No" on the confirmation dialog. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Thu Oct 20 00:57:55 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Wed, 19 Oct 2011 18:57:55 -0400 Subject: [Tutor] Socket not connecting In-Reply-To: References: Message-ID: > > (I might try increasing the listen value to say 3 or 5 but it shouldn't > really be necessary) What exactly is the listen value (by the way, I'm jake's friend he was talking about.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Oct 20 02:06:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Oct 2011 01:06:58 +0100 Subject: [Tutor] Socket not connecting In-Reply-To: References: Message-ID: On 19/10/11 23:57, Christopher King wrote: > (I might try increasing the listen value to say 3 or 5 but it > shouldn't really be necessary) > > What exactly is the listen value (by the way, I'm jake's friend he was > talking about.) It's essentially the number of messages in the queue. If you only use 1 and some spurious rubbish arrives then you won't get any of the real data... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Thu Oct 20 14:39:09 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 20 Oct 2011 05:39:09 -0700 (PDT) Subject: [Tutor] logging question In-Reply-To: References: Message-ID: <1319114349.37560.YahooMailNeo@web110704.mail.gq1.yahoo.com> Maybe something like this? I don't know what data type 'book' is, and what Exception would be raised in case someting goes wrong.import logging logging.basicConfig(filename='example.log',level=logging.ERROR) for book in results: ? try: ??? result = process(book) ??? logging.info('Everything fine with this book') ? except SomeException: ??? logging.error('Something wrong with this book') ? ? logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too') Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >________________________________ >From: Alex Hall >To: tutor >Sent: Wednesday, October 19, 2011 9:19 PM >Subject: [Tutor] logging question > >Hi all, >I have never done logging before, and I am wondering how it will >change my script. Currently, I have something like this: >for book in results: >try: checkForErrors(book) >except Exception, e: >? print e >? continue > >That way I see any errors in a given book, but that book is skipped >and the loop continues. Now, though, checkForErrors() logs exceptions >instead of raising them, so my try/except won't work, right? There is >my question: if a method logs an exception instead of raising it, is >that exception still raised by the logging module? Do I have to make >checkForErrors() return something, and check for that, instead of >using try/except or can I keep my loop how it is? TIA! > >-- >Have a great day, >Alex (msg sent from GMail website) >mehgcap at gmail.com; http://www.facebook.com/mehgcap >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Oct 20 14:52:45 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 20 Oct 2011 14:52:45 +0200 Subject: [Tutor] logging question In-Reply-To: References: Message-ID: <4EA0199D.5030604@compuscan.co.za> On 2011/10/19 09:19 PM, Alex Hall wrote: > Hi all, > I have never done logging before, and I am wondering how it will > change my script. Currently, I have something like this: > for book in results: > try: checkForErrors(book) > except Exception, e: > print e > continue > > That way I see any errors in a given book, but that book is skipped > and the loop continues. Now, though, checkForErrors() logs exceptions > instead of raising them, so my try/except won't work, right? There is > my question: if a method logs an exception instead of raising it, is > that exception still raised by the logging module? Do I have to make > checkForErrors() return something, and check for that, instead of > using try/except or can I keep my loop how it is? TIA! > If you have some exception handling and want it to propagate further up the chain you can just raise it, for eg. def checkForErrors(book): try: do_something_that_could_raise_exceptions() except Exception, e: log_errors(e) raise for book in results: try: checkForErrors(book) except Exception, e: do_your_other_exception_handling() -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Thu Oct 20 15:27:03 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 20 Oct 2011 09:27:03 -0400 Subject: [Tutor] logging question In-Reply-To: <4EA0199D.5030604@compuscan.co.za> References: <4EA0199D.5030604@compuscan.co.za> Message-ID: Thanks, raise should do it. I read later on last night that raise called with nothing else re-raises the last exception, but never thought of using it in my situation. On 10/20/11, Christian Witts wrote: > On 2011/10/19 09:19 PM, Alex Hall wrote: >> Hi all, >> I have never done logging before, and I am wondering how it will >> change my script. Currently, I have something like this: >> for book in results: >> try: checkForErrors(book) >> except Exception, e: >> print e >> continue >> >> That way I see any errors in a given book, but that book is skipped >> and the loop continues. Now, though, checkForErrors() logs exceptions >> instead of raising them, so my try/except won't work, right? There is >> my question: if a method logs an exception instead of raising it, is >> that exception still raised by the logging module? Do I have to make >> checkForErrors() return something, and check for that, instead of >> using try/except or can I keep my loop how it is? TIA! >> > > If you have some exception handling and want it to propagate further up > the chain you can just raise it, for eg. > > def checkForErrors(book): > try: > do_something_that_could_raise_exceptions() > except Exception, e: > log_errors(e) > raise > > for book in results: > try: > checkForErrors(book) > except Exception, e: > do_your_other_exception_handling() > > -- > > Christian Witts > Python Developer > > // > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From ramit.prasad at jpmorgan.com Thu Oct 20 18:20:48 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 20 Oct 2011 12:20:48 -0400 Subject: [Tutor] close failed in file object destructor: In-Reply-To: <4E9F0E91.7040400@gmail.com> References: <4E9DBDBE.30503@gmail.com> <4E9DBE96.2000700@gmail.com> <4E9DE75B.3040801@gmail.com> <4E9EF1C6.7020209@gmail.com> <4E9F0350.3080802@gmail.com> <4E9F0497.7080103@gmail.com> <4E9F0E91.7040400@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F219922F1@EMARC112VS01.exchad.jpmchase.net> >Thanks for your reply. Please always reply-all so a copy goes to the list, I will second this, if you do not reply all then you can only one person helping you. If you keep replying all, then any of us can jump in with our comments or suggestions. It is for your benefit, not ours ;) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From c2praveen30jun at gmail.com Fri Oct 21 15:00:08 2011 From: c2praveen30jun at gmail.com (Praveen Singh) Date: Fri, 21 Oct 2011 09:00:08 -0400 Subject: [Tutor] functions and default argument Message-ID: In function- "Default value is *evaluated only once*.This makes different when the default is a mutable object such as a list, dictionary or instance of most classes." I am not getting it properly-evaluated once?? different behaviour???-- please explain this. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Fri Oct 21 15:19:39 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 21 Oct 2011 15:19:39 +0200 Subject: [Tutor] functions and default argument In-Reply-To: References: Message-ID: <4EA1716B.5060904@compuscan.co.za> On 2011/10/21 03:00 PM, Praveen Singh wrote: > In function- > > "Default value is *evaluated only once*.This makes different when the > default is a mutable object such as a list, dictionary or instance of > most classes." > > I am not getting it properly-evaluated once?? different behaviour???-- > please explain this. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Mutable defaults for function/method arguments is a Python Gotcha, you can find a good read here [1]. It's a better read than how I would explain it. [1] http://www.ferg.org/projects/python_gotchas.html#contents_item_6 -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From crusier at gmail.com Fri Oct 21 18:37:40 2011 From: crusier at gmail.com (Crusier) Date: Fri, 21 Oct 2011 09:37:40 -0700 Subject: [Tutor] Web Praser Message-ID: Hi, I am new to programming. I want to know what I should look at if I want to learn more about Web Praser. I know there is something called Beautiful Soup but I think it is kind of difficult for me at this stage. Thank you Regards, Crusier From steve at pearwood.info Fri Oct 21 19:25:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Oct 2011 04:25:51 +1100 Subject: [Tutor] functions and default argument In-Reply-To: References: Message-ID: <4EA1AB1F.4090204@pearwood.info> Praveen Singh wrote: > In function- > > "Default value is *evaluated only once*.This makes different when the > default is a mutable object such as a list, dictionary or instance of most > classes." > > I am not getting it properly-evaluated once?? different behaviour???-- > please explain this. Look at an example: >>> import time >>> def test(t=time.asctime()): ... print t, "***", time.asctime() ... >>> time.sleep(30) # wait a little bit >>> test() Sat Oct 22 04:17:08 2011 *** Sat Oct 22 04:17:57 2011 >>> time.sleep(30) # wait a little bit longer >>> test() Sat Oct 22 04:17:08 2011 *** Sat Oct 22 04:18:46 2011 Notice that the first time printed, using the default value, is the same. The default value for t is assigned once, and not calculated again. Since t is a string, it is immutable and can never change. The same thing occurs when you use a mutable object like a list or a dict. The default value is assigned once, and once only. But notice that you can modify the default value, say by appending to it: >>> def test(x=[]): ... print x, id(x) ... x.append(1) ... >>> test() [] 3085600236L >>> test() [1] 3085600236L >>> test() [1, 1] 3085600236L It is the same default list every time, but the *contents* of the list are changing. -- Steven From steve at pearwood.info Fri Oct 21 19:51:41 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Oct 2011 04:51:41 +1100 Subject: [Tutor] Web Praser In-Reply-To: References: Message-ID: <4EA1B12D.5010502@pearwood.info> Crusier wrote: > Hi, > > I am new to programming. I want to know what I should look at if I > want to learn more about Web Praser. I know there is something called > Beautiful Soup but I think it is kind of difficult for me at this > stage. What do you mean by "web parser"? The web (world wide web) is a network on the internet, you can't parse it. Do you mean a parser for HTML files? If you want to learn about parsing, then you should start with something simpler than HTML. If you want to learn about HTML, start with a good book or tutorial about HTML. There are dozens of them. Before we can advise you properly, you need to explain what it is you actually want to do. -- Steven From ramit.prasad at jpmorgan.com Fri Oct 21 21:40:39 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 21 Oct 2011 15:40:39 -0400 Subject: [Tutor] functions and default argument In-Reply-To: <4EA1AB1F.4090204@pearwood.info> References: <4EA1AB1F.4090204@pearwood.info> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB4441@EMARC112VS01.exchad.jpmchase.net> >The same thing occurs when you use a mutable object like a list or a >dict. The default value is assigned once, and once only. But notice that >you can modify the default value, say by appending to it: Not sure this will work exactly the same way in other IDEs, but in mine: >>> a = [] >>> def foo(x=a): ... x.append(1) ... >>> a.append( 2 ) >>> foo() >>> print a [2, 1] >>> help(foo) Help on function foo in module __pieshell__: foo(x=[2, 1]) >>> foo() >>> help(foo) Help on function foo in module __pieshell__: foo(x=[2, 1, 1]) >>> a.append( 3 ) >>> help(foo) Help on function foo in module __pieshell__: foo(x=[2, 1, 1, 3]) >>> b = [] >>> foo(b) >>> b [1] Notice how it is always bound to the list a, but can be "overridden". I know this has been discussed on this list or the main list before if you take a look through the archives. Sorry I can't remember what the thread would be like or when it was :( http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From fomcl at yahoo.com Fri Oct 21 22:40:50 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 21 Oct 2011 13:40:50 -0700 (PDT) Subject: [Tutor] functions and default argument In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB4441@EMARC112VS01.exchad.jpmchase.net> References: <4EA1AB1F.4090204@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB4441@EMARC112VS01.exchad.jpmchase.net> Message-ID: <1319229650.31516.YahooMailNeo@web110708.mail.gq1.yahoo.com> Interesting thread and webpages. Insightful, but is this really used as a technique in daily practice? It feels a bit like a hack to me. Like the author of one of the websites said: rule #1 don't mess with this. ? Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >________________________________ >From: "Prasad, Ramit" >To: "tutor at python.org" >Sent: Friday, October 21, 2011 9:40 PM >Subject: Re: [Tutor] functions and default argument > >>The same thing occurs when you use a mutable object like a list or a >>dict. The default value is assigned once, and once only. But notice that >>you can modify the default value, say by appending to it: > >Not sure this will work exactly the same way in other IDEs, but in mine: > >>>> a = [] >>>> def foo(x=a): >...? ? x.append(1) >...? ? >>>> a.append( 2 ) >>>> foo() >>>> print a >[2, 1] >>>> help(foo) >Help on function foo in module __pieshell__: > >foo(x=[2, 1]) > >>>> foo() >>>> help(foo) >Help on function foo in module __pieshell__: > >foo(x=[2, 1, 1]) > >>>> a.append( 3 ) >>>> help(foo) >Help on function foo in module __pieshell__: > >foo(x=[2, 1, 1, 3]) >>>> b = [] >>>> foo(b) >>>> b >[1] > > >Notice how it is always bound to the list a, but can be "overridden". > >I know this has been discussed on this list or the main list before if you take a look through the archives. >Sorry I can't remember what the thread would be like or when it was :( >http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument > > >Ramit > > >Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology >712 Main Street | Houston, TX 77002 >work phone: 713 - 216 - 5423 > > > > >This email is confidential and subject to important disclaimers and >conditions including on offers for the purchase or sale of >securities, accuracy and completeness of information, viruses, >confidentiality, legal privilege, and legal entity disclaimers, >available at http://www.jpmorgan.com/pages/disclosures/email.? >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Oct 21 23:23:51 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 21 Oct 2011 17:23:51 -0400 Subject: [Tutor] functions and default argument In-Reply-To: <1319229650.31516.YahooMailNeo@web110708.mail.gq1.yahoo.com> References: <4EA1AB1F.4090204@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB4441@EMARC112VS01.exchad.jpmchase.net> <1319229650.31516.YahooMailNeo@web110708.mail.gq1.yahoo.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB466B@EMARC112VS01.exchad.jpmchase.net> >Interesting thread and webpages. Insightful, but is this really used as a technique in daily practice? It feels a bit like a hack to me. Like the author of one of the websites said: rule #1 don't mess with this. I think the problem with rule #1 is that this can occur when you do *not* understand what is going on. The behavior can be non-intuitive for programmers coming from other (more statically-typed) languages and figuring out the programming error can be difficult depending on the complexity/design of the function or program. As for daily usage, well that depends on each person's needs; I do not need to write to files daily either, but I suspect most people would consider my Python knowledge lacking if I did not ;). I suspect you are right and it is not used on a daily basis by the majority of Python users/developers. In my opinion, knowledge > ignorance. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From mehgcap at gmail.com Fri Oct 21 23:46:07 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 Oct 2011 17:46:07 -0400 Subject: [Tutor] difference between super() and parent.__init__()? Message-ID: Hi all, I am just curious: I have seen classes that are subclasses initialize their parents through both super and parentClass.__init__. What is the difference, if any, and is one "better" or "more pythonic" than the other? -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From alan.gauld at btinternet.com Sat Oct 22 02:32:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Oct 2011 01:32:27 +0100 Subject: [Tutor] functions and default argument In-Reply-To: <1319229650.31516.YahooMailNeo@web110708.mail.gq1.yahoo.com> References: <4EA1AB1F.4090204@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB4441@EMARC112VS01.exchad.jpmchase.net> <1319229650.31516.YahooMailNeo@web110708.mail.gq1.yahoo.com> Message-ID: On 21/10/11 21:40, Albert-Jan Roskam wrote: > Interesting thread and webpages. Insightful, but is this really used as > a technique in daily practice? Yes, one example is where you use it for a counter to determine how often a function gets called: def reserveScarceResource(p1,p2,count = [0]): : count is mutable count[0] += 1 if count[0] > 100: raise UsedTooManyException # allocate resources Its not really a hack, it's an implementation feature and it's a fair impression of a closure in languages like Lisp, which makes it useful for certain classes of problem. It can also be useful in state machines where you want to carry through a state value across transitions but don't need to retain it after the state sequence completes. You don't need it often but its nice to have when you do! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Oct 22 02:29:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Oct 2011 11:29:56 +1100 Subject: [Tutor] difference between super() and parent.__init__()? In-Reply-To: References: Message-ID: <4EA20E84.8080204@pearwood.info> Alex Hall wrote: > Hi all, > I am just curious: I have seen classes that are subclasses initialize > their parents through both super and parentClass.__init__. What is the > difference, if any, and is one "better" or "more pythonic" than the > other? A simple question with a complicated answer... First off, the answer depends on whether you are using so-called "classic classes" or "new-style classes". If you are using Python 3, there are only new-style classes: classic classes are gone. But in Python 2, classic classes are written like this: class MyClass: # Don't inherit from anything. pass while new-style classes inherit from either object or some other built-in type which inherits from object: class MyClass(object): # Inherit from object, new-style class. pass class MyInt(int): pass class MyStr(str): pass class MyList(list): pass # etc. super *does not work* for classic classes, end of story. So in the following discussion, I'm only talking about new-style classes, the only sort of class in Python 3. Secondly, let's talk about the difference between simple, single inheritance and multiple inheritance. Single inheritance is when each class inherits from exactly one parent, or superclass: class A(object): pass class B(A): pass class C(B): pass gives an inheritance hierarchy (a family tree, if you like): object | A | B | C In the case of single inheritance, super doesn't do anything special. It is the recommended way to handle inheritance: you are encouraged to write something like this: class C(B): def method(self, arg): x = super().method(arg) # Only works in Python 3 # or in Python 2, use super(C, self).method(arg) instead of x = B.method(arg), but functionality-wise, there is no difference between the two. In Python 3, super becomes a little more convenient, but it doesn't really matter much which you use. (But keep reading, for a reason why you *should* use super even in single inheritance.) The situation is more complicated once you have multiple inheritance. In multiple inheritance, at least one of the classes involved inherits from two or more superclasses. Here's a particularly simple example: class A(object): pass class B(A): pass class C(A): pass class D(B, C): pass # multiple superclasses or: object | A / \ B C \ / D In full generality, multiple inheritance can be so complex that most programming languages prohibit it, or put severe restrictions on it. Python is one of the very few that support it with very few restrictions. The difficulty occurs when you override a method in D. Now you need to ensure that each superclass (B and C) gets a shot at having their method called too. Here is a simple example showing how NOT to do it: class A(object): def save(self): print("class A saves") class B(A): def save(self): print("B saves stuff") A.save(self) # call the parent class method too class C(A): def save(self): print("C saves stuff") A.save(self) class D(B, C): def save(self): print ("D saves stuff") # make sure you let both B and C save too B.save(self) C.save(self) Simple, obvious... but wrong. Try it and see: >>> d = D() >>> d.save() D saves stuff B saves stuff class A saves C saves stuff class A saves The problem is that the A.save method gets called twice. In general, it is very hard to solve this problem by hand, especially if you have a complex family tree. You have to manage the entire family tree, keeping track of which superclasses you have already called, and avoid calling them a second time. That's fiddly and annoying and hard to do right. But super can do it for you. Here's a version that works correctly: class A(object): def save(self): print("class A saves") class B(A): def save(self): print("B saves stuff") super(B, self).save() # In Python 3, you can abbreviate this as super().save() class C(A): def save(self): print("C saves stuff") super(C, self).save() class D(B, C): def save(self): print ("D saves stuff") super(D, self).save() and in use: >>> d = D() >>> d.save() D saves stuff B saves stuff C saves stuff class A saves Now each class gets called exactly once, and in the right order. All the smarts managing the entire inheritance hierarchy is built into super, so each method gets called once and exactly once, provided that every class *only* uses super. If you try to mix super calls and direct method calls like B.method(self, arg), it probably won't work correctly, and if it does, it will probably be by accident. So please use super, even in single inheritance. Otherwise you are restricting the usefulness of your class: it can never be used with multiple inheritance. The one exception to this is if your class changes the method signature. E.g. if A.method takes no arguments, but B.method requires an argument. super cannot help you now. But changing the signature of methods is almost always the wrong thing to do: it is a violation of good object oriented design, and should be avoided. The main time it is justified is in the class constructor methods, __new__ or __init__, in which case you may need to avoid super and *carefully* manage the inheritance by hand. -- Steven From alan.gauld at btinternet.com Sat Oct 22 02:35:32 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Oct 2011 01:35:32 +0100 Subject: [Tutor] Web Praser In-Reply-To: References: Message-ID: On 21/10/11 17:37, Crusier wrote: > want to learn more about Web Praser. I know there is something called > Beautiful Soup but I think it is kind of difficult for me at this > stage. One of the objectives of Beautiful Soup is to make parsing fairly easy. Its certainly easier than most of the other HTML parsers out there! But parsing is not a trivial task regardless of the tool you use, especially something like HTML (which is what the web is made up of!) which is loosely defined and even more loosely implemented/used. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Oct 22 02:43:10 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Oct 2011 11:43:10 +1100 Subject: [Tutor] functions and default argument In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB466B@EMARC112VS01.exchad.jpmchase.net> References: <4EA1AB1F.4090204@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB4441@EMARC112VS01.exchad.jpmchase.net> <1319229650.31516.YahooMailNeo@web110708.mail.gq1.yahoo.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB466B@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4EA2119E.5040003@pearwood.info> Prasad, Ramit wrote: >> Interesting thread and webpages. Insightful, but is this really >> used as a technique in daily practice? It feels a bit like a hack >> to me. Like the author of one of the websites said: rule #1 don't >> mess with this. > > I think the problem with rule #1 is that this can occur when you do > *not* understand what is going on. The behavior can be non-intuitive > for programmers coming from other (more statically-typed) languages > and figuring out the programming error can be difficult depending on > the complexity/design of the function or program. It actually has nothing to do with whether the language is statically typed or dynamically typed. It has everything to do with whether default arguments are early bound or late bound. That is, given the function definition: def func(arg=something): pass does the default argument `something` get created once (early binding, occurs one time only when the function is defined) or multiple times (late binding, each time the function is called)? In my experience, most people aren't even aware that there are two potential behaviours until they implicitly assume the one their language doesn't support. -- Steven From mehgcap at gmail.com Sat Oct 22 02:51:36 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 Oct 2011 20:51:36 -0400 Subject: [Tutor] difference between super() and parent.__init__()? In-Reply-To: <4EA20E84.8080204@pearwood.info> References: <4EA20E84.8080204@pearwood.info> Message-ID: On 10/21/11, Steven D'Aprano wrote: > Alex Hall wrote: >> Hi all, >> I am just curious: I have seen classes that are subclasses initialize >> their parents through both super and parentClass.__init__. What is the >> difference, if any, and is one "better" or "more pythonic" than the >> other? > > > A simple question with a complicated answer... > > > First off, the answer depends on whether you are using so-called > "classic classes" or "new-style classes". I always use new-style (python2.7). > > If you are using Python 3, there are only new-style classes: classic > classes are gone. But in Python 2, classic classes are written like this: > > class MyClass: # Don't inherit from anything. > pass > > > while new-style classes inherit from either object or some other > built-in type which inherits from object: > > class MyClass(object): # Inherit from object, new-style class. > pass > class MyInt(int): pass > class MyStr(str): pass > class MyList(list): pass > # etc. > > > super *does not work* for classic classes, end of story. So in the > following discussion, I'm only talking about new-style classes, the only > sort of class in Python 3. > > Secondly, let's talk about the difference between simple, single > inheritance and multiple inheritance. Single inheritance is when each > class inherits from exactly one parent, or superclass: > > class A(object): pass > class B(A): pass > class C(B): pass > > gives an inheritance hierarchy (a family tree, if you like): > > object > | > A > | > B > | > C > > > In the case of single inheritance, super doesn't do anything special. It > is the recommended way to handle inheritance: you are encouraged to > write something like this: > > class C(B): > def method(self, arg): > x = super().method(arg) # Only works in Python 3 > # or in Python 2, use super(C, self).method(arg) > > instead of x = B.method(arg), but functionality-wise, there is no > difference between the two. In Python 3, super becomes a little more > convenient, but it doesn't really matter much which you use. (But keep > reading, for a reason why you *should* use super even in single > inheritance.) > > The situation is more complicated once you have multiple inheritance. In > multiple inheritance, at least one of the classes involved inherits from > two or more superclasses. Here's a particularly simple example: > > class A(object): pass > class B(A): pass > class C(A): pass > class D(B, C): pass # multiple superclasses > > or: > > object > | > A > / \ > B C > \ / > D > > > In full generality, multiple inheritance can be so complex that most > programming languages prohibit it, or put severe restrictions on it. > Python is one of the very few that support it with very few restrictions. > > The difficulty occurs when you override a method in D. Now you need to > ensure that each superclass (B and C) gets a shot at having their method > called too. Here is a simple example showing how NOT to do it: > > class A(object): > def save(self): > print("class A saves") > > class B(A): > def save(self): > print("B saves stuff") > A.save(self) # call the parent class method too > > class C(A): > def save(self): > print("C saves stuff") > A.save(self) > > class D(B, C): > def save(self): > print ("D saves stuff") > # make sure you let both B and C save too > B.save(self) > C.save(self) > > > Simple, obvious... but wrong. Try it and see: > > >>> d = D() > >>> d.save() > D saves stuff > B saves stuff > class A saves > C saves stuff > class A saves > > The problem is that the A.save method gets called twice. > > In general, it is very hard to solve this problem by hand, especially if > you have a complex family tree. You have to manage the entire family > tree, keeping track of which superclasses you have already called, and > avoid calling them a second time. That's fiddly and annoying and hard to > do right. > > But super can do it for you. Here's a version that works correctly: > > class A(object): > def save(self): > print("class A saves") > > class B(A): > def save(self): > print("B saves stuff") > super(B, self).save() > # In Python 3, you can abbreviate this as super().save() > > class C(A): > def save(self): > print("C saves stuff") > super(C, self).save() > > class D(B, C): > def save(self): > print ("D saves stuff") > super(D, self).save() > > > and in use: > > >>> d = D() > >>> d.save() > D saves stuff > B saves stuff > C saves stuff > class A saves > > Now each class gets called exactly once, and in the right order. That all makes sense, and explains a lot. > > All the smarts managing the entire inheritance hierarchy is built into > super, so each method gets called once and exactly once, provided that > every class *only* uses super. If you try to mix super calls and direct > method calls like B.method(self, arg), it probably won't work correctly, > and if it does, it will probably be by accident. I'll keep it in mind; super() is to be *always* used, or never at all. > > So please use super, even in single inheritance. Otherwise you are > restricting the usefulness of your class: it can never be used with > multiple inheritance. > > The one exception to this is if your class changes the method signature. > E.g. if A.method takes no arguments, but B.method requires an argument. > super cannot help you now. But changing the signature of methods is > almost always the wrong thing to do: it is a violation of good object > oriented design, and should be avoided. The main time it is justified is > in the class constructor methods, __new__ or __init__, in which case you > may need to avoid super and *carefully* manage the inheritance by hand. I'm not sure about this part. Could I not simply do something like: class a(object): def m(self, p1): pass class b(a): def m(self, p1, p2, *args, **kwords): super(b, self).m(*args, **kwords) #different signatures, but a.m() still gets what it wants, if called correctly Also, what is the difference between __init__ (what I always use) and __new__? If you can change these, why not other methods? Of course these would be the most commonly changed, but the question stands. Thanks! > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Sat Oct 22 08:16:52 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Oct 2011 17:16:52 +1100 Subject: [Tutor] difference between super() and parent.__init__()? In-Reply-To: References: <4EA20E84.8080204@pearwood.info> Message-ID: <4EA25FD4.3010909@pearwood.info> Alex Hall wrote: > On 10/21/11, Steven D'Aprano wrote: [...] >> The one exception to this is if your class changes the method signature. >> E.g. if A.method takes no arguments, but B.method requires an argument. >> super cannot help you now. But changing the signature of methods is >> almost always the wrong thing to do: it is a violation of good object >> oriented design, and should be avoided. The main time it is justified is >> in the class constructor methods, __new__ or __init__, in which case you >> may need to avoid super and *carefully* manage the inheritance by hand. > I'm not sure about this part. Could I not simply do something like: > class a(object): > def m(self, p1): pass > > class b(a): > def m(self, p1, p2, *args, **kwords): > super(b, self).m(*args, **kwords) #different signatures, but a.m() > still gets what it wants, if called correctly No, that won't work. Consider what happens when you do this: instance = b() instance.m(1, 2, "spam", "ham", foo=None) The m method gets called with arguments: p1 = 1 p2 = 2 args = ("spam", "ham") kwords = {"foo": None} So far so good. But b.m calls a.m using: super(b, self).m(*args, **kwords) which drops p1=1 completely, replacing it with "spam". That surely is incorrect. It also tries to supply an extra two arguments, "ham" and foo=None, but a.m only takes one argument. > Also, what is the difference between __init__ (what I always use) and > __new__? If you can change these, why not other methods? Of course > these would be the most commonly changed, but the question stands. __new__ and __init__ are respectively the constructor and initialiser for the class. __new__ is responsible for actually creating the instance, and returning it. If the class is immutable, like int, str or tuple, this is the time to set the contents of the instance. (Once the instance is created, it's too late to change it.) Normally, you don't need to do anything with __new__, you can consider it a moderately specialised method. __init__ is responsible for initialising any extra attributes on the instance, or for mutable classes like lists or dicts, setting the contents. It's much more common to use __init__ rather than __new__. -- Steven From lina.lastname at gmail.com Sat Oct 22 18:09:01 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 23 Oct 2011 00:09:01 +0800 Subject: [Tutor] how to unique the string Message-ID: Hi, I googled for a while, but failed to find the perfect answer, for a string ['85CUR', '85CUR'] how can I unique it as: ['85CUR'] Thanks, From jeanpierreda at gmail.com Sat Oct 22 18:22:41 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 22 Oct 2011 12:22:41 -0400 Subject: [Tutor] how to unique the string In-Reply-To: References: Message-ID: You should be able to do this yourself, with the help of the following link: http://docs.python.org/library/stdtypes.html#set Is this a homework question? Devin On Sat, Oct 22, 2011 at 12:09 PM, lina wrote: > Hi, > > I googled for a while, but failed to find the perfect answer, > > for a string > > ['85CUR', '85CUR'] > > how can I unique it as: > > ['85CUR'] > > Thanks, > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From bgailer at gmail.com Sat Oct 22 18:25:34 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 22 Oct 2011 12:25:34 -0400 Subject: [Tutor] how to unique the string In-Reply-To: References: Message-ID: <4EA2EE7E.4000601@gmail.com> On 10/22/2011 12:09 PM, lina wrote: > Hi, > > I googled for a while, but failed to find the perfect answer, > > for a string > > ['85CUR', '85CUR'] > > how can I unique it as: > > ['85CUR'] Try set(['85CUR', '85CUR'] -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Sat Oct 22 18:50:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 23 Oct 2011 03:50:44 +1100 Subject: [Tutor] how to unique the string In-Reply-To: References: Message-ID: <4EA2F464.3000403@pearwood.info> lina wrote: > Hi, > > I googled for a while, but failed to find the perfect answer, > > for a string > > ['85CUR', '85CUR'] That's not a string, it is a list. > how can I unique it as: > > ['85CUR'] Your question is unclear. If you have this: ['85CUR', '99bcd', '85CUR', '85CUR'] what do you expect to get? # keep only the very first item ['85CUR'] # keep the first copy of each string, in order ['85CUR', '99bcd'] # keep the last copy of each string, in order ['99bcd', '85CUR'] # ignore duplicates only when next to each other ['85CUR', '99bcd', '85CUR'] Does the order of the result matter? If order matters, and you want to keep the first copy of each string: unique = [] for item in items: if item not in unique: unique.append(item) If order doesn't matter, then use this: unique = list(set(items)) -- Steven From lina.lastname at gmail.com Sat Oct 22 19:05:27 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 23 Oct 2011 01:05:27 +0800 Subject: [Tutor] how to unique the string In-Reply-To: References: Message-ID: On 23 Oct, 2011, at 0:22, Devin Jeanpierre wrote: > You should be able to do this yourself, with the help of the following link: > > http://docs.python.org/library/stdtypes.html#set Thanks. > > Is this a homework question? No. > > Devin > > On Sat, Oct 22, 2011 at 12:09 PM, lina wrote: >> Hi, >> >> I googled for a while, but failed to find the perfect answer, >> >> for a string >> >> ['85CUR', '85CUR'] >> >> how can I unique it as: >> >> ['85CUR'] >> >> Thanks, >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> From evosweet at hotmail.com Sat Oct 22 21:32:50 2011 From: evosweet at hotmail.com (Rayon) Date: Sat, 22 Oct 2011 15:32:50 -0400 Subject: [Tutor] python telnet Message-ID: From: Rayon [mailto:rayon at gtt.co.gy] Sent: 21 October 2011 18:53 To: 'tutor at python.org' Subject: python telnet Can I connect to a telnet session and return data without disconnecting the data session. Regards Rayon -------------- next part -------------- An HTML attachment was scrubbed... URL: From tktucker at gmail.com Sat Oct 22 21:48:34 2011 From: tktucker at gmail.com (Tom Tucker) Date: Sat, 22 Oct 2011 15:48:34 -0400 Subject: [Tutor] python telnet In-Reply-To: References: Message-ID: Take a look at pyexpect. I have used this mod to ssh into juniper firewalls, excute a command, save results and exit. Instead of exiting you can drop down to interactive mode. On Oct 22, 2011 3:40 PM, "Rayon" wrote: > ** ** > > ** ** > > ** ** > > *From:* Rayon [mailto:rayon at gtt.co.gy] > *Sent:* 21 October 2011 18:53 > *To:* 'tutor at python.org' > *Subject:* python telnet**** > > ** ** > > Can I connect to a telnet session and return data without disconnecting the > data session. **** > > ** ** > > Regards Rayon**** > > ** ** > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Oct 22 21:55:02 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 23 Oct 2011 06:55:02 +1100 Subject: [Tutor] python telnet In-Reply-To: References: Message-ID: <4EA31F96.909@pearwood.info> Rayon wrote: > Can I connect to a telnet session and return data without disconnecting the > data session. Isn't this the same question you asked back in June? We tried to answer your question then, did you see our responses, and were they useful? At the time, you were complaining that the telnet session was too slow, but you didn't tell us what you were actually doing. David Heiserca took a guess as to what you were doing, and suggested what you should do again. Did you see his response, and was it helpful? You should show us the code you are using. -- Steven From ckava1 at msn.com Sun Oct 23 00:10:19 2011 From: ckava1 at msn.com (Chris Kavanagh) Date: Sat, 22 Oct 2011 18:10:19 -0400 Subject: [Tutor] Simple Question On A Method (in subclass) Message-ID: Hello, First, thank you for providing this GREAT service, & THANKS to everyone who contributes. It's greatly appreciated. . .I'm new to Python (2.7, Win XP) & new to programming in general. I have been studying on my own for about a month now. I believe I have a good grasp of the basics. Secondly, I have several questions about this piece of code from 'A Byte Of Python' by Swaroop. Hope that's ok to use this code. I guess I could try to write a new ex. on my own, but, figured it would be too confusing. My question is regarding the tell methods in the subclasses,the code {SchoolMember.tell(self)}, in the class Teacher & Student. I just don't understand what this is doing? Calling the first method {def tell} from the parent class, I assume? There is already a print statement in each of the subclass {def tell} showing details, why call another print statement (from parent class {def tell})?? I know this should be simple, but I'm confused. LOL, obviously. Thank you in advance! class SchoolMember: '''Represents any school member.''' def __init__(self,name,age): self.name = name self.age = age print '(Initialized SchoolMember: %s)' %self.name def tell(self): '''Tell my details.''' print 'Name:"%s" Age:"%s"' % (self.name, self.age), class Teacher(SchoolMember): '''Represents a teacher''' def __init__(self,name,age,salary): SchoolMember.__init__(self,name,age) self.salary = salary print '(Initialized Teacher: %s)' %self.name def tell(self): SchoolMember.tell(self) print 'Salary: "%d"' % self.salary class Student(SchoolMember): '''Represents a student.''' def __init__(self,name,age,marks): SchoolMember.__init__(self,name,age) self.marks = marks print '(Initialized Student: %s)' %self.name def tell(self): SchoolMember.tell(self) print 'Marks: "%d"' % self.marks t = Teacher('Mrs. Shrividya',40,30000) s = Student('Swaroop',22,75) print ##prints a blank line members = [t,s] for member in members: OUTPUT $ python inherit.py (Initialized SchoolMember: Mrs. Shrividya) (Initialized Teacher: Mrs. Shrividya) (Initialized SchoolMember: Swaroop) (Initialized Student: Swaroop) Name:"Mrs. Shrividya" Age:"40" Salary: "30000" Name:"Swaroop" Age:"22" Marks: "75" From d at davea.name Sun Oct 23 00:59:45 2011 From: d at davea.name (Dave Angel) Date: Sat, 22 Oct 2011 18:59:45 -0400 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: Message-ID: <4EA34AE1.6000503@davea.name> On 10/22/2011 06:10 PM, Chris Kavanagh wrote: > Hello, First, thank you for providing this GREAT service, & THANKS to > everyone who contributes. It's greatly appreciated. . .I'm new to > Python (2.7, Win XP) & new to programming in general. I have been > studying on my own for about a month now. I believe I have a good > grasp of the basics. > > Secondly, I have several questions about this piece of code from 'A > Byte Of Python' by Swaroop. Hope that's ok to use this code. I guess I > could try to write a new ex. on my own, but, figured it would be too > confusing. > > My question is regarding the tell methods in the subclasses,the code > {SchoolMember.tell(self)}, in the class Teacher & Student. I just > don't understand what this is doing? Calling the first method {def > tell} from the parent class, I assume? There is already a print > statement in each of the subclass {def tell} showing details, why call > another print statement (from parent class {def tell})?? I know this > should be simple, but I'm confused. LOL, obviously. > > Thank you in advance! > > > class SchoolMember: > '''Represents any school member.''' > def __init__(self,name,age): > self.name = name > self.age = age > print '(Initialized SchoolMember: %s)' %self.name > > def tell(self): > '''Tell my details.''' > print 'Name:"%s" Age:"%s"' % (self.name, self.age), > > class Teacher(SchoolMember): > '''Represents a teacher''' > def __init__(self,name,age,salary): > SchoolMember.__init__(self,name,age) > self.salary = salary > print '(Initialized Teacher: %s)' %self.name > > def tell(self): > SchoolMember.tell(self) > print 'Salary: "%d"' % self.salary > > class Student(SchoolMember): > '''Represents a student.''' > def __init__(self,name,age,marks): > SchoolMember.__init__(self,name,age) > self.marks = marks > print '(Initialized Student: %s)' %self.name > > def tell(self): > SchoolMember.tell(self) > print 'Marks: "%d"' % self.marks > > t = Teacher('Mrs. Shrividya',40,30000) > s = Student('Swaroop',22,75) > > print ##prints a blank line > > members = [t,s] > for member in members: > > > > OUTPUT > > $ python inherit.py > (Initialized SchoolMember: Mrs. Shrividya) > (Initialized Teacher: Mrs. Shrividya) > (Initialized SchoolMember: Swaroop) > (Initialized Student: Swaroop) > > Name:"Mrs. Shrividya" Age:"40" Salary: "30000" > Name:"Swaroop" Age:"22" Marks: "75" Welcome to the python-tutor list. We are all volunteers here, and most, like me, ask questions as well as answering them. it's a two-way street. The whole point of subclassing is to share either code, data, or both. In this example, the amount of shared data is just the name and age, and the shared method is tell(). Because the parent knows how to 'tell' its information, the child doesn't need to. So instead of altering the prints in both the child classes to print name & age, you let the common code in the parent handle it. It becomes more clearly a win when you have much more data, or much more complex methods involved. But you have to start simple. BTW, there were some transcription errors in the email. For example, the code as written would be using a separate line for Salary on Mrs. Shrividya's record. And you're missing the content of the for member in members: loop. No problem, but it might have affected our discussion. Did you retype it all, or was it just a glitch? Presumably you know how to copy/paste from and to a console prompt? -- DaveA From alan.gauld at btinternet.com Sun Oct 23 01:24:36 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Oct 2011 00:24:36 +0100 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: Message-ID: On 22/10/11 23:10, Chris Kavanagh wrote: > My question is regarding the tell methods in the subclasses,the code > {SchoolMember.tell(self)}, in the class Teacher & Student. I just don't > understand what this is doing? Calling the first method {def tell} from > the parent class, I assume? Thats right, the child class is calling its parent class method. This saves the child class from copying the code in the parent. > There is already a print statement in each of the subclass {def tell} > showing details, why call another print statement In this case it doesn't same much code (a few charactrs less) but with a more complex method it couyld be a lot iof saving. However, that's not the only advantage. If you want to change the format of the parent message you only need to change the parent code, the children get the change for free. Also if you copied the code into each child there is a real risk that you'd get the formatting slightly different. Then when you try to call the tell() method of a list of objects, some parents and some children the outputs would look different - thats messy. > class SchoolMember: > def tell(self): > '''Tell my details.''' > print 'Name:"%s" Age:"%s"' % (self.name, self.age), > > class Teacher(SchoolMember): > def tell(self): > SchoolMember.tell(self) > print 'Salary: "%d"' % self.salary > > class Student(SchoolMember): > def tell(self): > SchoolMember.tell(self) > print 'Marks: "%d"' % self.marks > > t = Teacher('Mrs. Shrividya',40,30000) > s = Student('Swaroop',22,75) > > members = [t,s] > for member in members: member.tell() > Name:"Mrs. Shrividya" Age:"40" Salary: "30000" > Name:"Swaroop" Age:"22" Marks: "75" HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From evosweet at hotmail.com Sun Oct 23 02:13:04 2011 From: evosweet at hotmail.com (Rayon) Date: Sat, 22 Oct 2011 20:13:04 -0400 Subject: [Tutor] python telnet In-Reply-To: <4EA31F96.909@pearwood.info> References: <4EA31F96.909@pearwood.info> Message-ID: Well what I am doing is connecting to a telnet session sending some commands, exiting and returning some data. What I would to do is send the commands and return the data without exiting the session. I would like to keep the same session and just send commands and return data. #!/usr/bin/env python import telnetlib class hlr_com(): #get host and command def __init__(self): """init host and command """ self.user_name = '********' self.password = '**********' self.host = '172.20.50.176' self.command = '' #edit top of return def fix_return(self,hia_return): """ edit the top of data returned form the hia """ try: data = str(hia_return).strip('\r') return data except Exception,error: logs("error",str(err),'null') #set host ip address def set_host(self,host): """ set host ipaddress""" self.host = host #send command to hia and end session def hlr_telnet(self,command): """ connect to host and execute command and exit """ try: hlr_tel = telnetlib.Telnet(self.host) hlr_tel.read_until('login:') hlr_tel.write(self.user_name+"\r") hlr_tel.read_until('Password:') hlr_tel.write(self.password+"\r") #execute command hlr_tel.read_until('maint at atcaHLRds0 /public/users/maint>') hlr_tel.write(command+'\r') #end session data = hlr_tel.read_until('maint at atcaHLRds0 /public/users/maint>') hlr_tel.write('exit'+'\r') data2 = self.fix_return(data) #return data return data2 except Exception,error: logs("error",str(err),'null') def logs(self,log_type,log_data,ip_address): """ Log for errors """ try: conn = psycopg2.connect(database="hlr_proxy",user="postgres",host="localhost", password="bb_server_1",port="5432") #connect to database create_date = str(datetime.datetime.now()) cur = conn.cursor() # create cursor cur.execute("insert into hlr_logs(create_date,log_type,log_data,ip_address)values(%s,%s,%s,%s)", (create_date,log_type,log_data,ip_address)) conn.commit() cur.close() conn.close() finally: try: log_file = open(r"text_log.txt","a") log_file.write(create_date+","+log_type+","+log_data+","+str(ip_address)+'\r '+'\n') log_file.close() except Exception,error: pass -----Original Message----- From: tutor-bounces+evosweet=hotmail.com at python.org [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of Steven D'Aprano Sent: 22 October 2011 15:55 To: tutor at python.org Subject: Re: [Tutor] python telnet Rayon wrote: > Can I connect to a telnet session and return data without > disconnecting the data session. Isn't this the same question you asked back in June? We tried to answer your question then, did you see our responses, and were they useful? At the time, you were complaining that the telnet session was too slow, but you didn't tell us what you were actually doing. David Heiserca took a guess as to what you were doing, and suggested what you should do again. Did you see his response, and was it helpful? You should show us the code you are using. -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sun Oct 23 03:12:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 23 Oct 2011 12:12:47 +1100 Subject: [Tutor] python telnet In-Reply-To: References: <4EA31F96.909@pearwood.info> Message-ID: <4EA36A0F.9080603@pearwood.info> Rayon wrote: > Well what I am doing is connecting to a telnet session sending some > commands, exiting and returning some data. > What I would to do is send the commands and return the data without exiting > the session. > I would like to keep the same session and just send commands and return > data. Change the work-flow from: repeatedly:- log in write data log out to: log in repeatedly: write data log out This is untested, but it should point you in the right direction. For brevity, anything unchanged will be left out. #!/usr/bin/env python import telnetlib class hlr_com(): #get host and command def __init__(self): """init host and command """ self.user_name = '********' self.password = '**********' self.host = '172.20.50.176' self.command = '' self._connected = False def fix_return(self,hia_return): # UNCHANGED FROM YOUR VERSION #set host ip address def set_host(self,host): # UNCHANGED FROM YOUR VERSION def connect(self): # If already connected, do nothing. if self._connected: return try: hlr_tel = telnetlib.Telnet(self.host) hlr_tel.read_until('login:') hlr_tel.write(self.user_name+"\r") hlr_tel.read_until('Password:') hlr_tel.write(self.password+"\r") self._connected = True except Exception,error: logs("error",str(err),'null') def execute(self, command): """execute command""" try: self._execute_or_fail(command) except Exception,error: logs("error",str(err),'null') def _execute_or_fail(self, command): if not self._connected: # This is probably the wrong exception type raise ValueError('you must connect first') # otherwise execute the command hlr_tel.read_until('maint at atcaHLRds0 /public/users/maint>') hlr_tel.write(command+'\r') def end_session(self): data = hlr_tel.read_until( 'maint at atcaHLRds0 /public/users/maint>' ) hlr_tel.write('exit'+'\r') data = self.fix_return(data) return data def logs(self,log_type,log_data,ip_address): # UNCHANGED FROM YOUR VERSION To use it: instance = hlr_com() instance.connect() instance.execute("fe") instance.execute("fi") instance.execute("fo") instance.execute("fum") instance.end_session() As I said, untested. Good luck! -- Steven From evosweet at hotmail.com Sun Oct 23 04:57:32 2011 From: evosweet at hotmail.com (Rayon) Date: Sat, 22 Oct 2011 22:57:32 -0400 Subject: [Tutor] python telnet In-Reply-To: <4EA36A0F.9080603@pearwood.info> References: <4EA31F96.909@pearwood.info> <4EA36A0F.9080603@pearwood.info> Message-ID: Thanks I will try it and post the code, looks like what I need. -----Original Message----- From: tutor-bounces+evosweet=hotmail.com at python.org [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of Steven D'Aprano Sent: 22 October 2011 21:13 To: tutor at python.org Subject: Re: [Tutor] python telnet Rayon wrote: > Well what I am doing is connecting to a telnet session sending some > commands, exiting and returning some data. > What I would to do is send the commands and return the data without > exiting the session. > I would like to keep the same session and just send commands and > return data. Change the work-flow from: repeatedly:- log in write data log out to: log in repeatedly: write data log out This is untested, but it should point you in the right direction. For brevity, anything unchanged will be left out. #!/usr/bin/env python import telnetlib class hlr_com(): #get host and command def __init__(self): """init host and command """ self.user_name = '********' self.password = '**********' self.host = '172.20.50.176' self.command = '' self._connected = False def fix_return(self,hia_return): # UNCHANGED FROM YOUR VERSION #set host ip address def set_host(self,host): # UNCHANGED FROM YOUR VERSION def connect(self): # If already connected, do nothing. if self._connected: return try: hlr_tel = telnetlib.Telnet(self.host) hlr_tel.read_until('login:') hlr_tel.write(self.user_name+"\r") hlr_tel.read_until('Password:') hlr_tel.write(self.password+"\r") self._connected = True except Exception,error: logs("error",str(err),'null') def execute(self, command): """execute command""" try: self._execute_or_fail(command) except Exception,error: logs("error",str(err),'null') def _execute_or_fail(self, command): if not self._connected: # This is probably the wrong exception type raise ValueError('you must connect first') # otherwise execute the command hlr_tel.read_until('maint at atcaHLRds0 /public/users/maint>') hlr_tel.write(command+'\r') def end_session(self): data = hlr_tel.read_until( 'maint at atcaHLRds0 /public/users/maint>' ) hlr_tel.write('exit'+'\r') data = self.fix_return(data) return data def logs(self,log_type,log_data,ip_address): # UNCHANGED FROM YOUR VERSION To use it: instance = hlr_com() instance.connect() instance.execute("fe") instance.execute("fi") instance.execute("fo") instance.execute("fum") instance.end_session() As I said, untested. Good luck! -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From henry at sa-hk.com Sun Oct 23 06:09:06 2011 From: henry at sa-hk.com (Henry) Date: Sat, 22 Oct 2011 21:09:06 -0700 Subject: [Tutor] Praser Message-ID: Hi Steven, First of all, I want to able to download the data from the web into the database. Here is the part of the link: http://boc.quotepower.com/web/bochk/stocks_mktTransactions.jsp?lang=en&domain=NCBHK&rand=-74344993&lastLevel1Name=nav_stocks&lastStock=5 I hope I can use the download data to do some analysis. I know it is an impossible task for a newbie; however, I don't mind doing it step by step. Thank you Regads, Crusier On Fri, Oct 21, 2011 at 1:40 PM, wrote: > Send Tutor mailing list submissions to > ? ? ? ?tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > ? ? ? ?http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > ? ? ? ?tutor-request at python.org > > You can reach the person managing the list at > ? ? ? ?tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > ? 1. functions and default argument (Praveen Singh) > ? 2. Re: functions and default argument (Christian Witts) > ? 3. Web Praser (Crusier) > ? 4. Re: functions and default argument (Steven D'Aprano) > ? 5. Re: Web Praser (Steven D'Aprano) > ? 6. Re: functions and default argument (Prasad, Ramit) > ? 7. Re: functions and default argument (Albert-Jan Roskam) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 21 Oct 2011 09:00:08 -0400 > From: Praveen Singh > To: tutor at python.org > Subject: [Tutor] functions and default argument > Message-ID: > ? ? ? ? > Content-Type: text/plain; charset="iso-8859-1" > > In function- > > "Default value is *evaluated only once*.This makes different when the > default is a mutable object such as a list, dictionary or instance of most > classes." > > I am not getting it properly-evaluated once?? different behaviour???-- > please explain this. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 2 > Date: Fri, 21 Oct 2011 15:19:39 +0200 > From: Christian Witts > To: Praveen Singh > Cc: tutor at python.org > Subject: Re: [Tutor] functions and default argument > Message-ID: <4EA1716B.5060904 at compuscan.co.za> > Content-Type: text/plain; charset="windows-1252"; Format="flowed" > > On 2011/10/21 03:00 PM, Praveen Singh wrote: >> In function- >> >> "Default value is *evaluated only once*.This makes different when the >> default is a mutable object such as a list, dictionary or instance of >> most classes." >> >> I am not getting it properly-evaluated once?? different behaviour???-- >> please explain this. >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > Mutable defaults for function/method arguments is a Python Gotcha, you > can find a good read here [1]. ?It's a better read than how I would > explain it. > > [1] http://www.ferg.org/projects/python_gotchas.html#contents_item_6 > -- > > Christian Witts > Python Developer > > // > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 3 > Date: Fri, 21 Oct 2011 09:37:40 -0700 > From: Crusier > To: tutor at python.org > Subject: [Tutor] Web Praser > Message-ID: > ? ? ? ? > Content-Type: text/plain; charset=ISO-8859-1 > > Hi, > > I am new to programming. I want to know what I should look at if I > want to learn more about Web Praser. I know there is something called > Beautiful Soup but I think it is kind of difficult for me at this > stage. > > Thank you > > Regards, > Crusier > > > ------------------------------ > > Message: 4 > Date: Sat, 22 Oct 2011 04:25:51 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] functions and default argument > Message-ID: <4EA1AB1F.4090204 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Praveen Singh wrote: >> In function- >> >> "Default value is *evaluated only once*.This makes different when the >> default is a mutable object such as a list, dictionary or instance of most >> classes." >> >> I am not getting it properly-evaluated once?? different behaviour???-- >> please explain this. > > > Look at an example: > > > ?>>> import time > ?>>> def test(t=time.asctime()): > ... ? ? print t, "***", time.asctime() > ... > ?>>> time.sleep(30) ?# wait a little bit > ?>>> test() > Sat Oct 22 04:17:08 2011 *** Sat Oct 22 04:17:57 2011 > ?>>> time.sleep(30) ?# wait a little bit longer > ?>>> test() > Sat Oct 22 04:17:08 2011 *** Sat Oct 22 04:18:46 2011 > > > Notice that the first time printed, using the default value, is the > same. The default value for t is assigned once, and not calculated > again. Since t is a string, it is immutable and can never change. > > The same thing occurs when you use a mutable object like a list or a > dict. The default value is assigned once, and once only. But notice that > you can modify the default value, say by appending to it: > > > ?>>> def test(x=[]): > ... ? ? print x, id(x) > ... ? ? x.append(1) > ... > ?>>> test() > [] 3085600236L > ?>>> test() > [1] 3085600236L > ?>>> test() > [1, 1] 3085600236L > > > It is the same default list every time, but the *contents* of the list > are changing. > > > > -- > Steven > > > ------------------------------ > > Message: 5 > Date: Sat, 22 Oct 2011 04:51:41 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Web Praser > Message-ID: <4EA1B12D.5010502 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Crusier wrote: >> Hi, >> >> I am new to programming. I want to know what I should look at if I >> want to learn more about Web Praser. I know there is something called >> Beautiful Soup but I think it is kind of difficult for me at this >> stage. > > What do you mean by "web parser"? The web (world wide web) is a network > on the internet, you can't parse it. Do you mean a parser for HTML files? > > If you want to learn about parsing, then you should start with something > simpler than HTML. If you want to learn about HTML, start with a good > book or tutorial about HTML. There are dozens of them. > > Before we can advise you properly, you need to explain what it is you > actually want to do. > > > > -- > Steven > > > ------------------------------ > > Message: 6 > Date: Fri, 21 Oct 2011 15:40:39 -0400 > From: "Prasad, Ramit" > To: "tutor at python.org" > Subject: Re: [Tutor] functions and default argument > Message-ID: > ? ? ? ?<0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB4441 at EMARC112VS01.exchad.jpmchase.net> > > Content-Type: text/plain; ? ? ? charset="us-ascii" > >>The same thing occurs when you use a mutable object like a list or a >>dict. The default value is assigned once, and once only. But notice that >>you can modify the default value, say by appending to it: > > Not sure this will work exactly the same way in other IDEs, but in mine: > >>>> a = [] >>>> def foo(x=a): > ... ? ? x.append(1) > ... >>>> a.append( 2 ) >>>> foo() >>>> print a > [2, 1] >>>> help(foo) > Help on function foo in module __pieshell__: > > foo(x=[2, 1]) > >>>> foo() >>>> help(foo) > Help on function foo in module __pieshell__: > > foo(x=[2, 1, 1]) > >>>> a.append( 3 ) >>>> help(foo) > Help on function foo in module __pieshell__: > > foo(x=[2, 1, 1, 3]) >>>> b = [] >>>> foo(b) >>>> b > [1] > > > Notice how it is always bound to the list a, but can be "overridden". > > I know this has been discussed on this list or the main list before if you take a look through the archives. > Sorry I can't remember what the thread would be like or when it was :( > http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > > > ------------------------------ > > Message: 7 > Date: Fri, 21 Oct 2011 13:40:50 -0700 (PDT) > From: Albert-Jan Roskam > To: "Prasad, Ramit" , ? ? ? ?"tutor at python.org" > ? ? ? ? > Subject: Re: [Tutor] functions and default argument > Message-ID: > ? ? ? ?<1319229650.31516.YahooMailNeo at web110708.mail.gq1.yahoo.com> > Content-Type: text/plain; charset="iso-8859-1" > > Interesting thread and webpages. Insightful, but is this really used as a technique in daily practice? It feels a bit like a hack to me. Like the author of one of the websites said: rule #1 don't mess with this. > > ? > Cheers!! > Albert-Jan > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > >>________________________________ >>From: "Prasad, Ramit" >>To: "tutor at python.org" >>Sent: Friday, October 21, 2011 9:40 PM >>Subject: Re: [Tutor] functions and default argument >> >>>The same thing occurs when you use a mutable object like a list or a >>>dict. The default value is assigned once, and once only. But notice that >>>you can modify the default value, say by appending to it: >> >>Not sure this will work exactly the same way in other IDEs, but in mine: >> >>>>> a = [] >>>>> def foo(x=a): >>...? ? ?x.append(1) >>...? ? >>>>> a.append( 2 ) >>>>> foo() >>>>> print a >>[2, 1] >>>>> help(foo) >>Help on function foo in module __pieshell__: >> >>foo(x=[2, 1]) >> >>>>> foo() >>>>> help(foo) >>Help on function foo in module __pieshell__: >> >>foo(x=[2, 1, 1]) >> >>>>> a.append( 3 ) >>>>> help(foo) >>Help on function foo in module __pieshell__: >> >>foo(x=[2, 1, 1, 3]) >>>>> b = [] >>>>> foo(b) >>>>> b >>[1] >> >> >>Notice how it is always bound to the list a, but can be "overridden". >> >>I know this has been discussed on this list or the main list before if you take a look through the archives. >>Sorry I can't remember what the thread would be like or when it was :( >>http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument >> >> >>Ramit >> >> >>Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology >>712 Main Street | Houston, TX 77002 >>work phone: 713 - 216 - 5423 >> >> >> >> >>This email is confidential and subject to important disclaimers and >>conditions including on offers for the purchase or sale of >>securities, accuracy and completeness of information, viruses, >>confidentiality, legal privilege, and legal entity disclaimers, >>available at http://www.jpmorgan.com/pages/disclosures/email.? >>_______________________________________________ >>Tutor maillist? -? Tutor at python.org >>To unsubscribe or change subscription options: >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 92, Issue 92 > ************************************* > From lina.lastname at gmail.com Sun Oct 23 10:33:52 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 23 Oct 2011 16:33:52 +0800 Subject: [Tutor] how to unique the string In-Reply-To: <4EA2F464.3000403@pearwood.info> References: <4EA2F464.3000403@pearwood.info> Message-ID: On Sun, Oct 23, 2011 at 12:50 AM, Steven D'Aprano wrote: > lina wrote: >> >> Hi, >> >> I googled for a while, but failed to find the perfect answer, >> >> for a string >> >> ['85CUR', '85CUR'] > > > That's not a string, it is a list. > > >> how can I unique it as: >> >> ['85CUR'] > > Your question is unclear. If you have this: > > ['85CUR', '99bcd', '85CUR', '85CUR'] > > what do you expect to get? > > > # keep only the very first item > ['85CUR'] > # keep the first copy of each string, in order > ['85CUR', '99bcd'] > # keep the last copy of each string, in order > ['99bcd', '85CUR'] > # ignore duplicates only when next to each other > ['85CUR', '99bcd', '85CUR'] > > > Does the order of the result matter? > > If order matters, and you want to keep the first copy of each string: > > unique = [] > for item in items: > ? ?if item not in unique: > ? ? ? ?unique.append(item) > > > If order doesn't matter, then use this: > > unique = list(set(items)) Thanks, this one unique=list(set(item)) works well. I have a further question: #!/usr/bin/python3 import os.path mapping={} DICTIONARYFILE="dictionary.pdb" TOBETRANSLATEDFILEEXT=".out" OUTPUTFILEEXT=".txt" def generate_dict(dictionarysourcefile): for line in open(dictionarysourcefile,"r").readlines(): parts=line.strip().split() mapping[parts[2]]=parts[0] def translate_process(dictionary,tobetranslatedfile): results=[] unique={} for line in open(tobetranslatedfile,"r").readlines(): tobetranslatedparts=line.strip().split() results.append(dictionary[tobetranslatedparts[2]]) for residue in results: if residue not in unique: unique[residue]=1 else: unique[residue]+=1 for residue, numbers in unique.items(): print(residue,numbers) with open(base+OUTPUTFILEEXT,"w") as f: f.write(str(unique)) ########### How can I output the results the same as the print one. Thanks. if __name__=="__main__": generate_dict(DICTIONARYFILE) for infilename in os.listdir("."): base, ext = os.path.splitext(infilename) if ext == TOBETRANSLATEDFILEEXT: translate_process(mapping, infilename) https://docs.google.com/leaf?id=0B93SVRfpVVg3ZTBiYjU1MzYtNTNkMS00ZjQ1LWI4MzEtNDEyZWUwYTFmNjU4&hl=en_GB https://docs.google.com/leaf?id=0B93SVRfpVVg3ODU4MDlkMDQtOTJmMy00MDJiLTkwM2EtY2EyNTUyZmNhNTNm&hl=en_GB Welcome anyone help me transform the code to another form. > > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sun Oct 23 10:58:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Oct 2011 09:58:27 +0100 Subject: [Tutor] Praser In-Reply-To: References: Message-ID: On 23/10/11 05:09, Henry wrote: Please delete irrelevant material from your messages. In particular do not send the entire digest content to the list. > First of all, I want to able to download the data from the web into > the database. Here is the part of the link: > > http://boc.quotepower.com/web/bochk/stocks_mktTransactions.jsp?lang=en&domain=NCBHK&rand=-74344993&lastLevel1Name=nav_stocks&lastStock=5 > > I hope I can use the download data to do some analysis. Look at the urllib and urllib2 modules in the standard library. They allow you to treat a url like a file (almost) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Oct 23 11:08:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Oct 2011 10:08:44 +0100 Subject: [Tutor] how to unique the string In-Reply-To: References: <4EA2F464.3000403@pearwood.info> Message-ID: On 23/10/11 09:33, lina wrote: > I have a further question: > > Welcome anyone help me transform the code to another form. What form would you like it transformed to? A flow chart? Another programming language? A different style of Python (Functional programming or OOP maybe?) I'm not sure what you want here? In the meantime I'll offer some general comments: > #!/usr/bin/python3 > import os.path > mapping={} > > > DICTIONARYFILE="dictionary.pdb" > TOBETRANSLATEDFILEEXT=".out" > OUTPUTFILEEXT=".txt" > > def generate_dict(dictionarysourcefile): > for line in open(dictionarysourcefile,"r").readlines(): You don't need the readlines(). Just use for line in open(dictionarysourcefile,"r"): That will work just as well. > parts=line.strip().split() > mapping[parts[2]]=parts[0] > > > def translate_process(dictionary,tobetranslatedfile): > results=[] > unique={} > for line in open(tobetranslatedfile,"r").readlines(): > tobetranslatedparts=line.strip().split() > results.append(dictionary[tobetranslatedparts[2]]) > for residue in results: > if residue not in unique: > unique[residue]=1 > else: > unique[residue]+=1 You can replace the if/else with the get() metjod of a dictionary: unique[residue] = unique.get(residue,0) + 1 get returns the current value and if the value is not there it returns the second parameter(zero here) > for residue, numbers in unique.items(): > print(residue,numbers) > with open(base+OUTPUTFILEEXT,"w") as f: > f.write(str(unique)) ########### How can I output the > results the same as the print one. Thanks. create a string before you write it: mystr = str(residue) + str(numbers) is the simplest way. However you may prefer to format the string in another way first. But thats your choice... > if __name__=="__main__": > generate_dict(DICTIONARYFILE) > for infilename in os.listdir("."): > base, ext = os.path.splitext(infilename) > if ext == TOBETRANSLATEDFILEEXT: > translate_process(mapping, infilename) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Sun Oct 23 11:37:55 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 23 Oct 2011 17:37:55 +0800 Subject: [Tutor] how to unique the string In-Reply-To: References: <4EA2F464.3000403@pearwood.info> Message-ID: On Sun, Oct 23, 2011 at 5:08 PM, Alan Gauld wrote: > On 23/10/11 09:33, lina wrote: > >> I have a further question: >> > >> Welcome anyone help me transform the code to another form. > > What form would you like it transformed to? > A flow chart? Another programming language? A different style of Python > (Functional programming or OOP maybe?) Just an updated version. Like the comments you gave. BTW, thanks for the comments. > > I'm not sure what you want here? > In the meantime I'll offer some general comments: > >> #!/usr/bin/python3 >> import os.path >> mapping={} >> >> >> DICTIONARYFILE="dictionary.pdb" >> TOBETRANSLATEDFILEEXT=".out" >> OUTPUTFILEEXT=".txt" >> >> def generate_dict(dictionarysourcefile): >> ? ? for line in open(dictionarysourcefile,"r").readlines(): > > You don't need the readlines(). Just > use > > ? ?for line in open(dictionarysourcefile,"r"): > > That will work just as well. > >> ? ? ? ? parts=line.strip().split() >> ? ? ? ? mapping[parts[2]]=parts[0] >> >> >> def translate_process(dictionary,tobetranslatedfile): >> ? ? results=[] >> ? ? unique={} >> ? ? for line in open(tobetranslatedfile,"r").readlines(): >> ? ? ? ? tobetranslatedparts=line.strip().split() >> ? ? ? ? results.append(dictionary[tobetranslatedparts[2]]) >> ? ? for residue in results: >> ? ? ? ? if residue not in unique: >> ? ? ? ? ? ? unique[residue]=1 >> ? ? ? ? else: >> ? ? ? ? ? ? unique[residue]+=1 > > You can replace the if/else with the get() metjod of a dictionary: > > ? ? ? ? ? unique[residue] = unique.get(residue,0) + 1 > > get returns the current value and if the value is not there it returns the > second parameter(zero here) > > >> ? ? for residue, numbers in unique.items(): >> ? ? ? ? print(residue,numbers) >> ? ? ? ? with open(base+OUTPUTFILEEXT,"w") as f: >> ? ? ? ? ? ? f.write(str(unique)) ? ? ?########### How can I output the >> results the same as the print one. Thanks. > > create a string before you write it: > > mystr = str(residue) + str(numbers) This part I just wish the output in file like: {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6} as 26SER 2 16LYS 1 83ILE 2 70LYS 6 still have problem in writing the dict. Thanks again for your time, Best regards, > > is the simplest way. However you may prefer to format the string in another > way first. But thats your choice... > >> if __name__=="__main__": >> ? ? generate_dict(DICTIONARYFILE) >> ? ? for infilename in os.listdir("."): >> ? ? ? ? base, ext = ?os.path.splitext(infilename) >> ? ? ? ? if ext == TOBETRANSLATEDFILEEXT: >> ? ? ? ? ? ? translate_process(mapping, infilename) > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From lina.lastname at gmail.com Sun Oct 23 11:39:27 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 23 Oct 2011 17:39:27 +0800 Subject: [Tutor] how to unique the string In-Reply-To: References: <4EA2F464.3000403@pearwood.info> Message-ID: The updated one -- following Alan's advice. #!/usr/bin/python3 import os.path mapping={} DICTIONARYFILE="dictionary.pdb" TOBETRANSLATEDFILEEXT=".out" OUTPUTFILEEXT=".txt" def generate_dict(dictionarysourcefile): for line in open(dictionarysourcefile,"r"): parts=line.strip().split() mapping[parts[2]]=parts[0] def translate_process(dictionary,tobetranslatedfile): results=[] unique={} for line in open(tobetranslatedfile,"r"): tobetranslatedparts=line.strip().split() results.append(dictionary[tobetranslatedparts[2]]) for residue in results: unique[residue]=unique.get(residue,0)+1 for residue, numbers in unique.items(): print(residue,numbers) with open(base+OUTPUTFILEEXT,"w") as f: f.write(str(unique)) if __name__=="__main__": generate_dict(DICTIONARYFILE) for infilename in os.listdir("."): base, ext = os.path.splitext(infilename) if ext == TOBETRANSLATEDFILEEXT: translate_process(mapping, infilename) From __peter__ at web.de Sun Oct 23 12:06:05 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 23 Oct 2011 12:06:05 +0200 Subject: [Tutor] how to unique the string References: <4EA2F464.3000403@pearwood.info> Message-ID: lina wrote: >>> tobetranslatedparts=line.strip().split() strip() is superfluous here, split() will take care of the stripping: >>> " alpha \tbeta\n".split() ['alpha', 'beta'] >>> for residue in results: >>> if residue not in unique: >>> unique[residue]=1 >>> else: >>> unique[residue]+=1 There is a dedicated class to help you with that, collections.Counter: >>> from collections import Counter >>> results = ["alpha", "beta", "gamma", "alpha"] >>> unique = Counter(results) >>> unique Counter({'alpha': 2, 'beta': 1, 'gamma': 1}) Counter is a subclass of dict, so the stuff you are doing with `unique` elswhere should continue to work. > This part I just wish the output in file like: > > {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6} > > as > > 26SER 2 > 16LYS 1 > 83ILE 2 > 70LYS 6 You can redirect the output of print() to a file using the `file` keyword argument: >>> unique = {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6} >>> with open("tmp.txt", "w") as f: ... for k, v in unique.items(): ... print(k, v, file=f) ... >>> $ cat tmp.txt 26SER 2 83ILE 2 70LYS 6 16LYS 1 $ From lina.lastname at gmail.com Sun Oct 23 14:01:59 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 23 Oct 2011 20:01:59 +0800 Subject: [Tutor] how to unique the string In-Reply-To: References: <4EA2F464.3000403@pearwood.info> Message-ID: On Sun, Oct 23, 2011 at 6:06 PM, Peter Otten <__peter__ at web.de> wrote: > lina wrote: > >>>> tobetranslatedparts=line.strip().split() > > strip() is superfluous here, split() will take care of the stripping: > >>>> " alpha \tbeta\n".split() > ['alpha', 'beta'] > >>>> for residue in results: >>>> ? ? if residue not in unique: >>>> ? ? ? ? unique[residue]=1 >>>> ? ? else: >>>> ? ? ? ? unique[residue]+=1 > > There is a dedicated class to help you with that, collections.Counter: > >>>> from collections import Counter >>>> results = ["alpha", "beta", "gamma", "alpha"] >>>> unique = Counter(results) >>>> unique > Counter({'alpha': 2, 'beta': 1, 'gamma': 1}) > > Counter is a subclass of dict, so the stuff you are doing with `unique` > elswhere should continue to work. > >> This part I just wish the output in file like: >> >> {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6} >> >> as >> >> 26SER 2 >> 16LYS 1 >> 83ILE 2 >> 70LYS 6 > > You can redirect the output of print() to a file using the `file` keyword > argument: > >>>> unique = {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6} >>>> with open("tmp.txt", "w") as f: > ... ? ? for k, v in unique.items(): > ... ? ? ? ? ? ? print(k, v, file=f) I tested it in idle3, it has no problem achieving this. But I am getting confused later: def translate_process(dictionary,tobetranslatedfile): results=[] unique={} for line in open(tobetranslatedfile,"r"): tobetranslatedparts=line.strip().split() results.append(dictionary[tobetranslatedparts[2]]) unique=Counter(results) with open(base+OUTPUTFILEEXT,"w") as f: for residue, numbers in unique.items(): print(residue,numbers,file=f) it still the same in the OUTPUTFILE as before, $ more atom-pair_6.txt {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6, '55HIS': 5} Thanks, > ... >>>> > $ cat tmp.txt > 26SER 2 > 83ILE 2 > 70LYS 6 > 16LYS 1 > $ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From delegbede at dudupay.com Sun Oct 23 16:47:47 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Sun, 23 Oct 2011 15:47:47 +0100 Subject: [Tutor] URLError Help. Message-ID: I am trying to access a url using the urllib2.urlopen() command. It does well when i run from idle but as soon as i plug into my app; it gives me this . Is there anything I am doing wrong or a thing I should look at? -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Oct 23 18:25:36 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 24 Oct 2011 03:25:36 +1100 Subject: [Tutor] Praser In-Reply-To: References: Message-ID: On 10/23/2011 03:09 PM, Henry wrote: > Hi Steven, > > First of all, I want to able to download the data from the web into > the database. Here is the part of the link: > > http://boc.quotepower.com/web/bochk/stocks_mktTransactions.jsp?lang=en&domain=NCBHK&rand=-74344993&lastLevel1Name=nav_stocks&lastStock=5 > > I hope I can use the download data to do some analysis. Python comes with two HTML parser: htmllib and HTMLParser. If the HTML is also a valid XML, you might want to treat it as an XML instead, Python comes with the xml module. From alan.gauld at btinternet.com Sun Oct 23 23:45:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Oct 2011 22:45:02 +0100 Subject: [Tutor] URLError Help. In-Reply-To: References: Message-ID: On 23/10/11 15:47, Dipo Elegbede wrote: > I am trying to access a url using the urllib2.urlopen() command. > > It does well when i run from idle but as soon as i plug into my app; it > gives me this forcibly closed by the remote host>. Can we see some code that generates the error? And can we see the full error traceback? Also the OS and Python version would be useful. Otherwise we are pretty much guessing at what might be wrong. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Mon Oct 24 00:22:18 2011 From: d at davea.name (Dave Angel) Date: Sun, 23 Oct 2011 18:22:18 -0400 Subject: [Tutor] Simple Question On A Method (in subclass) Message-ID: <4EA4939A.2070602@davea.name> (please do REPLY-ALL, or at least add the mailing list to the recipient list. Otherwise, only one person will see the message. I'm forwarding it to the group with my comments added.) -------- Original Message -------- Subject: Re: [Tutor] Simple Question On A Method (in subclass) Date: Sun, 23 Oct 2011 16:53:40 -0400 From: Chris Kavanagh Organization: Home Office To: d at davea.name On 10/22/2011 6:59 PM, Dave Angel wrote: > >> My question is regarding the tell methods in the subclasses,the code >> {SchoolMember.tell(self)}, in the class Teacher & Student. I just >> don't understand what this is doing? Calling the first method {def >> tell} from the parent class, I assume? There is already a print >> statement in each of the subclass {def tell} showing details, why call >> another print statement (from parent class {def tell})?? I know this >> should be simple, but I'm confused. LOL, obviously. >> >> Thank you in advance! >> >> >> > Welcome to the python-tutor list. We are all volunteers here, and most, > like me, ask questions as well as answering them. it's a two-way street. > > The whole point of subclassing is to share either code, data, or both. > In this example, the amount of shared data is just the name and age, and > the shared method is tell(). Because the parent knows how to 'tell' its > information, the child doesn't need to. So instead of altering the > prints in both the child classes to print name & age, you let the common > code in the parent handle it. > > It becomes more clearly a win when you have much more data, or much more > complex methods involved. But you have to start simple. > > BTW, there were some transcription errors in the email. For example, the > code as written would be using a separate line for Salary on Mrs. > Shrividya's record. And you're missing the content of the for member in > members: loop. No problem, but it might have affected our discussion. > Did you retype it all, or was it just a glitch? Presumably you know how > to copy/paste from and to a console prompt? Chris Kavanagh said: Thanks to both Alan Gauld & Dave Angel for the help!!! I'm not sure how the transcrption errors happened, I copied & pasted. Must have not copied the entire thing. I'll correct it below. Speaking of the last line of code, I have a question about that also. The last line should have been (without my error) {member.tell()}. My question is, why couldn't this last line have been {print member}?? Every example of an iterator I've seen until this point of my learning, has had a print statement then the item variable. Instead, Swaroop uses the item variable to call the function {tell()}. This is sorta confusing to me. What if there was no function to print out the Student and Teacher variable?? How would the iterator been printed out in that case?? Thanks again, in advance. Here's the correct code. class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): self.name = name self.age = age print '(Initialized SchoolMember: %s)' % self.name def tell(self): '''Tell my details.''' print 'Name:"%s" Age:"%s"' % (self.name, self.age), class Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary print '(Initialized Teacher: %s)' % self.name def tell(self): SchoolMember.tell(self) print 'Salary: "%d"' % self.salary class Student(SchoolMember): '''Represents a student.''' def __init__(self, name, age, marks): SchoolMember.__init__(self, name, age) self.marks = marks print '(Initialized Student: %s)' % self.name def tell(self): SchoolMember.tell(self) print 'Marks: "%d"' % self.marks t = Teacher('Mrs. Shrividya', 40, 30000) s = Student('Swaroop', 22, 75) print # prints a blank line members = [t, s] for member in members: member.tell() # works for both Teachers and Students Output $ python inherit.py (Initialized SchoolMember: Mrs. Shrividya) (Initialized Teacher: Mrs. Shrividya) (Initialized SchoolMember: Swaroop) (Initialized Student: Swaroop) Name:"Mrs. Shrividya" Age:"40" Salary: "30000" Name:"Swaroop" Age:"22" Marks: "75" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> You always have a choice of where to put useful code. if you put it in member functions, it can be shared by all the callers. There's no right or wrong way to do it. The only "rule" I can think of is not to mix significant calculations with prints. Make them two different methods, so the user of the class can use them independently. If you had no class member like tell(), one choice would be to enumerate the members yourself. So you could do something like: print member.name, member.age, member.marks, member.salary With some formatting. But not all members have all these fields, so you'd have to do some conditional testing, and it could get quite complex. -- DaveA From d at davea.name Mon Oct 24 00:40:44 2011 From: d at davea.name (Dave Angel) Date: Sun, 23 Oct 2011 18:40:44 -0400 Subject: [Tutor] how to unique the string In-Reply-To: References: <4EA2F464.3000403@pearwood.info> Message-ID: <4EA497EC.5080504@davea.name> On 10/23/2011 08:01 AM, lina wrote: > On Sun, Oct 23, 2011 at 6:06 PM, Peter Otten<__peter__ at web.de> wrote: >> lina wrote: >> >>>>> tobetranslatedparts=line.strip().split() >> strip() is superfluous here, split() will take care of the stripping: >> >>>>> " alpha \tbeta\n".split() >> ['alpha', 'beta'] >> >>>>> for residue in results: >>>>> if residue not in unique: >>>>> unique[residue]=1 >>>>> else: >>>>> unique[residue]+=1 >> There is a dedicated class to help you with that, collections.Counter: >> >>>>> from collections import Counter >>>>> results = ["alpha", "beta", "gamma", "alpha"] >>>>> unique = Counter(results) >>>>> unique >> Counter({'alpha': 2, 'beta': 1, 'gamma': 1}) >> >> Counter is a subclass of dict, so the stuff you are doing with `unique` >> elswhere should continue to work. >> >>> This part I just wish the output in file like: >>> >>> {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6} >>> >>> as >>> >>> 26SER 2 >>> 16LYS 1 >>> 83ILE 2 >>> 70LYS 6 >> You can redirect the output of print() to a file using the `file` keyword >> argument: >> >>>>> unique = {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6} >>>>> with open("tmp.txt", "w") as f: >> ... for k, v in unique.items(): >> ... print(k, v, file=f) > I tested it in idle3, it has no problem achieving this. > > But I am getting confused later: > > def translate_process(dictionary,tobetranslatedfile): > results=[] > unique={} > for line in open(tobetranslatedfile,"r"): > tobetranslatedparts=line.strip().split() > results.append(dictionary[tobetranslatedparts[2]]) > unique=Counter(results) > with open(base+OUTPUTFILEEXT,"w") as f: Every time you do this, you're truncating the file. It'd be better to open the file outside the for-line loop, and just use the file object in the loop. > for residue, numbers in unique.items(): > print(residue,numbers,file=f) > > it still the same in the OUTPUTFILE as before, > > $ more atom-pair_6.txt > {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6, '55HIS': 5} > > Thanks, > >> ... >> $ cat tmp.txt >> 26SER 2 >> 83ILE 2 >> 70LYS 6 >> 16LYS 1 >> $ >> -- DaveA From ckava1 at msn.com Mon Oct 24 01:54:25 2011 From: ckava1 at msn.com (Chris Kavanagh) Date: Sun, 23 Oct 2011 19:54:25 -0400 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: <4EA4939A.2070602@davea.name> References: <4EA4939A.2070602@davea.name> Message-ID: On 10/23/2011 6:22 PM, Dave Angel wrote: > > (please do REPLY-ALL, or at least add the mailing list to the recipient > list. Otherwise, only one person will see the message. I'm forwarding it > to the group with my comments added.) > > -------- Original Message -------- > Subject: Re: [Tutor] Simple Question On A Method (in subclass) > Date: Sun, 23 Oct 2011 16:53:40 -0400 > From: Chris Kavanagh > Organization: Home Office > To: d at davea.name > > > > On 10/22/2011 6:59 PM, Dave Angel wrote: >> >>> My question is regarding the tell methods in the subclasses,the code >>> {SchoolMember.tell(self)}, in the class Teacher & Student. I just >>> don't understand what this is doing? Calling the first method {def >>> tell} from the parent class, I assume? There is already a print >>> statement in each of the subclass {def tell} showing details, why call >>> another print statement (from parent class {def tell})?? I know this >>> should be simple, but I'm confused. LOL, obviously. >>> >>> Thank you in advance! >>> >>> >>> > >> Welcome to the python-tutor list. We are all volunteers here, and most, >> like me, ask questions as well as answering them. it's a two-way street. >> >> The whole point of subclassing is to share either code, data, or both. >> In this example, the amount of shared data is just the name and age, and >> the shared method is tell(). Because the parent knows how to 'tell' its >> information, the child doesn't need to. So instead of altering the >> prints in both the child classes to print name & age, you let the common >> code in the parent handle it. >> >> It becomes more clearly a win when you have much more data, or much more >> complex methods involved. But you have to start simple. >> >> BTW, there were some transcription errors in the email. For example, the >> code as written would be using a separate line for Salary on Mrs. >> Shrividya's record. And you're missing the content of the for member in >> members: loop. No problem, but it might have affected our discussion. >> Did you retype it all, or was it just a glitch? Presumably you know how >> to copy/paste from and to a console prompt? > > Chris Kavanagh said: > > Thanks to both Alan Gauld & Dave Angel for the help!!! > > I'm not sure how the transcrption errors happened, I copied & pasted. > Must have not copied the entire thing. I'll correct it below. > > Speaking of the last line of code, I have a question about that also. > The last line should have been (without my error) {member.tell()}. > My question is, why couldn't this last line have been {print member}?? > Every example of an iterator I've seen until this point of my learning, > has had a print statement then the item variable. Instead, Swaroop uses > the item variable to call the function {tell()}. This is sorta confusing > to me. What if there was no function to print out the Student and > Teacher variable?? How would the iterator been printed out in that > case?? Thanks again, in advance. Here's the correct code. > > > class SchoolMember: > '''Represents any school member.''' > def __init__(self, name, age): > self.name = name > self.age = age > print '(Initialized SchoolMember: %s)' % self.name > > def tell(self): > '''Tell my details.''' > print 'Name:"%s" Age:"%s"' % (self.name, self.age), > > class Teacher(SchoolMember): > '''Represents a teacher.''' > def __init__(self, name, age, salary): > SchoolMember.__init__(self, name, age) > self.salary = salary > print '(Initialized Teacher: %s)' % self.name > > def tell(self): > SchoolMember.tell(self) > print 'Salary: "%d"' % self.salary > > class Student(SchoolMember): > '''Represents a student.''' > def __init__(self, name, age, marks): > SchoolMember.__init__(self, name, age) > self.marks = marks > print '(Initialized Student: %s)' % self.name > > def tell(self): > SchoolMember.tell(self) > print 'Marks: "%d"' % self.marks > > t = Teacher('Mrs. Shrividya', 40, 30000) > s = Student('Swaroop', 22, 75) > > print # prints a blank line > > members = [t, s] > for member in members: > member.tell() # works for both Teachers and Students > > > > Output > > > $ python inherit.py > (Initialized SchoolMember: Mrs. Shrividya) > (Initialized Teacher: Mrs. Shrividya) > (Initialized SchoolMember: Swaroop) > (Initialized Student: Swaroop) > > Name:"Mrs. Shrividya" Age:"40" Salary: "30000" > Name:"Swaroop" Age:"22" Marks: "75" > > >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > You always have a choice of where to put useful code. if you put it in > member functions, it can be shared by all the callers. There's no right > or wrong way to do it. The only "rule" I can think of is not to mix > significant calculations with prints. Make them two different methods, > so the user of the class can use them independently. > > If you had no class member like tell(), one choice would be to enumerate > the members yourself. So you could do something like: > > print member.name, member.age, member.marks, member.salary > > With some formatting. But not all members have all these fields, so > you'd have to do some conditional testing, and it could get quite complex. > > -- > > DaveA > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Sorry, thought I hit reply all. . .I'm still a little shaky on this. I thought if you created an iterator, and you wanted to see the results, you had to write, print(item variable). How can you use the item variable with a function? Is it because the item variable, in this case {member}, is an object? And because it's an object you can use dot notation to call the {tell} function {member.tell()} Sorry for the confusing question. Sometimes I'm not quite sure how to ask what I want to know, lol. . .Anyways, THANKS so much for the help. From alan.gauld at btinternet.com Mon Oct 24 02:28:10 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Oct 2011 01:28:10 +0100 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: On 24/10/11 00:54, Chris Kavanagh wrote: >> Speaking of the last line of code, I have a question about that also. >> The last line should have been (without my error) {member.tell()}. >> My question is, why couldn't this last line have been {print member}?? It could have been, but the output would have been different. When you call print it automatically calls the str() function on the arguments. So {print member} would actually print out {str(member)}. But str(member) is a message to say that member is an instance of a class, not a list of the attributes formatted in a specific way. Now Swaroop could have chosen to implement a __str__() method in the classes in which case print would have done what you expect. (But I guess he felt that would be too advanced at this stage in his tutor) Another option would have been to make tell() return a string rather than print it, in which case you could have used {print member.tell()} >> Every example of an iterator I've seen until this point of my learning, >> has had a print statement then the item variable. Thats just a coincidence with how you've seen iterators used. An iterator allows you to do anything you like to the items being iterated over. It just so happens that so far you have only seen them being printed. Printing is only one, and is far from the most common, use of iterators. >> the item variable to call the function {tell()}. This is sorta confusing >> to me. What if there was no function to print out the Student and >> Teacher variable?? You would have to rely on the str() conversion - which will always print something, even if its not very helpful! Or, you could manually print the contents of the member - but that gets very complicated where you have mixed sub and superclasses in a single collection. > How would the iterator been printed out in that > case?? Being picky, you are not printing the iterator, you are printing the items returned by the iterator. But ignoring that, you would do one of the options I described above: 1) print the object using its built in str() convertion 2) create your own string conversion method (__str__() ) 3) print the individual data members by hand Personally I would choose the second one, but modifying the code is not always possible, in which case, option 3 wins. Option 1 is usually pretty useless! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ckava1 at msn.com Mon Oct 24 05:08:36 2011 From: ckava1 at msn.com (Chris Kavanagh) Date: Sun, 23 Oct 2011 23:08:36 -0400 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: On 10/23/2011 8:28 PM, Alan Gauld wrote: > On 24/10/11 00:54, Chris Kavanagh wrote: > >>> Speaking of the last line of code, I have a question about that also. >>> The last line should have been (without my error) {member.tell()}. >>> My question is, why couldn't this last line have been {print member}?? > > It could have been, but the output would have been different. > When you call print it automatically calls the str() function on the > arguments. So {print member} would actually print out > {str(member)}. But str(member) is a message to say that member is an > instance of a class, not a list of the attributes formatted in a > specific way. > > Now Swaroop could have chosen to implement a __str__() method in the > classes in which case print would have done what you expect. (But I > guess he felt that would be too advanced at this stage in his tutor) > Another option would have been to make tell() return a string rather > than print it, in which case you could have used {print member.tell()} > >>> Every example of an iterator I've seen until this point of my learning, >>> has had a print statement then the item variable. > > Thats just a coincidence with how you've seen iterators used. An > iterator allows you to do anything you like to the items being iterated > over. It just so happens that so far you have only seen them being > printed. Printing is only one, and is far from the most common, use of > iterators. > >>> the item variable to call the function {tell()}. This is sorta confusing >>> to me. What if there was no function to print out the Student and >>> Teacher variable?? > > You would have to rely on the str() conversion - which will always print > something, even if its not very helpful! Or, you could manually print > the contents of the member - but that gets very complicated where you > have mixed sub and superclasses in a single collection. > > > How would the iterator been printed out in that >> case?? > > Being picky, you are not printing the iterator, you are printing the > items returned by the iterator. But ignoring that, you would do one of > the options I described above: > > 1) print the object using its built in str() convertion > 2) create your own string conversion method (__str__() ) > 3) print the individual data members by hand > > Personally I would choose the second one, but modifying the code is not > always possible, in which case, option 3 wins. Option 1 is usually > pretty useless! > > HTH > Thanks so much for the help Alan. . .I'm not trying to beat this question into the ground, LOL, but let me see if I can ask it a better way. So we have {member.tell} as the last line of code. So trying to understand this piece of code, {member} the variable is considered an object? Therefore we can combine it with a function {tell()} using dot notation?? Is this correct??? I haven't seen anything but an object combined with a function using dot notation. When I say "object", I mean an "object" created from a class. So I'm trying to figure out how we can combine the variable {member} with the function {tell}. Hope this question makes sense to you, LOL. Thanks again. From apometron.listas.cinco at gmail.com Mon Oct 24 05:21:49 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Mon, 24 Oct 2011 01:21:49 -0200 Subject: [Tutor] What is wrong with my code? In-Reply-To: <4EA49BA2.6080309@davea.name> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> Message-ID: <4EA4D9CD.7010101@gmail.com> Sorry to continue discussing my thread on this list, I already subbed on the Tutor list but I need to reply and if possible, some ideas of why it dont works. Now it is another thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py dont works? http://pastebin.com/dExFtTkp Thanks by the gentle support. []s Apometron On 10/23/2011 8:56 PM, Dave Angel wrote: > On 10/23/2011 06:03 AM, apometron wrote: >> import os >> nome = sys.argv[1] >> final = nome >> for i in nome: >> print i >> if nome[i] = "_": >> final[i] = " " >> os.rename(nome, final) >> > What do you want to be wrong with it? There are so many things, it'd > be fun to try to see who could come up with the most. > > 1) it's not a valid Fortran program. > 2) it's missing a shebang line > if we assume it's for Windows, or that you run it with an explicit > bash line > 3) if we pretend it's a python program, a few more > 3a) It has a syntax error calling the print() function. (Python 3.2) > If we assume it's a python 2.x program > 4) it uses sys, without importing it > 5) it uses second argument without checking if the user typed such an > argument > 6) it tries to change a character within a string, which is a > non-mutable type > 7) It creates two more references to the same string sys.argv[1], then > tries to modify one of them, not realizing the others would change to. > 8) it tries to subscript a string using a character. > 9) it calls rename with two references to the same object. So nothing > will ever actually happen, even if the other problems were fixed. > > Generally, you'll get the best answers here if you specify more of > your environment (python version, OS), show what you tried (pasted > from the command line), and the results you got (such as stack traces). > > HTH > > DaveA > > From sweetnivi88 at gmail.com Mon Oct 24 06:04:12 2011 From: sweetnivi88 at gmail.com (nivedita datta) Date: Mon, 24 Oct 2011 09:34:12 +0530 Subject: [Tutor] reg current work in pycrypto Message-ID: Hi all, Can anyone tell me about some projects or applications which has been built using pycrypto. Also I would like to know about any ongoing/past project or application development in pycrypto. I would like to have the following information on pycrypto : 1. some attention grabbing fact/detail related to past progress in the work or related to the usability.**** 2. the future work or possible extension.**** 3. some references of some existing paper or book on the same. Regards, Nivedita Datta -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Oct 24 06:06:05 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 23 Oct 2011 21:06:05 -0700 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: On Sun, Oct 23, 2011 at 8:08 PM, Chris Kavanagh wrote: > So we have {member.tell} as the last line of code. So trying to understand > this piece of code, {member} the variable is considered an object? Therefore > we can combine it with a function {tell()} using dot notation?? Is this > correct??? I haven't seen anything but an object combined with a function > using dot notation. When I say "object", I mean an "object" created from a > class. So I'm trying to figure out how we can combine the variable {member} > with the function {tell}. Hope this question makes sense to you, LOL. Thanks > again. > First of all: other languages distinguish between variables and objects, and between functions and objects, but in Python both variables and functions are objects. EVERYTHING is an object. This is an important thing to remember - even if you never create classes of your own (which would be a terrible waste, BTW) a lot of the language won't make sense unless you remember that everything's an object. Second, the line "members = [t, s]" creates a list "members" (which is also an object, by the way!) containing two objects - "t" is a Teacher, "s" is a Student - which are both subclassed from SchoolMember. The line "for member in members" means: step through the list "members" and work with each object we find in it; let's call that object "member" while we're working with it. As soon as we finish with the first object and move on to the next, call the next one "member" - and so on. The beauty of this approach is that it simply doesn't matter what the contents of the list are - one could be a Student, the next a WoollyMammoth - and as long as your code only references methods and attributes that work for all the items in the list, Python won't care. Third, dot notation: objects have "methods" (which in non-OOP contexts would be called "functions") and "attributes" (variables, more or less.) >From outside of the class definition, you refer to the object's attributes like so: variable = object.attribute # if you want to read the attribute's current value or object.attribute = variable # if you want to set the attribute to a new value and to its methods like so: variable = object.method(parameter1, parameter2, etc) Like all functions, methods can take a fixed number of parameters, an optional bunch of named parameters, or no parameters at all; they may return a value or they may not; you may want to use that value, or ignore it. Things to remember: -you can get a value from a method, but you can't assign to it: variable = object.method() but NOT object.method() = variable -the only visible difference between reading an attribute and calling a method with no parameters is the parentheses at the end. Don't forget them, and don't be misled by the similarity. Hope that helps... -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Oct 24 09:24:05 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Oct 2011 09:24:05 +0200 Subject: [Tutor] how to unique the string References: <4EA2F464.3000403@pearwood.info> Message-ID: lina wrote: > But I am getting confused later: > > def translate_process(dictionary,tobetranslatedfile): > results=[] > unique={} > for line in open(tobetranslatedfile,"r"): > tobetranslatedparts=line.strip().split() > results.append(dictionary[tobetranslatedparts[2]]) > unique=Counter(results) > with open(base+OUTPUTFILEEXT,"w") as f: > for residue, numbers in unique.items(): > print(residue,numbers,file=f) As Dave says, the above four lines should run only once, outside the for- loop. Here's a way to avoid the intermediate results list. As a bonus I'm removing access to the `base` global variable: def change_ext(name, new_ext): """ >>> change_ext("/deep/blue.eyes", ".c") '/deep/blue.c' """ return os.path.splitext(name)[0] + new_ext def translate_process(dictionary, tobetranslatedfile): with open(tobetranslatedfile, "r") as f: results = (dictionary[line.split()[2]] for line in f) unique = Counter(results) with open(change_ext(tobetranslatedfile, OUTPUTFILEEXT), "w") as out: for residue, numbers in unique.items(): print(residue, numbers, file=out) > it still the same in the OUTPUTFILE as before, > > $ more atom-pair_6.txt > {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6, '55HIS': 5} Unlikely. Verify that you are running the correct script and looking into the right output file. From lina.lastname at gmail.com Mon Oct 24 09:56:12 2011 From: lina.lastname at gmail.com (lina) Date: Mon, 24 Oct 2011 15:56:12 +0800 Subject: [Tutor] how to unique the string In-Reply-To: References: <4EA2F464.3000403@pearwood.info> Message-ID: On Mon, Oct 24, 2011 at 3:24 PM, Peter Otten <__peter__ at web.de> wrote: > lina wrote: > >> But I am getting confused later: >> >> def translate_process(dictionary,tobetranslatedfile): >> ? ? results=[] >> ? ? unique={} >> ? ? for line in open(tobetranslatedfile,"r"): >> ? ? ? ? tobetranslatedparts=line.strip().split() >> ? ? ? ? results.append(dictionary[tobetranslatedparts[2]]) > >> ? ? ? ? unique=Counter(results) >> ? ? ? ? with open(base+OUTPUTFILEEXT,"w") as f: >> ? ? ? ? ? ? for residue, numbers in unique.items(): >> ? ? ? ? ? ? ? ? print(residue,numbers,file=f) > > As Dave says, the above four lines should run only once, outside the for- > loop. > > Here's a way to avoid the intermediate results list. As a bonus I'm removing > access to the `base` global variable: > > def change_ext(name, new_ext): > ? ?""" > ? ?>>> change_ext("/deep/blue.eyes", ".c") > ? ?'/deep/blue.c' > ? ?""" > ? ?return os.path.splitext(name)[0] + new_ext > > def translate_process(dictionary, tobetranslatedfile): > ? ?with open(tobetranslatedfile, "r") as f: > ? ? ? ?results = (dictionary[line.split()[2]] for line in f) > ? ? ? ?unique = Counter(results) > > ? ?with open(change_ext(tobetranslatedfile, OUTPUTFILEEXT), "w") as out: > ? ? ? ?for residue, numbers in unique.items(): > ? ? ? ? ? ?print(residue, numbers, file=out) > > >> it still the same in the OUTPUTFILE as before, >> >> ?$ more atom-pair_6.txt >> {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6, '55HIS': 5} > > Unlikely. Verify that you are running the correct script and looking into > the right output file. Thanks, print(residue,numbers,"\n",file=f) achieve this. 62PHE 10 34LEU 37 43ASP 6 but seems the \n added one more line, > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From lina.lastname at gmail.com Mon Oct 24 10:04:04 2011 From: lina.lastname at gmail.com (lina) Date: Mon, 24 Oct 2011 16:04:04 +0800 Subject: [Tutor] how to unique the string In-Reply-To: <4EA497EC.5080504@davea.name> References: <4EA2F464.3000403@pearwood.info> <4EA497EC.5080504@davea.name> Message-ID: >> >> def translate_process(dictionary,tobetranslatedfile): >> ? ? results=[] >> ? ? unique={} >> ? ? for line in open(tobetranslatedfile,"r"): >> ? ? ? ? tobetranslatedparts=line.strip().split() >> ? ? ? ? results.append(dictionary[tobetranslatedparts[2]]) >> ? ? ? ? unique=Counter(results) >> ? ? ? ? with open(base+OUTPUTFILEEXT,"w") as f: > > Every time you do this, you're truncating the file. ?It'd be better to open > the file outside the for-line loop, and just use the file object in the > loop. Before I did not understand well, until I read Peter's following post. Thanks, > > -- > > DaveA > > From lina.lastname at gmail.com Mon Oct 24 10:05:11 2011 From: lina.lastname at gmail.com (lina) Date: Mon, 24 Oct 2011 16:05:11 +0800 Subject: [Tutor] how to unique the string In-Reply-To: References: <4EA2F464.3000403@pearwood.info> Message-ID: On Mon, Oct 24, 2011 at 3:24 PM, Peter Otten <__peter__ at web.de> wrote: > lina wrote: > >> But I am getting confused later: >> >> def translate_process(dictionary,tobetranslatedfile): >> ? ? results=[] >> ? ? unique={} >> ? ? for line in open(tobetranslatedfile,"r"): >> ? ? ? ? tobetranslatedparts=line.strip().split() >> ? ? ? ? results.append(dictionary[tobetranslatedparts[2]]) > >> ? ? ? ? unique=Counter(results) >> ? ? ? ? with open(base+OUTPUTFILEEXT,"w") as f: >> ? ? ? ? ? ? for residue, numbers in unique.items(): >> ? ? ? ? ? ? ? ? print(residue,numbers,file=f) > > As Dave says, the above four lines should run only once, outside the for- > loop. > > Here's a way to avoid the intermediate results list. As a bonus I'm removing > access to the `base` global variable: > > def change_ext(name, new_ext): > ? ?""" > ? ?>>> change_ext("/deep/blue.eyes", ".c") > ? ?'/deep/blue.c' > ? ?""" > ? ?return os.path.splitext(name)[0] + new_ext > > def translate_process(dictionary, tobetranslatedfile): > ? ?with open(tobetranslatedfile, "r") as f: > ? ? ? ?results = (dictionary[line.split()[2]] for line in f) > ? ? ? ?unique = Counter(results) > > ? ?with open(change_ext(tobetranslatedfile, OUTPUTFILEEXT), "w") as out: > ? ? ? ?for residue, numbers in unique.items(): > ? ? ? ? ? ?print(residue, numbers, file=out) Now work as expected. concise than before. Thanks, > > >> it still the same in the OUTPUTFILE as before, >> >> ?$ more atom-pair_6.txt >> {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6, '55HIS': 5} > > Unlikely. Verify that you are running the correct script and looking into > the right output file. > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Oct 24 10:40:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Oct 2011 09:40:49 +0100 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: On 24/10/11 04:08, Chris Kavanagh wrote: > Thanks so much for the help Alan. . .I'm not trying to beat this > question into the ground, LOL, but let me see if I can ask it a better way. Marc has already given a good answer, but I'll try a slightly different approach to the same thing.... The differences are purely philosophical :-) > So we have {member.tell} as the last line of code. So trying to > understand this piece of code, {member} the variable is considered an > object? Almost. member is an object because it is an instance of a class. We created instances of Teacher and Student (t and s) and put them in a list (members) with this code: t = Teacher('Mrs. Shrividya', 40, 30000) s = Student('Swaroop', 22, 75) members = [t, s] Thus for member in members takes each object in the list and assigns it to member. We can read {for member in members} as "Let member take on, in turn, each value in the collection members" And making it more explicit with a while loop: index = 0 while index < len(members): member = members[index] member.tell() index += 1 > Therefore we can combine it with a function {tell()} using dot > notation?? Is this correct??? I haven't seen anything but an > object combined with a function using dot notation. dot notation is how we access anything that is defined inside the class definition. In this case there are only the __init__() and tell() methods but there could be data attributes too. Furthermore we can add data attributes to the objects by using the self parameter, as is done in __init__() So we end up with the instance containing the attributes defined at the class level (including those of its superclass) plus any added by the __init__() method which is called when the object is created (or instantiated). So for Teacher the attributes will be: __init__() tell() name - from SchoolMember.__init__() age - ditto salary - from Teacher.__init__() So we could have accessed any of those for the first iteration of the loop because member was a Teacher instance (t) using: member.tell, member.name, member.age, member.salary But the last one would have broken for the second object in the list since it was a student, which doesn't have a salary. So when dealing with a list of objects we have to restrict the access via dot notation to those attributes that are common to all objects in the collection - usually the ones defined in the super class. Python doesn't care whether the attributes we access are data or functions because in Python everything is an "object" (see Marc's post) But by putting parentheses after the object name Python treats the named object as a function (specifically a "callable" object) You can see this diffence at work in the interpreter if you type this: >>> def f(): ... return "Called f" ... >>> print f >>> print f() Called f See the difference the () made? Without it we print the function object called f. With it we print the result of calling the function f. Thats quite a subtle concept and usually hard for beginners to grasp but it is a very powerful concept and you will find it being used in more advanced programs, especially GUI development. > So I'm trying to figure out how we can > combine the variable {member} with the function {tell}. Hope this > question makes sense to you, LOL. Thanks again. How we combine it is done inside Python as part of the magic of classes and instantiation. Basically you can call any function defined inside a class and Python will automatically assign the first parameter of that function to the object instace that you are referencing at the time. Thus when we do for member in members: member.tell() Python recognises that first time round member refers to the object t which is an instanmce of Teacher. It then calls the tell() method within the Teacher class definition and assigns t as the self parameter. We could write it explicitly as: Teacher.tell(member) # where member is t On the second time round member is assigned to s and Python recognizes that s in an instance of Student. So it calls Student.tell(member) where member is s. The member.tell() notation is just a convenient way for us to write it and allows Python to do the hard work of figuring out what kind of object member is at any given time. [Aside: In true OOP speak we describe the process as "sending a message to the object. Thus member.tell() sends the message "tell" to the object "member" and the OOP framework invokes the corresponding method tell() in the corresponding class. In some OOP languages you can use different names for the messages and corresponding methods but in Python they are the same so we just talk about calling the method.] HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Mon Oct 24 12:17:58 2011 From: lina.lastname at gmail.com (lina) Date: Mon, 24 Oct 2011 18:17:58 +0800 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: a quick Q: Every time call the method, need go through the __initi__( ) part? Thanks, I attached the one I used to practice fast-typing: #!/usr/bin/python3 class SchoolMember: '''Represents any school members.''' def __init__(self,name,age): self.name = name self.age = age print("Initialized School Memeber: ", self.name) def tell(self): '''Tell my details.''' print("Name:", self.name, "Age: ", self.age) class Teacher(SchoolMember): '''Represents a Teacher''' def __init__(self,name,age,salary): SchoolMember.__init__(self,name,age) self.salary = salary print("Initialized Teacher", self.name) def tell(self): SchoolMember.tell(self) print("Salary:", self.salary) class Student(SchoolMember): '''Represent a student.''' def __init__(self,name,age,marks): SchoolMember.__init__(self,name,age) self.marks = marks print("Initialized Student:", self.name) def tell(self): SchoolMember.tell(self) print("Marks: ", self.marks) t = Teacher('Mrs. Shrividya',40,30000) s = Student('Swaroop',22,75) print() members=[t,s] for member in members: member.tell() From ckava1 at msn.com Mon Oct 24 13:17:17 2011 From: ckava1 at msn.com (Chris Kavanagh) Date: Mon, 24 Oct 2011 07:17:17 -0400 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: On 10/24/2011 4:40 AM, Alan Gauld wrote: > On 24/10/11 04:08, Chris Kavanagh wrote: > >> Thanks so much for the help Alan. . .I'm not trying to beat this >> question into the ground, LOL, but let me see if I can ask it a better >> way. > > Marc has already given a good answer, but I'll try a slightly different > approach to the same thing.... The differences are purely philosophical :-) > >> So we have {member.tell} as the last line of code. So trying to >> understand this piece of code, {member} the variable is considered an >> object? > > Almost. > > member is an object because it is an instance of a class. > We created instances of Teacher and Student (t and s) and put them in a > list (members) with this code: > > t = Teacher('Mrs. Shrividya', 40, 30000) > s = Student('Swaroop', 22, 75) > members = [t, s] > > Thus for member in members takes each object in the list and assigns it > to member. > > We can read {for member in members} as > > "Let member take on, in turn, each value in the collection members" > > And making it more explicit with a while loop: > > index = 0 > while index < len(members): > member = members[index] > member.tell() > index += 1 > > > Therefore we can combine it with a function {tell()} using dot > > notation?? Is this correct??? I haven't seen anything but an > > object combined with a function using dot notation. > > dot notation is how we access anything that is defined inside the class > definition. In this case there are only the __init__() and tell() > methods but there could be data attributes too. Furthermore we can add > data attributes to the objects by using the self parameter, as is done > in __init__() So we end up with the instance containing the attributes > defined at the class level (including those of its superclass) plus any > added by the __init__() method which is called when the object is > created (or instantiated). So for Teacher the attributes will be: > > __init__() > tell() > name - from SchoolMember.__init__() > age - ditto > salary - from Teacher.__init__() > > So we could have accessed any of those for the first iteration of the > loop because member was a Teacher instance (t) using: > > member.tell, member.name, member.age, member.salary > > But the last one would have broken for the second object in the list > since it was a student, which doesn't have a salary. So when dealing > with a list of objects we have to restrict the access via dot notation > to those attributes that are common to all objects in the collection - > usually the ones defined in the super class. > > Python doesn't care whether the attributes we access are data or > functions because in Python everything is an "object" (see Marc's post) > But by putting parentheses after the object name Python treats the named > object as a function (specifically a "callable" object) > > You can see this diffence at work in the interpreter if you > type this: > > >>> def f(): > ... return "Called f" > ... > >>> print f > > >>> print f() > Called f > > See the difference the () made? Without it we print the function object > called f. With it we print the result of calling the function f. > Thats quite a subtle concept and usually hard for beginners to grasp but > it is a very powerful concept and you will find it being used in > more advanced programs, especially GUI development. > > > So I'm trying to figure out how we can >> combine the variable {member} with the function {tell}. Hope this >> question makes sense to you, LOL. Thanks again. > > How we combine it is done inside Python as part of the magic of classes > and instantiation. Basically you can call any function defined inside a > class and Python will automatically assign the first parameter of that > function to the object instace that you are referencing at the time. > > Thus when we do > > for member in members: > member.tell() > > Python recognises that first time round member refers to the object t > which is an instanmce of Teacher. It then calls the tell() method within > the Teacher class definition and assigns t as the self parameter. > We could write it explicitly as: > > Teacher.tell(member) # where member is t > > On the second time round member is assigned to s and Python recognizes > that s in an instance of Student. So it calls Student.tell(member) where > member is s. > > The member.tell() notation is just a convenient way for us to write it > and allows Python to do the hard work of figuring out what kind of > object member is at any given time. > > [Aside: In true OOP speak we describe the process as "sending a message > to the object. Thus member.tell() sends the message "tell" to the object > "member" and the OOP framework invokes the corresponding method tell() > in the corresponding class. In some OOP languages you can use different > names for the messages and corresponding methods but in Python they are > the same so we just talk about calling the method.] > > HTH, > Yes, both of you gave great answers. I just couldn't get it straight in my head for some reason. And I do get it now. I just wasn't seeing {member} as an instance of a class. I guess because I'm used to seeing simple straightforward examples of classes & objects so far. Thank you guys so much for the help. You don't know how nice it is to be able to ask someone who is an expert a question, and get an answer! Thanks to everyone who contributes, I've learned a lot by reading others questions. And THANKS for providing this awesome service! I want to make sure you guys, especially Alan & Dave, are appreciated for taking their own personal time to do this, for free. From waynejwerner at gmail.com Mon Oct 24 13:45:46 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 24 Oct 2011 06:45:46 -0500 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: On Sun, Oct 23, 2011 at 11:06 PM, Marc Tompkins wrote: > Things to remember: > -you can get a value from a method, but you can't assign to it: > variable = object.method() > but NOT > object.method() = variable > As a slight aside, you _can_ assign to the method name: object.method = variable #object.method is now whatever variable was I'm not aware of any valid reason to do this, that is to say I don't know of anything that you could do this way that you couldn't do another more readable/maintainable way. But I could be wrong! HTH, -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From c2praveen30jun at gmail.com Mon Oct 24 15:10:03 2011 From: c2praveen30jun at gmail.com (Praveen Singh) Date: Mon, 24 Oct 2011 09:10:03 -0400 Subject: [Tutor] How to print corresponding keys in Dictionary Message-ID: In Dictionary- How to print corresponding keys if the values of dictionary is given?? -d={'a':1,'b':2,'c':3} -i can print the corresponding values by using get() method- - d.get('a') -1 What if i have to print reverse??? -------------- next part -------------- An HTML attachment was scrubbed... URL: From raulcumplido at gmail.com Mon Oct 24 15:18:11 2011 From: raulcumplido at gmail.com (=?ISO-8859-1?Q?Ra=FAl_Cumplido?=) Date: Mon, 24 Oct 2011 15:18:11 +0200 Subject: [Tutor] How to print corresponding keys in Dictionary In-Reply-To: References: Message-ID: Hi, Keys are unique in a dictionaire but values aren't. What do you want to print if you have the next dictionaire: dict = {'a' : 1, 'b' : 1} If you are using python 2.7 you can use dictionary comprehensions to swap keys for values: >>> d={'a':1,'b':2,'c':3} >>> new_dict = {v : k for k,v in d.iteritems()} >>> new_dict {1: 'a', 2: 'b', 3: 'c'} but if you're values are repeated you will loose some keys: >>> dict = {'a' : 1, 'b':1} >>> {v : k for k,v in dict.iteritems()} {1: 'b'} HTH, Ra?l On Mon, Oct 24, 2011 at 3:10 PM, Praveen Singh wrote: > In Dictionary- > How to print corresponding keys if the values of dictionary is given?? > > -d={'a':1,'b':2,'c':3} > -i can print the corresponding values by using get() method- > - d.get('a') > -1 > > What if i have to print reverse??? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Ra?l Cumplido -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Oct 24 15:18:14 2011 From: d at davea.name (Dave Angel) Date: Mon, 24 Oct 2011 09:18:14 -0400 Subject: [Tutor] How to print corresponding keys in Dictionary In-Reply-To: References: Message-ID: <4EA56596.3040503@davea.name> On 10/24/2011 09:10 AM, Praveen Singh wrote: > In Dictionary- > How to print corresponding keys if the values of dictionary is given?? > > -d={'a':1,'b':2,'c':3} > -i can print the corresponding values by using get() method- > - d.get('a') > -1 > > What if i have to print reverse??? > > A dictionary can be viewed as a mapping between keys and values, where you supply a key, and the dictionary quickly finds the corresponding value. To do the reverse, you have to construct the code yourself and it will be much smaller, if there are many items. For example (untested): d = {"a", 1, "b":2, "c":3, "d":2} def getkey(dictionary, value): for key, val in dictionary.items(): if val == value: return key Note that if there are multiple keys with the same value, my function would get only the first. It wouldn't be hard to modify the function to return a list of matching keys. -- DaveA From d at davea.name Mon Oct 24 18:52:24 2011 From: d at davea.name (Dave Angel) Date: Mon, 24 Oct 2011 12:52:24 -0400 Subject: [Tutor] How to print corresponding keys in Dictionary In-Reply-To: References: <4EA56596.3040503@davea.name> Message-ID: <4EA597C8.50307@davea.name> (You forgot to include the list on your reply. Easiest way is to do a reply-all when you're replying) On 10/24/2011 12:21 PM, Praveen Singh wrote: > On Mon, Oct 24, 2011 at 9:18 AM, Dave Angel wrote: > >> >> >> def getkey(dictionary, value): >> for key, val in dictionary.items(): >> if val == value: >> return key >> >> >> Note that if there are multiple keys with the same value, my function would >> get only the first. It wouldn't be hard to modify the function to return a >> list of matching keys. >> >> >> >> > Thanks DaveA!! i made this programme to return a list of matching > keys...thanks for this outline... > Can you hint me something in this problem??This is another problem.. > > >>>> invertDictionary({'a':1, 'b':2, 'c':3, 'd':2}) > {1: ['a'], 2: ['b', 'd'], 3: ['c']} > > def reverseLook(dictionary,value): > a=[] > d={} > for key,values in dictionary.iteritems(): > > d.update({values:a.append(key)}) // this line is not working// > print d > No idea what you're trying to do here. But maybe if you start by showing the getkeys() function you wrote for the last assignent, we can see if it's useful for doing this one. Also when you have multiple runtime errors in your program, and don't show us the stacktraces, we have to assume you haven't even tried the code. If I were to run that, I'd get an error calling a non-existent invertDictionary(). What do you mean "this line is not working" ? Is it crashing the machine, getting an error (show stacktrace), or just not doing the thing you expect? -- DaveA From alan.gauld at btinternet.com Mon Oct 24 19:56:46 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Oct 2011 18:56:46 +0100 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: On 24/10/11 11:17, lina wrote: > > > a quick Q: Every time call the method, need go through the __initi__( ) part? No. __init__() is only called when an instance is first created. Here is an example in the IDLE: >>> class C: def __init__(self): print("I'm in init") def method(self): print("I'm in method") >>> c = C() I'm in init >>> c.method() I'm in method >>> c2 = C().method() # calls init for C(), then the method I'm in init I'm in method >>> HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jmartiee at gmail.com Mon Oct 24 20:04:20 2011 From: jmartiee at gmail.com (Johan Martinez) Date: Mon, 24 Oct 2011 13:04:20 -0500 Subject: [Tutor] string immutability Message-ID: Hi, I am struggling to understand Python string immutability. I am able to modify Python string object after initializing/assigning it a value. So how does immutability work? I am not following it. Sorry for really stupid question. Any help? >>> s = "First" >>> print s.__class__ >>> print s First >>> s = "Second" >>> print s Second >>> jM. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 24 20:00:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Oct 2011 19:00:50 +0100 Subject: [Tutor] How to print corresponding keys in Dictionary In-Reply-To: <4EA56596.3040503@davea.name> References: <4EA56596.3040503@davea.name> Message-ID: On 24/10/11 14:18, Dave Angel wrote: > def getkey(dictionary, value): > for key, val in dictionary.items(): > if val == value: > return key > > > Note that if there are multiple keys with the same value, my function > would get only the first. It wouldn't be hard to modify the function to > return a list of matching keys. For fun: def getKeys(aDict, aValue): return [key for key,val in aDict if val == aValue] HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Mon Oct 24 20:45:10 2011 From: d at davea.name (Dave Angel) Date: Mon, 24 Oct 2011 14:45:10 -0400 Subject: [Tutor] string immutability In-Reply-To: References: Message-ID: <4EA5B236.5010202@davea.name> On 10/24/2011 02:04 PM, Johan Martinez wrote: > Hi, > > I am struggling to understand Python string immutability. I am able to > modify Python string object after initializing/assigning it a value. So how > does immutability work? I am not following it. Sorry for really stupid > question. Any help? You're confusing attributes and objects. When you say s = "First" two distinct things happen. An immutable object of type str is created, with an immutable value "First". And then the attribute s is bound to that object. s is not immutable at all. Then when you do s = "Second" you are creating a totally different immutable object, which s is now bound to. And behind the scenes, the first object is garbage collected. We all confuse this by referring to "variables," but they are not the same as "variables" in most other languages. They never have a value, they just refer to an object. And if you do t = s, you're not copying a value at all. You're just saying that t and s now are bound to (refer to) the same object. If the object is immutable, then you don't need the distinction. But if you mute the object, as opposed to creating a new one, both the attributes are still bound to the same object. Top-level (global) variables are attributes of the module. Local variables are attributes of the function. And instance variables (an incorrect term) are attributes of an instance, frequently referred to as obj.inst Going from the other end, an object may be bound to one place, two places, or many. And when it's bound to nothing, it gets garbage collected (sometimes ref-counted, but that disctinction refers to a particular implementation, not to the language Python). Those "places" I'm referring to may be attributes, so we see it as having "a name", but it may be bound to something without an explicit name, such as an element of a list. Ints, floats, and strings are immutable. So I guess the simplest object that's mutable is a list. You can modify the 3rd item in a list without affecting any of the "variables" that are bound to it. But when you use any of those variables, it'll appear to have a "new value." list1 = [3, 0, 44] list2= list1 list3 = [10, 12, 15, 22] list1[2] = 45 #mutates the list object bound to list1 #but list2 is bound to the same object print list2 #will now be [3, 0, 45] list2 = list3 #doesn't mutate any objects, it simply rebinds list2 from the first list object to the second one. HTH -- DaveA From sander.sweers at gmail.com Mon Oct 24 20:47:25 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 24 Oct 2011 20:47:25 +0200 Subject: [Tutor] string immutability In-Reply-To: References: Message-ID: <1319482045.31177.5.camel@Nokia-N900> On Mon, 24 Oct 2011, 20:04:20 CEST, Johan Martinez wrote: > I am struggling to understand Python string immutability. I am able to > modify Python string object after initializing/assigning it a value. So > how does immutability work? I am not following it. Sorry for really > stupid question. Any help? Mutibility means changinging the object (string) in place. What you are doing below is creating a new string and asigning it to a variable. > > > > > > s = "First" > > > > print s.__class__ > > > > > print s > First > > > > s = "Second" > > > > print s > Second > > > > > > If the object s reffernces is mutable you should be able to do: s[0] = 'x' Try it and see what happen. Then also try this with a list of strings s = ['f', 'i', 'r', 's', 't'] s[0] = 'x' Greets sander -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Oct 24 20:52:14 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 24 Oct 2011 13:52:14 -0500 Subject: [Tutor] string immutability In-Reply-To: References: Message-ID: On Mon, Oct 24, 2011 at 1:04 PM, Johan Martinez wrote: > Hi, > > I am struggling to understand Python string immutability. I am able to > modify Python string object after initializing/assigning it a value. So how > does immutability work? I am not following it. Sorry for really stupid > question. Any help? > > > > >>> s = "First" > >>> print s.__class__ > > >>> print s > First > >>> s = "Second" > This is not actually modifying the string object. Unlike most other programming languages where a variable refers to an actual location in memory (usually), in Python the variable names the actual value. So when you do s = "First" then you are telling python that you want to be able to refer to the string "First" by the name/variable s. When you execute s="Second" you are now telling python that instead of referring to "First" you want the name 's' to refer to the string "Second". If you try to modify the actual value of the string, you will raise an exception: >>> s = "First" >>> s[0] = "T" Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignment HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Mon Oct 24 20:34:51 2011 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 24 Oct 2011 11:34:51 -0700 Subject: [Tutor] string immutability In-Reply-To: References: Message-ID: <20111024183451.GA4802@dragon.alchemy.com> On Mon, Oct 24, 2011 at 01:04:20PM -0500, Johan Martinez wrote: > Hi, > > I am struggling to understand Python string immutability. I am able to > modify Python string object after initializing/assigning it a value. So how > does immutability work? I am not following it. Sorry for really stupid > question. Any help? No, you're actualy not. > >>> s = "First" > >>> print s > First At this point, you have created a string object with the value "First" and put that into the variable "s" (which is glossing over a detail about how Python variables realy work, but that's another topic). > >>> s = "Second" > >>> print s > Second Now you created a new string object with the value "Second" and stored THAT into s, replacing the original object, which is now lost. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From andreas.perstinger at gmx.net Mon Oct 24 21:07:49 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Mon, 24 Oct 2011 21:07:49 +0200 Subject: [Tutor] string immutability In-Reply-To: References: Message-ID: <4EA5B785.5000400@gmx.net> On 2011-10-24 20:04, Johan Martinez wrote: > Hi, > > I am struggling to understand Python string immutability. I am able to > modify Python string object after initializing/assigning it a value. > >>>> s = "First" >>>> print s.__class__ > >>>> print s > First >>>> s = "Second" >>>> print s > Second Dave, Sander and Wayne have already explained why you aren't modifying string objects in your example. With the id()-function you can also see what is happening: >>> s = "First" >>> id(s) 3077110080L # In CPython this is the memory address of the object # with the name 's' (in your case "First") >>> s = "Second" >>> id(s) 3077110304L # You see that 's' refers now to another address >>> id("First") 3077110080L # But "First" is still on the same address as before >>> id("Second") 3077110304L # And this proves that "Second" is at the address # which 's' refers to Bye, Andreas From jmartiee at gmail.com Mon Oct 24 21:17:08 2011 From: jmartiee at gmail.com (Johan Martinez) Date: Mon, 24 Oct 2011 14:17:08 -0500 Subject: [Tutor] string immutability In-Reply-To: References: Message-ID: On Mon, Oct 24, 2011 at 1:52 PM, Wayne Werner wrote: > On Mon, Oct 24, 2011 at 1:04 PM, Johan Martinez wrote: > >> Hi, >> >> I am struggling to understand Python string immutability. I am able to >> modify Python string object after initializing/assigning it a value. So how >> does immutability work? I am not following it. Sorry for really stupid >> question. Any help? >> >> >> >> >>> s = "First" >> >>> print s.__class__ >> >> >>> print s >> First >> >>> s = "Second" >> > > This is not actually modifying the string object. Unlike most other > programming languages where a variable refers to an actual location in > memory (usually), in Python the variable names the actual value. > > So when you do s = "First" then you are telling python that you want to be > able to refer to the string "First" by the name/variable s. > > When you execute s="Second" you are now telling python that instead of > referring to "First" you want the name 's' to refer to the string "Second". > > If you try to modify the actual value of the string, you will raise an > exception: > > >>> s = "First" > >>> s[0] = "T" > Traceback (most recent call last): > File "", line 1, in > TypeError: 'str' object does not support item assignment > > HTH, > Wayne > Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I realized my wrong understanding/interpretation after posting the message to the list, which usually happens most of the time with me! jM. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmartiee at gmail.com Mon Oct 24 21:21:44 2011 From: jmartiee at gmail.com (Johan Martinez) Date: Mon, 24 Oct 2011 14:21:44 -0500 Subject: [Tutor] string immutability In-Reply-To: <4EA5B785.5000400@gmx.net> References: <4EA5B785.5000400@gmx.net> Message-ID: On Mon, Oct 24, 2011 at 2:07 PM, Andreas Perstinger < andreas.perstinger at gmx.net> wrote: > On 2011-10-24 20:04, Johan Martinez wrote: > >> Hi, >> >> I am struggling to understand Python string immutability. I am able to >> modify Python string object after initializing/assigning it a value. >> >> s = "First" >>>>> print s.__class__ >>>>> >>>> >> >>> print s >>>>> >>>> First >> >>> s = "Second" >>>>> print s >>>>> >>>> Second >> > > Dave, Sander and Wayne have already explained why you aren't modifying > string objects in your example. > With the id()-function you can also see what is happening: > > >>> s = "First" > >>> id(s) > 3077110080L # In CPython this is the memory address of the object > # with the name 's' (in your case "First") > >>> s = "Second" > >>> id(s) > 3077110304L # You see that 's' refers now to another address > >>> id("First") > 3077110080L # But "First" is still on the same address as before > >>> id("Second") > 3077110304L # And this proves that "Second" is at the address > # which 's' refers to > > Bye, Andreas > Great, that's really helpful Andreas. thanks, jM. -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Mon Oct 24 21:24:54 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Mon, 24 Oct 2011 20:24:54 +0100 Subject: [Tutor] string immutability In-Reply-To: References: Message-ID: What you did here is just re-assigning s. Try slicing s and then assign a new value to the slice. s[2] would return 'r' now try to to set s[2] to another value to understand immutability. Hope it helps. On 24 Oct 2011 19:06, "Johan Martinez" wrote: > Hi, > > I am struggling to understand Python string immutability. I am able to > modify Python string object after initializing/assigning it a value. So how > does immutability work? I am not following it. Sorry for really stupid > question. Any help? > > > > >>> s = "First" > >>> print s.__class__ > > >>> print s > First > >>> s = "Second" > >>> print s > Second > >>> > > > > jM. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Mon Oct 24 21:32:12 2011 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 24 Oct 2011 12:32:12 -0700 Subject: [Tutor] string immutability In-Reply-To: References: Message-ID: <4EA5BD3C.2030308@alchemy.com> On 24-Oct-11 12:17, Johan Martinez wrote: > Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I > realized my wrong understanding/interpretation after posting the message > to the list, which usually happens most of the time with me! That happens to most of us all the time too :) Unfortunately, with the lag between posting to the list and mail getting out to everyone, you'll probably get several replies that all say the same thing--we're not piling up on you, it's just a bunch of people being helpful without seeing that someone already answered yet. Glad we could help. Looking more into how Python variables work unlocks a lot of potential for all sorts of data structure operations that other languages require pointers to do, but are a lot easier when essentially all "variables" are references to objects but with the details handled behind the scenes for you. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From d at davea.name Mon Oct 24 21:33:52 2011 From: d at davea.name (Dave Angel) Date: Mon, 24 Oct 2011 15:33:52 -0400 Subject: [Tutor] string immutability In-Reply-To: References: <4EA5B785.5000400@gmx.net> Message-ID: <4EA5BDA0.7030800@davea.name> On 10/24/2011 03:21 PM, Johan Martinez wrote: > On Mon, Oct 24, 2011 at 2:07 PM, Andreas Perstinger< > andreas.perstinger at gmx.net> wrote: > >> On 2011-10-24 20:04, Johan Martinez wrote: >> >>> Hi, >>> >>> I am struggling to understand Python string immutability. I am able to >>> modify Python string object after initializing/assigning it a value. >>> >>> s = "First" >>>>>> print s.__class__ >>>>>> >>>>> >>>> print s >>>>> First >>>> s = "Second" >>>>>> print s >>>>>> >>>>> Second >> Dave, Sander and Wayne have already explained why you aren't modifying >> string objects in your example. >> With the id()-function you can also see what is happening: >> >>>>> s = "First" >>>>> id(s) >> 3077110080L # In CPython this is the memory address of the object >> # with the name 's' (in your case "First") >>>>> s = "Second" >>>>> id(s) >> 3077110304L # You see that 's' refers now to another address >>>>> id("First") >> 3077110080L # But "First" is still on the same address as before >>>>> id("Second") >> 3077110304L # And this proves that "Second" is at the address >> # which 's' refers to >> >> Bye, Andreas >> > Great, that's really helpful Andreas. > > thanks, > jM. > Unfortunately, that trick is not guaranteed to work. The only reason that id("First") gives the same value as s="First"; id(s) is that "First" is one of the few magic values that get cached. Small non-negative integers and short strings without spaces tend to be in that category, but you can't count on it. Try a = 400 b = 400 print id(a), id(b) it'll probably print different numbers, if the value 400 isn't one of the "cached" values. Worse is that an id() can be reused once an object is garbage collected. So I could do something like: a = 600 print id(a) del a b = 400 print id(b) and it might print the same value. There are more subtle cases, but I wanted to keep it simple. An id() is guaranteed to be unique across all objects that exist at the same moment. So as long as you're comparing id's of two objects that are both present, you're fine. I'm afraid to really understand id(), you have to understand how the object model works, so you can't use id() to prove it. -- DaveA From jmartiee at gmail.com Mon Oct 24 21:52:02 2011 From: jmartiee at gmail.com (Johan Martinez) Date: Mon, 24 Oct 2011 14:52:02 -0500 Subject: [Tutor] string immutability In-Reply-To: <4EA5BD3C.2030308@alchemy.com> References: <4EA5BD3C.2030308@alchemy.com> Message-ID: On Mon, Oct 24, 2011 at 2:32 PM, Steve Willoughby wrote: > On 24-Oct-11 12:17, Johan Martinez wrote: > >> Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I >> realized my wrong understanding/interpretation after posting the message >> to the list, which usually happens most of the time with me! >> > > That happens to most of us all the time too :) Unfortunately, with the lag > between posting to the list and mail getting out to everyone, you'll > probably get several replies that all say the same thing--we're not piling > up on you, it's just a bunch of people being helpful without seeing that > someone already answered yet. > > Glad we could help. Looking more into how Python variables work unlocks a > lot of potential for all sorts of data structure operations that other > languages require pointers to do, but are a lot easier when essentially all > "variables" are references to objects but with the details handled behind > the scenes for you. > > -- > Steve Willoughby / steve at alchemy.com > "A ship in harbor is safe, but that is not what ships are built for." > PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C Actually it's good to see so many replies and different methods and explanations here. Also, is there any doc link where I can find all the information about String object - class and instance methods. Google pointed me to following two links, but that wasn't helpful for finding instance method for finding length of a string object (rather than using 'len' function). - http://docs.python.org/library/string.html - http://docs.python.org/library/stdtypes.html#string-methods Finally I figured it out ( __length__() ) thanks to ipython shell env. But is there any online documentation or interactive reference like ruby-ri? jM. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Oct 24 23:48:44 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 24 Oct 2011 17:48:44 -0400 Subject: [Tutor] string immutability In-Reply-To: References: <4EA5BD3C.2030308@alchemy.com> Message-ID: the len() function works on lots of objects: >>> a = "this is a string" >>> len(a) 16 On Mon, Oct 24, 2011 at 3:52 PM, Johan Martinez wrote: > > > On Mon, Oct 24, 2011 at 2:32 PM, Steve Willoughby wrote: > >> On 24-Oct-11 12:17, Johan Martinez wrote: >> >>> Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I >>> realized my wrong understanding/interpretation after posting the message >>> to the list, which usually happens most of the time with me! >>> >> >> That happens to most of us all the time too :) Unfortunately, with the >> lag between posting to the list and mail getting out to everyone, you'll >> probably get several replies that all say the same thing--we're not piling >> up on you, it's just a bunch of people being helpful without seeing that >> someone already answered yet. >> >> Glad we could help. Looking more into how Python variables work unlocks a >> lot of potential for all sorts of data structure operations that other >> languages require pointers to do, but are a lot easier when essentially all >> "variables" are references to objects but with the details handled behind >> the scenes for you. >> >> -- >> Steve Willoughby / steve at alchemy.com >> "A ship in harbor is safe, but that is not what ships are built for." >> PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C > > > Actually it's good to see so many replies and different methods and > explanations here. > > Also, is there any doc link where I can find all the information about > String object - class and instance methods. Google pointed me to following > two links, but that wasn't helpful for finding instance method for finding > length of a string object (rather than using 'len' function). > > - http://docs.python.org/library/string.html > - http://docs.python.org/library/stdtypes.html#string-methods > > Finally I figured it out ( __length__() ) thanks to ipython shell env. But > is there any online documentation or interactive reference like ruby-ri? > > jM. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Oct 25 00:05:39 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 25 Oct 2011 09:05:39 +1100 Subject: [Tutor] reg current work in pycrypto In-Reply-To: References: Message-ID: <4EA5E133.9010708@pearwood.info> nivedita datta wrote: > Hi all, > > Can anyone tell me about some projects or applications which has been built > using pycrypto. Also I would like to know about any ongoing/past project or > application development in pycrypto. This is a mailing list for beginners learning the basics of Python programming, not for arbitrary questions about third-party advanced cryptography libraries. You might be lucky to find someone here who happens to have used pycrypto, but I would be surprised if it happens. You would be better off asking on any pycrypto mailing lists or other forums. If all else fails, try the main Python discussion list, comp.lang.python. -- Steven From nozarm at triumf.ca Tue Oct 25 00:40:18 2011 From: nozarm at triumf.ca (Mina Nozar) Date: Mon, 24 Oct 2011 15:40:18 -0700 Subject: [Tutor] regex and parsing through a semi-csv file In-Reply-To: References: <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C9DF0.8040805@triumf.ca> Message-ID: <4EA5E952.6000103@triumf.ca> Hi Marc, Thank you. Following some of your suggestion, the rewrite below worked. I agree with your point on readability over complexity. By grace I meant not convoluted or simpler. That's all. As a beginner, I find not knowing all the existing functions, I end up re-inventing the wheel sometimes. Cheers, Mina ==== isotope_name,isotope_A = args.isotope.split('-') print isotope_name, isotope_A found_isotope = False activity_time = [] activity = [] activity_err = [] f = open(args.fname, 'r') lines = f.readlines() f.close() for i, line in enumerate(lines): line = line.strip() if isotope_name in line and isotope_A in line: found_isotope = True print 'found isotope' #print line lines = lines[i+1:] break for line in lines: line = line.strip() if not line[0].isdigit(): break print 'found' words = line.split(',') activity_time.append(float(words[0])) activity.append(float(words[1])) activity_err.append(float(words[2])) On 11-10-19 12:06 PM, Marc Tompkins wrote: > On Wed, Oct 5, 2011 at 11:12 AM, Mina Nozar > wrote: > > Now, I would like to parse through this code and fill out 3 lists: 1) activity_time, 2) activity, 3) error, and plot > the activities as a function of time using matplotlip. My question specifically is on how to parse through the > lines containing the data (activity time, activity, error) for a given isotope, stopping before reaching the next > isotope's info. > > > Regular expressions certainly are terse, but (IMHO) they're really, really hard to debug and maintain; I find I have to > get myself into a Zen state to even unpack them, and that just doesn't feel very Pythonic. > > Here's an approach I've used in similar situations (a file with arbitrary sequences of differently-formatted lines, > where one line determines the "type" of the lines that follow): > - create a couple of status variables: currentElement, currentIsotope > - read each line and split it into a list, separating on the commas > - look at the first item on the line: is it an element? (You could use a list of the 120 symbols, or you could just > check to see if it's alphabetic...) > - if the first item is an element, then set currentElement and currentIsotope, move on to next line. > - if the first item is NOT an element, then this is a data line. > - if currentElement and currentIsotope match what the user asked for, > - add time, activity, and error to the appropriate lists > - if not, move on. > > This approach also works in the event that the data wasn't all collected in order - i.e. there might be data for Ag111 > followed by U235 followed by Ag111 again. > > Note that the size of the lists will change depending on the number of activities for a given run of the simulation > so I don't want to hard code '13' as the number of lines to read in followed by the line containing isotope_name, etc. > > > This should work for any number of lines or size of file, as long as the data lines are all formatted as you expect. > Obviously a bit of error-trapping would be a good thing.... > > If there is a more graceful way of doing this, please let me know as well. I am new to python... > > For me, readability and maintainability trump "grace" every time. Nobody's handing out awards for elegance (outside of > the classroom), but complexity gets punished (with bugs and wasted time.) More elegant solutions might also run faster, > but remember that premature optimization is a Bad Thing. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From bgailer at gmail.com Tue Oct 25 00:44:51 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 24 Oct 2011 18:44:51 -0400 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: <4EA5EA63.8070907@gmail.com> On 10/24/2011 7:45 AM, Wayne Werner wrote: > On Sun, Oct 23, 2011 at 11:06 PM, Marc Tompkins > > wrote: > > Things to remember: > -you can get a value from a method, but you can't assign to it: > variable = object.method() > but NOT > object.method() = variable > > > As a slight aside, you _can_ assign to the method name: > > object.method = variable #object.method is now whatever variable was > > I'm not aware of any valid reason to do this, that is to say I don't > know of anything that you could do this way that you couldn't do > another more readable/maintainable way. In my Python Pipelines program I deliberately reassign instance methods. Example: Given a (trivial) pipeline specification: "< foo.txt | > goo.txt" meaning: "open foo.txt, open goo.txt, read one record at a time from foo.txt, write it to goo.txt, at end close both files." The specification parser creates an instance of ReadFile and an instance of WriteFile, It must then "connect" these two instances, such that the output of the first goes to the input of the second. The IMHO easiest way to do this: instance1.output = instance2.input where output and input are methods. I've had other cases where the __init__method of a class determines some behaviors by assigning one of several methods to a particular method. I've had yet other cases where I swap methods during the first call, such that subsequent calls have different behavior. All of these could be done differently, but reassigning methods makes the most sense to me. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Oct 25 00:50:33 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 24 Oct 2011 18:50:33 -0400 Subject: [Tutor] How to print corresponding keys in Dictionary In-Reply-To: <4EA597C8.50307@davea.name> References: <4EA56596.3040503@davea.name> <4EA597C8.50307@davea.name> Message-ID: <4EA5EBB9.1050608@gmail.com> Another approach is to subclass dict such that each time you add a key:value pair you also create an entry in a reverse dictionary. Then all you need do is lookup in the reverse dictionary. If there are several keys with the same value, then create and extend a list of values in the reverse dictionary. This will fail (as any other reverse dictionary approach will) if the values are not hashable -- Bob Gailer 919-636-4239 Chapel Hill NC From g.nius.ck at gmail.com Tue Oct 25 01:02:28 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Mon, 24 Oct 2011 19:02:28 -0400 Subject: [Tutor] Quacks like an object Message-ID: Dear Tutors, I am trying to make an object, which will appear exactly like an object of my choice. It will should be impossible to tell it is not the object. This is because I am making an object that modifies it methods so that if the methods make a change to the object, it will sync those changes to a file, but I don't want it to be another object, so foreign functions will not mistake for not being the object. For example if, I used type on the object, it should return the class of the object it is trying to mimic. I have tried everything from modifying the object's get set attribute methods, to having making a new object that has get and set the same as the object except with a filter for methods, but I had no luck. In a nutshell, I want an object that walks like another object, quacks like another object, and basically is another object. Is this possible? Sincerely, Me -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Oct 25 01:48:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Oct 2011 00:48:05 +0100 Subject: [Tutor] How to print corresponding keys in Dictionary In-Reply-To: References: <4EA56596.3040503@davea.name> Message-ID: On 24/10/11 19:00, Alan Gauld wrote: > For fun: > > def getKeys(aDict, aValue): > return [key for key,val in aDict if val == aValue] Oops, that should have been return [key for key,val in aDict.items() if val == aValue] -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Oct 25 01:56:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Oct 2011 00:56:56 +0100 Subject: [Tutor] string immutability In-Reply-To: References: <4EA5BD3C.2030308@alchemy.com> Message-ID: On 24/10/11 20:52, Johan Martinez wrote: > Also, is there any doc link where I can find all the information about > String object - class and instance methods. >>> help(str) or even >>> help("") For a quick list try dir() >>> dir ("") > Finally I figured it out ( __length__() ) thanks to ipython shell env. len(x) gets converted to x.__length__() by Python. So you can make any object work with len() by providing a __length__() method. Similarly you can make any object into a string by providing a __str__() metjod and then str(obj) will work (as will print (obj) ) There are a bunch of these "magic" methods that you can provide to help make your objects appear more like the standard built in objects. > But is there any online documentation or interactive reference like > ruby-ri? There are various help browsers for Python. The one that comes with ActiveState Python for Windows is quite good IMHO and integrates with Windows Help too. But personally I just use dir() and help() and Google... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Oct 25 02:06:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Oct 2011 01:06:33 +0100 Subject: [Tutor] Quacks like an object In-Reply-To: References: Message-ID: On 25/10/11 00:02, Christopher King wrote: > Dear Tutors, > I am trying to make an object, which will appear exactly like an > object of my choice. It will should be impossible to tell it is not the > object. We can get pretty close but I suspect its impossible to make it 100% reliable - otherwise Python itself would get confused! > This is because I am making an object that modifies it methods > so that if the methods make a change to the object, it will sync those > changes to a file, but I don't want it to be another object, > so foreign functions will not mistake for not being the object. Sorry that bit lost me! You want to persist data changes to a file? Thats easy enough. But the last two lines sem disconnected fro the saving to file bit? > For example if, I used type on the object, it should return > the class of the object it is trying to mimic. And presumably isinstance() too? > but I had no luck. In a nutshell, I want an object that walks like > another object, quacks like another object, and basically is another > object. But basically is NOT another object I think you mean. If you really want it to be the other object then just make another instance cloning the attributes. But I don;t think thats really what you want? > Is this possible? If you are prepared to spend a lot of time implementing all the meta methods etc then you should be able to get pretty close. But it will be tedious. I suspect there will almost certainly be a better solution if we understood the actual problem you are trying to solve. (The facade design pattern sounds likely for example!) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ckava1 at msn.com Tue Oct 25 06:20:33 2011 From: ckava1 at msn.com (Chris Kavanagh) Date: Tue, 25 Oct 2011 00:20:33 -0400 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: On 10/24/2011 12:06 AM, Marc Tompkins wrote: > On Sun, Oct 23, 2011 at 8:08 PM, Chris Kavanagh > wrote: > > So we have {member.tell} as the last line of code. So trying to > understand this piece of code, {member} the variable is considered > an object? Therefore we can combine it with a function {tell()} > using dot notation?? Is this correct??? I haven't seen anything but > an object combined with a function using dot notation. When I say > "object", I mean an "object" created from a class. So I'm trying to > figure out how we can combine the variable {member} with the > function {tell}. Hope this question makes sense to you, LOL. Thanks > again. > > > First of all: other languages distinguish between variables and objects, > and between functions and objects, but in Python both variables and > functions are objects. EVERYTHING is an object. This is an important > thing to remember - even if you never create classes of your own (which > would be a terrible waste, BTW) a lot of the language won't make sense > unless you remember that everything's an object. > > Second, the line "members = [t, s]" creates a list "members" (which is > also an object, by the way!) containing two objects - "t" is a Teacher, > "s" is a Student - which are both subclassed from SchoolMember. > The line "for member in members" means: step through the list "members" > and work with each object we find in it; let's call that object "member" > while we're working with it. As soon as we finish with the first object > and move on to the next, call the next one "member" - and so on. The > beauty of this approach is that it simply doesn't matter what the > contents of the list are - one could be a Student, the next a > WoollyMammoth - and as long as your code only references methods and > attributes that work for all the items in the list, Python won't care. > > Third, dot notation: objects have "methods" (which in non-OOP contexts > would be called "functions") and "attributes" (variables, more or > less.) From outside of the class definition, you refer to the object's > attributes like so: > variable = object.attribute # if you want to read the attribute's > current value > or > object.attribute = variable # if you want to set the attribute to a > new value > > and to its methods like so: > variable = object.method(parameter1, parameter2, etc) > > Like all functions, methods can take a fixed number of parameters, an > optional bunch of named parameters, or no parameters at all; they may > return a value or they may not; you may want to use that value, or > ignore it. > > Things to remember: > -you can get a value from a method, but you can't assign to it: > variable = object.method() > but NOT > object.method() = variable > > -the only visible difference between reading an attribute and calling a > method with no parameters is the parentheses at the end. Don't forget > them, and don't be misled by the similarity. > > Hope that helps... > Thanks so much for the explanation Marc! My problem was, I wasn't seeing {member} as referring to the class objects {t} and {s}. Since it was, we now can use member just like any class object, and combine it with class functions (and class variables), such as {member.tell}. I had never in my short programming experience, seen an example like this. So I was confused, obviously, LOL. Makes perfect sense now. . .Thanks again Marc (and Alan, Dave) BTW, do you guys luv Python the way I do!?? I just luv the way everything works together so explicitly. I LUV learning this stuff!! From marc.tompkins at gmail.com Tue Oct 25 06:46:19 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 24 Oct 2011 21:46:19 -0700 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: On Mon, Oct 24, 2011 at 9:20 PM, Chris Kavanagh wrote: > Makes perfect sense now. . .Thanks again Marc (and Alan, Dave) > BTW, do you guys luv Python the way I do!?? I just luv the way everything > works together so explicitly. I LUV learning this stuff!! > Oh yeah, baby. Python makes programming fun again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Oct 25 06:53:57 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 24 Oct 2011 21:53:57 -0700 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: <4EA5EA63.8070907@gmail.com> References: <4EA4939A.2070602@davea.name> <4EA5EA63.8070907@gmail.com> Message-ID: On Mon, Oct 24, 2011 at 3:44 PM, bob gailer wrote: > On 10/24/2011 7:45 AM, Wayne Werner wrote: > > On Sun, Oct 23, 2011 at 11:06 PM, Marc Tompkins wrote: > >> Things to remember: >> -you can get a value from a method, but you can't assign to it: >> variable = object.method() >> but NOT >> object.method() = variable >> > > As a slight aside, you _can_ assign to the method name: > > object.method = variable #object.method is now whatever variable was > > I'm not aware of any valid reason to do this, that is to say I don't know > of anything that you could do this way that you couldn't do another more > readable/maintainable way. > > > In my Python Pipelines program I deliberately reassign instance methods. > Example: > > Given a (trivial) pipeline specification: "< foo.txt | > goo.txt" > meaning: "open foo.txt, open goo.txt, read one record at a time from > foo.txt, write it to goo.txt, at end close both files." > The specification parser creates an instance of ReadFile and an instance of > WriteFile, It must then "connect" these two instances, such that the output > of the first goes to the input of the second. The IMHO easiest way to do > this: instance1.output = instance2.input where output and input are methods. > > I've had other cases where the __init__method of a class determines some > behaviors by assigning one of several methods to a particular method. > > I've had yet other cases where I swap methods during the first call, such > that subsequent calls have different behavior. > > All of these could be done differently, but reassigning methods makes the > most sense to me. > As Einstein said, "Everything should be made as simple as possible, but not simpler." I also reassign methods (it's not my first choice, but sometimes it's the best way to do what I want to do) but I thought it would muddy the waters if I brought it up. I apologize for over-simplifying. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Oct 25 09:50:22 2011 From: d at davea.name (Dave Angel) Date: Tue, 25 Oct 2011 03:50:22 -0400 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: <4EA66A3E.6010701@davea.name> On 10/25/2011 12:20 AM, Chris Kavanagh wrote: > > > On 10/24/2011 12:06 AM, Marc Tompkins wrote: >> On Sun, Oct 23, 2011 at 8:08 PM, Chris Kavanagh > > > My problem was, I wasn't seeing {member} as referring to the class > objects {t} and {s}. Since it was, we now can use member just like any > class object, and combine it with class functions (and class > variables), such as {member.tell}. I had never in my short programming > experience, seen an example like this. So I was confused, obviously, LOL. > In the context of: t = Teacher('Mrs. Shrividya', 40, 30000) s = Student('Swaroop', 22, 75) members = [t, s] for member in members; member.dosomething() member does not refer to t and s at all. It refers to the same object as t and as s, in succession. members is a list of references to objects. Each item in members is bound to a particular object. It is not bound in any way to s or t. For example, suppose we did: members = [t, s] t = 42 for member in members: member.dosomething() member still references the object holding Mrs. Shrividya, or Swaroop, in succession, even though t is now (bound to) an integer (object). -- DaveA From steve at pearwood.info Tue Oct 25 10:07:09 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 25 Oct 2011 19:07:09 +1100 Subject: [Tutor] Quacks like an object In-Reply-To: References: Message-ID: <20111025080652.GB16181@ando> On Mon, Oct 24, 2011 at 07:02:28PM -0400, Christopher King wrote: > Dear Tutors, > I am trying to make an object, which will appear exactly like an object > of my choice. It will should be impossible to tell it is not the object. Can't be done in Python. The only way to make something absolutely indistinguishable from another thing is to actually make them the same thing. > This is because I am making an object that modifies it methods so that if > the methods make a change to the object, it will sync those changes to a > file, but I don't want it to be another object, so foreign functions will > not mistake for not being the object. Unfortunately, some functions are excessively finicky about their input. When writing a function, the author can: (1) Just Try It, and if it fails, deal with the failure. Dealing with the failure may mean "do nothing, just let the exception happen", or it may mean catching the exception and do something else. (2) Check for an interface first, then perform the task, e.g.: if hasattr(obj, '__getitem__'): x = obj[i] (3) Check the type using isinstance, which supports subtypes: if isinstance(obj, list): x = obj[i] (4) Check for an exact type, which defeats subtyping: if type(obj) is list: x = obj[i] There is very little you can do with functions that take the last approach, except report it back to the author as a bug. > For example > if, I used type on the object, it should return the class of the object it > is trying to mimic. I have tried everything from modifying the object's get > set attribute methods, to having making a new object that has get and set > the same as the object except with a filter for methods, but I had no luck. > In a nutshell, I want an object that walks like another object, quacks like > another object, and basically is another object. Is this possible? No. You have misunderstood duck typing. With duck typing, if your object swims like a duck and walks like a duck and quacks like a duck, who cares if it's actually a goose? The only way to make it exactly the same as a duck is if it actually is a duck. But you can get pretty close. The usual two approaches are: (A) Delegation. Something like this (untested): class Wrapper: def __init__(self, obj): self['_obj'] = obj def __getattr__(self, attr): return getattr(self._obj, attr) def __delattr__(self, attr): delattr(self._obj, attr) def __setattr__(self, attr, value): setattr(self._obj, attr, value) def spam(self, arg): # Save to a file somefile.write("whatever") self._obj.spam(arg) # Call the original. Delegation works really well for functions that don't use isinstance or type checking. (B) Inheritence. class MySpam(Spam): # Subclass of Spam that saves to a file. def spam(self, arg): somefile.write("whatever") super(MySpam, self).spam(arg) Does this help? -- Steven From steve at pearwood.info Tue Oct 25 10:23:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 25 Oct 2011 19:23:34 +1100 Subject: [Tutor] string immutability In-Reply-To: References: <4EA5BD3C.2030308@alchemy.com> Message-ID: <20111025082334.GC16181@ando> On Tue, Oct 25, 2011 at 12:56:56AM +0100, Alan Gauld wrote: > On 24/10/11 20:52, Johan Martinez wrote: > >Finally I figured it out ( __length__() ) thanks to ipython shell env. > > len(x) > > gets converted to x.__length__() by Python. That's actually __len__ not __length__. >>> [].__length__ Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object has no attribute '__length__' >>> [].__len__ > But personally I just use dir() and help() and Google... If you use dir() a lot, you might find this useful: http://code.activestate.com/recipes/577774-enhancing-dir-with-globs/ -- Steven From apometron.listas.cinco at gmail.com Tue Oct 25 10:24:22 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Tue, 25 Oct 2011 06:24:22 -0200 Subject: [Tutor] What is wrong with my code? In-Reply-To: References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> Message-ID: <4EA67236.5040907@gmail.com> I did it very much times, Anssi. Beyond of run it on Python 2.7 latest build, what do you suggest? Do install Python 3.2 along the Python 2.7 installation could give me any problems? cheers, Apometron http://about.me/apometron On 10/25/2011 6:11 AM, Anssi Saari wrote: > apometron writes: > >> Now it is another >> thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py >> dont works? > Well, Rename3.py works for me, even in Windows 7. Maybe you should test > it again? From d at davea.name Tue Oct 25 11:34:11 2011 From: d at davea.name (Dave Angel) Date: Tue, 25 Oct 2011 05:34:11 -0400 Subject: [Tutor] What is wrong with my code? In-Reply-To: <4EA67236.5040907@gmail.com> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA67236.5040907@gmail.com> Message-ID: <4EA68293.9070805@davea.name> (Once again, please don't top-post. It makes your responses out of order) On 10/25/2011 04:24 AM, apometron wrote: > I did it very much times, Anssi. > > Beyond of run it on Python 2.7 latest build, what do you suggest? > > Do install Python 3.2 along the Python 2.7 installation could give me > any problems? > Why don't you say publicly that you aren't using cmd ? If your file manager is not running the equivalent of python yourprogram.py filename.txt then everyone here is chasing a wild goose. Switch to the command line, issue a sequence of commands that cause the failure, and paste them in a message here. Then if it works, but doesn't from your file manager, you/we/they can address the differences from the working command line. -- DaveA From apometron.listas.cinco at gmail.com Tue Oct 25 12:09:38 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Tue, 25 Oct 2011 08:09:38 -0200 Subject: [Tutor] What is wrong with my code? In-Reply-To: <4EA68293.9070805@davea.name> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA67236.5040907@gmail.com> <4EA68293.9070805@davea.name> Message-ID: <4EA68AE2.2080309@gmail.com> On 10/25/2011 7:34 AM, Dave Angel wrote: > (Once again, please don't top-post. It makes your responses out of > order) > > On 10/25/2011 04:24 AM, apometron wrote: >> I did it very much times, Anssi. >> >> Beyond of run it on Python 2.7 latest build, what do you suggest? >> >> Do install Python 3.2 along the Python 2.7 installation could give me >> any problems? >> > > Why don't you say publicly that you aren't using cmd ? > > If your file manager is not running the equivalent of > > > python yourprogram.py filename.txt > > > then everyone here is chasing a wild goose. > > Switch to the command line, issue a sequence of commands that cause > the failure, and paste them in a message here. Then if it works, but > doesn't from your file manager, you/we/they can address the > differences from the working command line. > I found out what it is. It is the File Commander giving wrong informations to the script. In Take Command command line it works sweet. I will show all this to the File Commander author and ask him some way to solve this. It turns out do the thing in command line every time is not best way. I need do it by the file manager. But the file manager was puting stones in the way. Take Command has a script language also, but I would like do the things in Python, if possible. And this difficulty with File Commander makes use Python a thing less easy to do. Question solved. It was not Take Command the problem and I was sure it was not. Enter in command line to do things is a pain. =( I mean, e-ve-ry ti-me. But then, good news, all the three scripts works smoothly in the command line. Do you believe drag and drop in the Windows Explorer can be my salvation? Cool thing to try. []s Apometron http://about.me/apometron From ckava1 at msn.com Tue Oct 25 14:31:19 2011 From: ckava1 at msn.com (Chris Kavanagh) Date: Tue, 25 Oct 2011 08:31:19 -0400 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: <4EA66A3E.6010701@davea.name> References: <4EA4939A.2070602@davea.name> <4EA66A3E.6010701@davea.name> Message-ID: On 10/25/2011 3:50 AM, Dave Angel wrote: > On 10/25/2011 12:20 AM, Chris Kavanagh wrote: >> >> >> On 10/24/2011 12:06 AM, Marc Tompkins wrote: >>> On Sun, Oct 23, 2011 at 8:08 PM, Chris Kavanagh >> >> >> My problem was, I wasn't seeing {member} as referring to the class >> objects {t} and {s}. Since it was, we now can use member just like any >> class object, and combine it with class functions (and class >> variables), such as {member.tell}. I had never in my short programming >> experience, seen an example like this. So I was confused, obviously, LOL. >> > > In the context of: > > t = Teacher('Mrs. Shrividya', 40, 30000) > s = Student('Swaroop', 22, 75) > members = [t, s] > > for member in members; > member.dosomething() > > member does not refer to t and s at all. It refers to the same object as > t and as s, in succession. members is a list of references to objects. > Each item in members is bound to a particular object. It is not bound in > any way to s or t. > > For example, suppose we did: > > members = [t, s] > t = 42 > for member in members: > member.dosomething() > > member still references the object holding Mrs. Shrividya, or Swaroop, > in succession, even though t is now (bound to) an integer (object). > > I understand. . .Thanks for clearing that up for me Dave. So much to learn, so little time! LOL. Thanks again to everyone, it's much appreciated. From kellyadrian at hotmail.com Tue Oct 25 15:45:50 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Tue, 25 Oct 2011 13:45:50 +0000 Subject: [Tutor] printing a key not a value Message-ID: if i have a dictionary called definitions is there a way of printing the keys and not the values that go with them? thanks so much Adrian -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Tue Oct 25 15:54:52 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Tue, 25 Oct 2011 13:54:52 +0000 Subject: [Tutor] printing a key not a value In-Reply-To: References: Message-ID: <1328549462-1319550899-cardhu_decombobulator_blackberry.rim.net-1327492009-@b4.c12.bise7.blackberry> Sure, mydict = {'a':1, 'b',2} for key in mydict: print key Hope this helps, Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: ADRIAN KELLY Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Tue, 25 Oct 2011 13:45:50 To: Subject: [Tutor] printing a key not a value _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From delegbede at dudupay.com Tue Oct 25 15:59:52 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Tue, 25 Oct 2011 14:59:52 +0100 Subject: [Tutor] printing a key not a value In-Reply-To: <1328549462-1319550899-cardhu_decombobulator_blackberry.rim.net-1327492009-@b4.c12.bise7.blackberry> References: <1328549462-1319550899-cardhu_decombobulator_blackberry.rim.net-1327492009-@b4.c12.bise7.blackberry> Message-ID: >>> definitions = {'name':'dipo','food':'spaghetti','age':30,'location':'lagos'} >>> definitions.keys() ['food', 'age', 'name', 'location'] >>> definitions.values() ['spaghetti', 30, 'dipo', 'lagos'] >>> You can do this to get what you want. Hope it helps. On Tue, Oct 25, 2011 at 2:54 PM, wrote: > Sure, > > mydict = {'a':1, 'b',2} > for key in mydict: > print key > > Hope this helps, > Bodsda > Sent from my BlackBerry? wireless device > > -----Original Message----- > From: ADRIAN KELLY > Sender: tutor-bounces+bodsda=googlemail.com at python.org > Date: Tue, 25 Oct 2011 13:45:50 > To: > Subject: [Tutor] printing a key not a value > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Oct 25 16:02:24 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 25 Oct 2011 10:02:24 -0400 Subject: [Tutor] printing a key not a value In-Reply-To: References: Message-ID: On Tue, Oct 25, 2011 at 9:45 AM, ADRIAN KELLY wrote: > if i have a dictionary called definitions is there a way of printing the > keys and not the values that go with them? > > thanks so much > > > > Adrian > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > The python.org documentation is a good place to learn about dictionaries. http://docs.python.org/library/stdtypes.html#mapping-types-dict As it turns out, you can iterate over the keys of a dictionary: >>> definitions = {'k1':'k1 value', 'k2': 'k2 value'} >>> for k in definitions: ... print k ... k2 k1 -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue Oct 25 17:02:59 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 25 Oct 2011 11:02:59 -0400 Subject: [Tutor] regex and parsing through a semi-csv file In-Reply-To: <4EA5E952.6000103@triumf.ca> References: <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C9DF0.8040805@triumf.ca> <4EA5E952.6000103@triumf.ca> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDEECF8EF@EMARC112VS01.exchad.jpmchase.net> >f = open(args.fname, 'r') >lines = f.readlines() >f.close() If you are using Python 2.6+ you can use a context manager to automatically close the file. That way you never have to worry about closing any files! with open(args.fname, 'r') as f: lines = f.readlines() Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From nozarm at triumf.ca Tue Oct 25 19:38:31 2011 From: nozarm at triumf.ca (Mina Nozar) Date: Tue, 25 Oct 2011 10:38:31 -0700 Subject: [Tutor] regex and parsing through a semi-csv file In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDEECF8EF@EMARC112VS01.exchad.jpmchase.net> References: <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8C9DF0.8040805@triumf.ca> <4EA5E952.6000103@triumf.ca> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDEECF8EF@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4EA6F417.10608@triumf.ca> Thank you Ramit. I updated my code since I am running 2.7.1+ on Ubuntu. Best wishes, Mina On 11-10-25 08:02 AM, Prasad, Ramit wrote: >> f = open(args.fname, 'r') >> lines = f.readlines() >> f.close() > > If you are using Python 2.6+ you can use a context manager to automatically close the file. That way you never have to worry about closing any files! > > with open(args.fname, 'r') as f: > lines = f.readlines() > > Ramit > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > -- > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From marc.tompkins at gmail.com Tue Oct 25 19:47:22 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 25 Oct 2011 10:47:22 -0700 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> <4EA66A3E.6010701@davea.name> Message-ID: On Tue, Oct 25, 2011 at 5:31 AM, Chris Kavanagh wrote: > > > On 10/25/2011 3:50 AM, Dave Angel wrote: > >> On 10/25/2011 12:20 AM, Chris Kavanagh wrote: >> >>> >>> >>> On 10/24/2011 12:06 AM, Marc Tompkins wrote: >>> >>>> On Sun, Oct 23, 2011 at 8:08 PM, Chris Kavanagh >>> >>>> >>> >>> My problem was, I wasn't seeing {member} as referring to the class >>> objects {t} and {s}. Since it was, we now can use member just like any >>> class object, and combine it with class functions (and class >>> variables), such as {member.tell}. I had never in my short programming >>> experience, seen an example like this. So I was confused, obviously, LOL. >>> >>> >> In the context of: >> >> t = Teacher('Mrs. Shrividya', 40, 30000) >> s = Student('Swaroop', 22, 75) >> members = [t, s] >> >> for member in members; >> member.dosomething() >> >> member does not refer to t and s at all. It refers to the same object as >> t and as s, in succession. members is a list of references to objects. >> Each item in members is bound to a particular object. It is not bound in >> any way to s or t. >> >> For example, suppose we did: >> >> members = [t, s] >> t = 42 >> for member in members: >> member.dosomething() >> >> member still references the object holding Mrs. Shrividya, or Swaroop, >> in succession, even though t is now (bound to) an integer (object). >> >> >> I understand. . .Thanks for clearing that up for me Dave. > So much to learn, so little time! LOL. > Thanks again to everyone, it's much appreciated. > It can be a little hard to wrap your head around how Python handles variables/objects; in other languages you create a variable and assign a value to it, while in Python you create an object and assign a name to it - the name can change while the object remains unchanged. Here's a very simplified demo of what Dave is talking about: >>> t = "This" >>> s = "That" >>> members = [t, s] >>> print members ['This', 'That'] >>> s = "The other" >>> print members ['This', 'That'] In other words, "members" is NOT a list of "t" and "s" - it's a list of the objects that "t" and "s" pointed to AT THE MOMENT you created "members". You can re-assign "t" and "s" to other objects, but the objects that are members of "members" remain unchanged until you manipulate them directly: >>> members[0] = "Something else entirely" >>> print members ['Something else entirely', 'That'] >>> print t, s This The other It's extremely logical, but almost entirely backward from the way most other languages do things. Possibly it's because Guido is Dutch. -------------- next part -------------- An HTML attachment was scrubbed... URL: From c2praveen30jun at gmail.com Wed Oct 26 10:46:23 2011 From: c2praveen30jun at gmail.com (Praveen Singh) Date: Wed, 26 Oct 2011 04:46:23 -0400 Subject: [Tutor] 12 hr to 24 hr time conversion Message-ID: How can i convert this- >>>time24hr('12:34am') '0034hr' i searched in date module but i am not able to figure out what how to do this... -------------- next part -------------- An HTML attachment was scrubbed... URL: From raulcumplido at gmail.com Wed Oct 26 11:21:31 2011 From: raulcumplido at gmail.com (=?ISO-8859-1?Q?Ra=FAl_Cumplido?=) Date: Wed, 26 Oct 2011 11:21:31 +0200 Subject: [Tutor] 12 hr to 24 hr time conversion In-Reply-To: References: Message-ID: Hi Praveen, Do you want to create the functon time24hr which with a string as an argument of the type ("12:24am") or ("12:24pm") returns an output of ("0024hr") or ("1224hr"), right? Is this format fixed? I mean, can you create a two arguments function? (i.e time24hr("12:24", "AM") ) If you cannot change the format of the functions / arguments, I don't know if there's any standard function to do that, but I will create a function with this steps inside: 1.- Check the format of the input is ok (has the hour format and the am or pm suffix) 2.- Check if it's am or pm 3.- Calculate if I had to modify the hour 12 --> 00 , 11 --> 23 .... 3.- Return the output format. Ra?l On Wed, Oct 26, 2011 at 10:46 AM, Praveen Singh wrote: > How can i convert this- > > >>>time24hr('12:34am') > '0034hr' > > i searched in date module but i am not able to figure out what how to do > this... > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Ra?l Cumplido -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Oct 26 11:23:10 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Oct 2011 11:23:10 +0200 Subject: [Tutor] 12 hr to 24 hr time conversion References: Message-ID: Praveen Singh wrote: > How can i convert this- > >>>>time24hr('12:34am') > '0034hr' > > i searched in date module but i am not able to figure out what how to do > this... >>> time.strftime("%H:%M", time.strptime("12:34am", "%I:%M%p")) '00:34' >>> datetime.datetime.strptime("12:34am", "%I:%M%p").strftime("%H:%M") '00:34' >>> datetime.datetime.strptime("12:34am", "%I:%M%p").strftime("%H:%Mhr") '00:34hr' The supported formats are explained here: http://docs.python.org/library/time.html#time.strftime From alan.gauld at btinternet.com Wed Oct 26 11:28:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Oct 2011 10:28:31 +0100 Subject: [Tutor] 12 hr to 24 hr time conversion In-Reply-To: References: Message-ID: On 26/10/11 09:46, Praveen Singh wrote: > How can i convert this- > > >>>time24hr('12:34am') > '0034hr' > > i searched in date module but i am not able to figure out what how to do > this... In the time module you can use strptime to convert a string to a tuple. And you can use strftime to convert a tuple to a string with user specified formatting. I suspect one option will be 24 hour format. So a combination of the two should achieve what you want... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From joel.goldstick at gmail.com Wed Oct 26 11:33:14 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 26 Oct 2011 05:33:14 -0400 Subject: [Tutor] 12 hr to 24 hr time conversion In-Reply-To: References: Message-ID: On Wed, Oct 26, 2011 at 4:46 AM, Praveen Singh wrote: > How can i convert this- > > >>>time24hr('12:34am') > '0034hr' > > i searched in date module but i am not able to figure out what how to do > this... > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You can do this with slices. if t = '13:34am' then t[-2:] gives you 'am' I'm not sure if your time will sometimes be like this: '03:34' or like this '3:34'. Assuming that the hours could be one or two digits makes slicing a problem, but you can use split() like this: pieces = t.split(":") Here is what I played with: >>> s = '12:34am' >>> s[:-2] '12:34' >>> s[-2] 'a' >>> s[-2:] 'am' >>> s[:-2].split(':') ['12', '34'] >>> So, you can get the pieces with those tools. Test the value for first value, and am/pm. If am and 12 then change 12 to 0. If pm and > 12, then add 12 to the number. Then put the pieces back together -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Wed Oct 26 17:30:05 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 26 Oct 2011 11:30:05 -0400 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF01237F@EMARC112VS01.exchad.jpmchase.net> >I want to make >sure you guys, especially Alan & Dave, are appreciated for taking their >own personal time to do this, for free. Your bill will arrive shortly ;) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- -----Original Message----- From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Chris Kavanagh Sent: Monday, October 24, 2011 6:17 AM To: Alan Gauld Cc: tutor at python.org Subject: Re: [Tutor] Simple Question On A Method (in subclass) On 10/24/2011 4:40 AM, Alan Gauld wrote: > On 24/10/11 04:08, Chris Kavanagh wrote: > >> Thanks so much for the help Alan. . .I'm not trying to beat this >> question into the ground, LOL, but let me see if I can ask it a better >> way. > > Marc has already given a good answer, but I'll try a slightly different > approach to the same thing.... The differences are purely philosophical :-) > >> So we have {member.tell} as the last line of code. So trying to >> understand this piece of code, {member} the variable is considered an >> object? > > Almost. > > member is an object because it is an instance of a class. > We created instances of Teacher and Student (t and s) and put them in a > list (members) with this code: > > t = Teacher('Mrs. Shrividya', 40, 30000) > s = Student('Swaroop', 22, 75) > members = [t, s] > > Thus for member in members takes each object in the list and assigns it > to member. > > We can read {for member in members} as > > "Let member take on, in turn, each value in the collection members" > > And making it more explicit with a while loop: > > index = 0 > while index < len(members): > member = members[index] > member.tell() > index += 1 > > > Therefore we can combine it with a function {tell()} using dot > > notation?? Is this correct??? I haven't seen anything but an > > object combined with a function using dot notation. > > dot notation is how we access anything that is defined inside the class > definition. In this case there are only the __init__() and tell() > methods but there could be data attributes too. Furthermore we can add > data attributes to the objects by using the self parameter, as is done > in __init__() So we end up with the instance containing the attributes > defined at the class level (including those of its superclass) plus any > added by the __init__() method which is called when the object is > created (or instantiated). So for Teacher the attributes will be: > > __init__() > tell() > name - from SchoolMember.__init__() > age - ditto > salary - from Teacher.__init__() > > So we could have accessed any of those for the first iteration of the > loop because member was a Teacher instance (t) using: > > member.tell, member.name, member.age, member.salary > > But the last one would have broken for the second object in the list > since it was a student, which doesn't have a salary. So when dealing > with a list of objects we have to restrict the access via dot notation > to those attributes that are common to all objects in the collection - > usually the ones defined in the super class. > > Python doesn't care whether the attributes we access are data or > functions because in Python everything is an "object" (see Marc's post) > But by putting parentheses after the object name Python treats the named > object as a function (specifically a "callable" object) > > You can see this diffence at work in the interpreter if you > type this: > > >>> def f(): > ... return "Called f" > ... > >>> print f > > >>> print f() > Called f > > See the difference the () made? Without it we print the function object > called f. With it we print the result of calling the function f. > Thats quite a subtle concept and usually hard for beginners to grasp but > it is a very powerful concept and you will find it being used in > more advanced programs, especially GUI development. > > > So I'm trying to figure out how we can >> combine the variable {member} with the function {tell}. Hope this >> question makes sense to you, LOL. Thanks again. > > How we combine it is done inside Python as part of the magic of classes > and instantiation. Basically you can call any function defined inside a > class and Python will automatically assign the first parameter of that > function to the object instace that you are referencing at the time. > > Thus when we do > > for member in members: > member.tell() > > Python recognises that first time round member refers to the object t > which is an instanmce of Teacher. It then calls the tell() method within > the Teacher class definition and assigns t as the self parameter. > We could write it explicitly as: > > Teacher.tell(member) # where member is t > > On the second time round member is assigned to s and Python recognizes > that s in an instance of Student. So it calls Student.tell(member) where > member is s. > > The member.tell() notation is just a convenient way for us to write it > and allows Python to do the hard work of figuring out what kind of > object member is at any given time. > > [Aside: In true OOP speak we describe the process as "sending a message > to the object. Thus member.tell() sends the message "tell" to the object > "member" and the OOP framework invokes the corresponding method tell() > in the corresponding class. In some OOP languages you can use different > names for the messages and corresponding methods but in Python they are > the same so we just talk about calling the method.] > > HTH, > Yes, both of you gave great answers. I just couldn't get it straight in my head for some reason. And I do get it now. I just wasn't seeing {member} as an instance of a class. I guess because I'm used to seeing simple straightforward examples of classes & objects so far. Thank you guys so much for the help. You don't know how nice it is to be able to ask someone who is an expert a question, and get an answer! Thanks to everyone who contributes, I've learned a lot by reading others questions. And THANKS for providing this awesome service! _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From kellyadrian at hotmail.com Thu Oct 27 20:25:21 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 27 Oct 2011 18:25:21 +0000 Subject: [Tutor] changing dictionary to lowercase Message-ID: Hi all, is it possible to change a dictionary list to lowercase..without having to retype? e.g. definitions={"Deprecated": "No longer in use", "Depreciation": "fall in value of an asset"} i have tried definitions=definitions.lower() regards adrian -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Thu Oct 27 20:33:58 2011 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 27 Oct 2011 11:33:58 -0700 Subject: [Tutor] changing dictionary to lowercase In-Reply-To: References: Message-ID: <4EA9A416.3090606@alchemy.com> On 27-Oct-11 11:25, ADRIAN KELLY wrote: > > Hi all, > is it possible to change a dictionary list to lowercase..without having > to retype? > e.g. definitions={"Deprecated": "No longer in use", "Depreciation": > "fall in value of an asset"} > > i have tried definitions=definitions.lower() lower() is not a dictionary method, it's a string method (i.e., dictionaries have no idea how to lowercase themselves, but strings do). So what you need to do is iterate over the list of dictionary members and re-create a new dictionary with lowercased versions of the strings (that's easier than changing the dictionary in-place, especially if you're lowercasing the keys, since keys are immutable--you'd have to delete the old one and re-store the data under the lowercased key anyway) There are several ways to do that, including loops and list comprehensions. Does that nudge you in the right direction? If you're still stuck, let us know. --steve -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From joel.goldstick at gmail.com Thu Oct 27 20:36:04 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 27 Oct 2011 14:36:04 -0400 Subject: [Tutor] changing dictionary to lowercase In-Reply-To: References: Message-ID: On Thu, Oct 27, 2011 at 2:25 PM, ADRIAN KELLY wrote: > > Hi all, > is it possible to change a dictionary list to lowercase..without having to > retype? > e.g. definitions={"Deprecated": "No longer in use", "Depreciation": "fall > in value of an asset"} > > i have tried definitions=definitions.lower() > > regards > adrian > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > There is a string method called lower so 'Bob'.lower() will return 'bob' You can't alter the keys in a dictionary because they are immutable -- they can't be changed But you can loop through your dictionary, make new keys lowercase and copy the values associated with each key like this: >>> new_d = {} >>> for d in definitions: ... new_d[d.lower()] = definitions[d] ... >>> new_d {'deprecated': 'No longer in use', 'depreciation': 'fall in value of an asset'} >>> -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Oct 27 23:49:18 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 27 Oct 2011 17:49:18 -0400 Subject: [Tutor] changing dictionary to lowercase In-Reply-To: References: Message-ID: <4EA9D1DE.8050704@gmail.com> On 10/27/2011 2:25 PM, ADRIAN KELLY wrote: > > Hi all, > is it possible to change a dictionary list to lowercase..without > having to retype? > e.g. definitions={"Deprecated": "No longer in use", "Depreciation": > "fall in value of an asset"} There seems to be some confusion both in the question and the proposed solutions regarding "lowercase". Re your e.g. - is that the original or the result? It's best to show both. I have to assume that your e.g. is the original since it contains upper case letters. Do you want to change the case of the keys, values or both? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Oct 28 01:46:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Oct 2011 00:46:55 +0100 Subject: [Tutor] changing dictionary to lowercase In-Reply-To: References: Message-ID: On 27/10/11 19:25, ADRIAN KELLY wrote: > is it possible to change a dictionary list to lowercase..without having > to retype? > e.g. definitions={"Deprecated": "No longer in use", "Depreciation": > "fall in value of an asset"} You've posted a few similar type questions lately that look suspiciously like homework exercises. If that is the case we are still happy to help but we try to avoid giving you the answer directly. And we do like to see what you have tried first. > i have tried definitions=definitions.lower() Thats a start but as you found out doesn't even execute. Others have suggested some options but it would help us if you tell us which version of Python you are using because Python 3 offers some different mechanisms to Python v2. (You can tell us the OS too for completeness but it probably doesn't make much difference for the questions you have been asking) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From joebatt at hotmail.co.uk Fri Oct 28 04:20:22 2011 From: joebatt at hotmail.co.uk (Joe Batt) Date: Fri, 28 Oct 2011 02:20:22 +0000 Subject: [Tutor] =?windows-1252?q?A_total_newbie=85sorry?= Message-ID: I am just starting to try to learn Python on IDLE on a Mac running Python 3.2.2 (v3.2.2:137e45f15c0b, Sep 3 2011, 17:28:59) and I have come unstuck at the very beginning I tried >>> print "Hello"SyntaxError: invalid syntax>>> print 'Hello'SyntaxError: invalid syntax>>> print "Hello"SyntaxError: invalid syntax>>> And as you can see its just saying invalid syntax yet if I run Python in the terminal using the same syntax it works Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> print "Hello"Hello>>> I can see its a different version but what is the problem? Many thanks and sorry for the VERY basic question :( Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacktradespublic at gmail.com Fri Oct 28 05:10:25 2011 From: jacktradespublic at gmail.com (Nick Zarr) Date: Thu, 27 Oct 2011 22:10:25 -0500 Subject: [Tutor] =?windows-1252?q?A_total_newbie=85sorry?= In-Reply-To: References: Message-ID: The syntax has changed from 2.x to 3.x. 2.x: >>> print "Hello" Hello 3.x: >>> print("Hello") Hello -- Nick Zarczynski Blog 4 -------------- next part -------------- An HTML attachment was scrubbed... URL: From c2praveen30jun at gmail.com Fri Oct 28 07:38:01 2011 From: c2praveen30jun at gmail.com (Praveen Singh) Date: Fri, 28 Oct 2011 01:38:01 -0400 Subject: [Tutor] how to calculate execution time and complexity Message-ID: >>> splitWord('google', 2) ['go', 'og', 'le'] >>> splitWord('google', 3) ['goo', 'gle'] >>> splitWord('apple', 1) ['a', 'p', 'p', 'l', 'e'] >>> splitWord('apple', 4) ['appl', 'e'] def splitWord(word, number): length=len(word) list1=[] x=0 increment=number while number<=length+increment: list1.append(word[x:number]) x=x+increment number=number+increment for d in list1: if d=='': list1.remove('') return list1 I am getting the desired output and this code is working fine..but i think it is quite bulky for this small operation. qus.1-- can you guys suggest me some better solution?? qus 2-- i know writing just a piece of code is not going to help me. i have to write efficient code.i want to know how to calculate execution time of my code and can you guys suggest me some links so that i can learn how to find complexity of code?? Thanks in advance... -------------- next part -------------- An HTML attachment was scrubbed... URL: From abhishek.vit at gmail.com Fri Oct 28 08:20:49 2011 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Thu, 27 Oct 2011 23:20:49 -0700 Subject: [Tutor] how to calculate execution time and complexity In-Reply-To: References: Message-ID: Hi Praveen I am still new to the language but here is what I would do. Sorry I can't comment on how to best check for efficiency. my_str='google' split_by= 2 [ my_str[i:i+split_by] for i in range(0, len(my_str), split_by) ] Just using a list comprehension. best, -Abhi On Thu, Oct 27, 2011 at 10:38 PM, Praveen Singh wrote: > >>> splitWord('google', 2) > ['go', 'og', 'le'] > > > >>> splitWord('google', 3) > ['goo', 'gle'] > > > >>> splitWord('apple', 1) > ['a', 'p', 'p', 'l', 'e'] > > > >>> splitWord('apple', 4) > ['appl', 'e'] > > > > def splitWord(word, number): > length=len(word) > list1=[] > x=0 > increment=number > while number<=length+increment: > list1.append(word[x:number]) > x=x+increment > > > number=number+increment > > for d in list1: > if d=='': > list1.remove('') > return list1 > > I am getting the desired output and this code is working fine..but i think it is quite bulky for this small operation. > > > qus.1-- can you guys suggest me some better solution?? > qus 2-- i know writing just a piece of code is not going to help me. i have to write efficient code.i want to know how to calculate execution time of my code and > > > can you guys suggest me some links so that i can learn how to find complexity of code?? > > Thanks in advance... > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Fri Oct 28 08:20:22 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 28 Oct 2011 08:20:22 +0200 Subject: [Tutor] how to calculate execution time and complexity In-Reply-To: References: Message-ID: <4EAA49A6.6040007@compuscan.co.za> On 2011/10/28 07:38 AM, Praveen Singh wrote: > >>> splitWord('google', 2) > ['go', 'og', 'le'] > > >>> splitWord('google', 3) > ['goo', 'gle'] > > >>> splitWord('apple', 1) > ['a', 'p', 'p', 'l', 'e'] > > >>> splitWord('apple', 4) > ['appl', 'e'] > > > > def splitWord(word, number): > length=len(word) > list1=[] > x=0 > increment=number > while number<=length+increment: > list1.append(word[x:number]) > x=x+increment > > number=number+increment > > for d in list1: > if d=='': > list1.remove('') > return list1 > > I am getting the desired output and this code is working fine..but i think it is quite bulky for this small operation. > > > qus.1-- can you guys suggest me some better solution?? > qus 2-- i know writing just a piece of code is not going to help me. i have to write efficient code.i want to know how to calculate execution time of my code and > > can you guys suggest me some links so that i can learn how to find complexity of code?? > > Thanks in advance... > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Below [1] is how I would write it, which is simply a re-factoring of your code so it's cleaner and more compact. For calculating execution time you can use the `timeit` module [2] and for more in-depth analysis you can look at `profile` [3] and further to the bare-bones `dis` [4]. [1] >>> def splitWord(word, number): ... x = [] ... for y in xrange(0, len(word), number): ... x.append(word[y:y+number]) ... return x ... >>> splitWord('google', 1) ['g', 'o', 'o', 'g', 'l', 'e'] >>> splitWord('google', 2) ['go', 'og', 'le'] >>> splitWord('google', 3) ['goo', 'gle'] >>> splitWord('google', 4) ['goog', 'le'] >>> splitWord('google', 5) ['googl', 'e'] >>> splitWord('google', 6) ['google'] >>> splitWord('google', 7) ['google'] [2] http://www.doughellmann.com/PyMOTW/timeit/ [3] http://www.doughellmann.com/PyMOTW/profile/index.html#module-profile [4] http://www.doughellmann.com/PyMOTW/dis/ -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From c2praveen30jun at gmail.com Fri Oct 28 08:31:23 2011 From: c2praveen30jun at gmail.com (Praveen Singh) Date: Fri, 28 Oct 2011 02:31:23 -0400 Subject: [Tutor] how to calculate execution time and complexity In-Reply-To: <4EAA49A6.6040007@compuscan.co.za> References: <4EAA49A6.6040007@compuscan.co.za> Message-ID: . > Thanks Christian for your links and code!!!! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor > > > Below [1] is how I would write it, which is simply a re-factoring of your > code so it's cleaner and more compact. For calculating execution time you > can use the `timeit` module [2] and for more in-depth analysis you can look > at `profile` [3] and further to the bare-bones `dis` [4]. > > [1] > >>> def splitWord(word, number): > ... x = [] > ... for y in xrange(0, len(word), number): > ... x.append(word[y:y+number]) > ... return x > ... > >>> splitWord('google', 1) > ['g', 'o', 'o', 'g', 'l', 'e'] > > >>> splitWord('google', 2) > ['go', 'og', 'le'] > >>> splitWord('google', 3) > ['goo', 'gle'] > >>> splitWord('google', 4) > ['goog', 'le'] > >>> splitWord('google', 5) > ['googl', 'e'] > >>> splitWord('google', 6) > ['google'] > >>> splitWord('google', 7) > ['google'] > > [2] http://www.doughellmann.com/PyMOTW/timeit/ > [3] http://www.doughellmann.com/PyMOTW/profile/index.html#module-profile > [4] http://www.doughellmann.com/PyMOTW/dis/ > > -- > > Christian Witts > Python Developer > > ** > -- www.tricksfind.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Oct 28 09:14:26 2011 From: d at davea.name (Dave Angel) Date: Fri, 28 Oct 2011 03:14:26 -0400 Subject: [Tutor] how to calculate execution time and complexity In-Reply-To: References: Message-ID: <4EAA5652.7060001@davea.name> On 10/28/2011 01:38 AM, Praveen Singh wrote: >>>> splitWord('google', 2) > ['go', 'og', 'le'] > >>> splitWord('google', 3) > ['goo', 'gle'] > >>> splitWord('apple', 1) > ['a', 'p', 'p', 'l', 'e'] > >>> splitWord('apple', 4) > ['appl', 'e'] > > > def splitWord(word, number): > length=len(word) > list1=[] > x=0 > increment=number > while number<=length+increment: > list1.append(word[x:number]) > x=x+increment > number=number+increment > > for d in list1: > if d=='': > list1.remove('') > return list1 > > I am getting the desired output and this code is working fine..but i > think it is quite bulky for this small operation. > > qus.1-- can you guys suggest me some better solution?? > qus 2-- i know writing just a piece of code is not going to help me. i > have to write efficient code.i want to know how to calculate execution > time of my code and > can you guys suggest me some links so that i can learn how to > find complexity of code?? > > Thanks in advance... > Use the grouper() recipe, shown on the intertools page of the docs: http://docs.python.org/library/itertools.html -- DaveA From alan.gauld at btinternet.com Fri Oct 28 09:38:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Oct 2011 08:38:17 +0100 Subject: [Tutor] =?windows-1252?q?A_total_newbie=85sorry?= In-Reply-To: References: Message-ID: On 28/10/11 03:20, Joe Batt wrote: > I am just starting to try to learn Python on IDLE on a Mac running Welcome, and don't worry thee are no stupid questions. And you've given us all the right info to answer too, well done! :-) > Python 3.2.2 (v3.2.2:137e45f15c0b, Sep 3 2011, 17:28:59) and I have come > unstuck at the very beginning I tried > > >>> print "Hello" > SyntaxError: invalid syntax > the terminal using the same syntax it works > > Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) > >>> print "Hello" > Hello > > I can see its a different version but what is the problem? Thats the problem. Python v3 has some big differences from v2. And print is one of them. You need to put the string inside parentheses: print ("hello"). But there are other subtle changes too. You don't mention what tutorial you are using to learn Python but it looks like it is based on v2 (as many are). So either you should install IDLE for v2.7 and carry on from there or find a tutorial for v3 and use that. If you can already program in another language then the official tutorial on the python web site is a good choice as it gets updated with each release. If you are a complete beginner to programming you could try mine (see below), but there are some others for v3 too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Oct 28 09:46:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 28 Oct 2011 18:46:47 +1100 Subject: [Tutor] =?windows-1252?q?A_total_newbie=85sorry?= In-Reply-To: References: Message-ID: <4EAA5DE7.6070207@pearwood.info> Alan Gauld wrote: > On 28/10/11 03:20, Joe Batt wrote: >> I am just starting to try to learn Python on IDLE on a Mac running > > Welcome, and don't worry thee are no stupid questions. Was it you or your brother who was killed in the war? -- Steven From fomcl at yahoo.com Fri Oct 28 11:51:39 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 28 Oct 2011 02:51:39 -0700 (PDT) Subject: [Tutor] changing dictionary to lowercase In-Reply-To: References: Message-ID: <1319795499.23311.YahooMailNeo@web110714.mail.gq1.yahoo.com> It would be nice to generalize the solution so it could also handle definitions={"Deprecated":?"No longer in use", "DEPRECATED":? "No longer in use"} These are unique now, but after turning them into lower case not anymore. new_d = {} for d in definitions: ??? try: ??????? new_d[d.lower()].append(definitions[d]) ??? except TypeError: ??????? new_d[d.lower()] = [definitions[d]] ? Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >________________________________ >From: Joel Goldstick >To: tutor at python.org >Sent: Thursday, October 27, 2011 8:36 PM >Subject: Re: [Tutor] changing dictionary to lowercase > > > > > >On Thu, Oct 27, 2011 at 2:25 PM, ADRIAN KELLY wrote: > > >>Hi all, >>is it possible to change a dictionary list to lowercase..without having to retype? >>e.g. definitions={"Deprecated":?"No longer in use", "Depreciation": "fall in value of an asset"} >>? >>i have tried definitions=definitions.lower() >>? >>regards >>adrian >> >> >>_______________________________________________ >>Tutor maillist ?- ?Tutor at python.org >>To unsubscribe or change subscription options: >>http://mail.python.org/mailman/listinfo/tutor >> >>There is a string method called lower so 'Bob'.lower() will return 'bob' > >You can't alter the keys in a dictionary because they are immutable -- they can't be changed > >But you can loop through your dictionary, make new keys lowercase and copy the values associated with each key > >like this: > >>>> new_d = {} > >>>> for d in definitions: >...?? new_d[d.lower()] = definitions[d] >... >>>> new_d >{'deprecated': 'No longer in use', 'depreciation': 'fall in value of an asset'} >>>> > > > > >-- >Joel Goldstick > > >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Fri Oct 28 12:01:34 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 28 Oct 2011 12:01:34 +0200 Subject: [Tutor] changing dictionary to lowercase In-Reply-To: <1319795499.23311.YahooMailNeo@web110714.mail.gq1.yahoo.com> References: <1319795499.23311.YahooMailNeo@web110714.mail.gq1.yahoo.com> Message-ID: <4EAA7D7E.8090800@compuscan.co.za> On 2011/10/28 11:51 AM, Albert-Jan Roskam wrote: > It would be nice to generalize the solution so it could also handle > definitions={"Deprecated": "No longer in use", "DEPRECATED": "No > longer in use"} > These are unique now, but after turning them into lower case not anymore. > new_d = {} > for d in definitions: > try: > new_d[d.lower()].append(definitions[d]) > except TypeError: > new_d[d.lower()] = [definitions[d]] > Cheers!! > Albert-Jan > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor To save yourself the try/except you can use defaultdict which is part of the collections module. from collections import defaultdict new_d = defaultdict(list) for key, value in definitions.iteritems(): new_d[key.lower()].append(value) -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Oct 28 16:14:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Oct 2011 15:14:30 +0100 Subject: [Tutor] =?windows-1252?q?A_total_newbie=85sorry?= In-Reply-To: <4EAA5DE7.6070207@pearwood.info> References: <4EAA5DE7.6070207@pearwood.info> Message-ID: On 28/10/11 08:46, Steven D'Aprano wrote: > Alan Gauld wrote: >> On 28/10/11 03:20, Joe Batt wrote: >>> I am just starting to try to learn Python on IDLE on a Mac running >> >> Welcome, and don't worry thee are no stupid questions. > > Was it you or your brother who was killed in the war? > > me :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ericschles at gmail.com Fri Oct 28 17:31:02 2011 From: ericschles at gmail.com (Eric Schles) Date: Fri, 28 Oct 2011 08:31:02 -0700 Subject: [Tutor] easy_install question Message-ID: Hello, This is my first time using this service so I am unsure what proper formatting should be. In any case here is my question. I just downloaded EasyInstall here: http://peak.telecommunity.com/DevCenter/EasyInstall In the example section under Downloading and Installing a Package which is in the website listed, there is an example called example 1. I can't get it to work. I was able to import easy_install into my python GUI. But whenever I try using it I get the following message: >>> easy_install SQLObject SyntaxError: invalid syntax I'm not sure what I am doing wrong since I copy/pasted the code from the tutorial. Any advice towards being able to use this module would be greatly appreciated. Sincerely, Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Oct 28 19:18:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 29 Oct 2011 04:18:51 +1100 Subject: [Tutor] easy_install question In-Reply-To: References: Message-ID: <4EAAE3FB.1020008@pearwood.info> Eric Schles wrote: > Hello, > > This is my first time using this service so I am unsure what proper > formatting should be. In any case here is my question. > > I just downloaded EasyInstall here: > http://peak.telecommunity.com/DevCenter/EasyInstall > > In the example section under > Downloading and Installing a > Package > which is in the website listed, there is an example called example 1. > > I can't get it to work. I was able to import easy_install into my python > GUI. But whenever I try using it I get the following message: >>>> easy_install SQLObject > SyntaxError: invalid syntax You are running Easy Install from inside Python, but using non-Python syntax. Normally you would run Easy Install from the shell. Under Linux, open your favourite xterm, console or terminal window. You should have a $ prompt instead of the Python prompt >>>. At the shell prompt, type: easy_install SQLObject and press the Enter key, and it should just work. (If you get "Permission Denied" errors, you may need to use sudo or run the command as the root user.) Under Windows will be similar, using command.com or cmd.exe. -- Steven From bgailer at gmail.com Fri Oct 28 20:05:09 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 28 Oct 2011 14:05:09 -0400 Subject: [Tutor] changing dictionary to lowercase In-Reply-To: References: <4EA9D1DE.8050704@gmail.com> Message-ID: <4EAAEED5.3020706@gmail.com> Always reply-all so a copy goes to the tutor list. Always put your responses following the question rather than at the top of the email. On 10/28/2011 8:28 AM, Adrian wrote: > Thats the original alright bob, id like to change keys to lowercase > Thanks > Adrian > > Sent from my iPad > > On 27 Oct 2011, at 22:49, bob gailer > wrote: > >> On 10/27/2011 2:25 PM, ADRIAN KELLY wrote: >>> >>> Hi all, >>> is it possible to change a dictionary list to lowercase..without >>> having to retype? >>> e.g. definitions={"Deprecated": "No longer in use", "Depreciation": >>> "fall in value of an asset"} >> >> There seems to be some confusion both in the question and the >> proposed solutions regarding "lowercase". >> >> Re your e.g. - is that the original or the result? >> >> It's best to show both. >> >> I have to assume that your e.g. is the original since it contains >> upper case letters. >> >> Do you want to change the case of the keys, values or both? >> >> -- >> Bob Gailer >> 919-636-4239 >> Chapel Hill NC -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From fal at libero.it Fri Oct 28 20:15:01 2011 From: fal at libero.it (Francesco Loffredo) Date: Fri, 28 Oct 2011 20:15:01 +0200 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: References: <4E848E9D.3090901@davea.name> <4E8B25C8.3060005@ieee.org> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F212344A5@EMARC112VS01.exchad.jpmchase.net> <4E8BC4DD.4070806@davea.name> <4E8BEE37.1050408@davea.name> <4E8E5815.1000804@davea.name> Message-ID: <4EAAF125.30006@libero.it> lina wrote: > > > On Fri, Oct 7, 2011 at 9:38 AM, Dave Angel > wrote: > > On 10/06/2011 12:21 PM, lina wrote: > > > > Yes. I understand this part now. But how can I print a list consists of the value of key B + E. > > For {'B': [4, 5, 6], 'E': [1, 2, 3]} > > I wanna get the summary of B and E in each column, namely [5, 7, 9] > My two cents on this very long thread: tot = [0]*numcolumns for q in result.values(): tot = [i+j for i, j in zip(tot, q)] ----- Nessun virus nel messaggio. Controllato da AVG - www.avg.com Versione: 2012.0.1834 / Database dei virus: 2092/4578 - Data di rilascio: 27/10/2011 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Fri Oct 28 20:30:00 2011 From: kellyadrian at hotmail.com (Adrian) Date: Fri, 28 Oct 2011 19:30:00 +0100 Subject: [Tutor] changing dictionary to lowercase In-Reply-To: <4EAAEED5.3020706@gmail.com> References: <4EA9D1DE.8050704@gmail.com> <4EAAEED5.3020706@gmail.com> Message-ID: Ok boss point noted Sent from my iPad On 28 Oct 2011, at 19:05, bob gailer wrote: > Always reply-all so a copy goes to the tutor list. > > Always put your responses following the question rather than at the top of the email. > > On 10/28/2011 8:28 AM, Adrian wrote: >> >> Thats the original alright bob, id like to change keys to lowercase >> Thanks >> Adrian >> >> Sent from my iPad >> >> On 27 Oct 2011, at 22:49, bob gailer wrote: >> >>> On 10/27/2011 2:25 PM, ADRIAN KELLY wrote: >>>> >>>> >>>> Hi all, >>>> is it possible to change a dictionary list to lowercase..without having to retype? >>>> e.g. definitions={"Deprecated": "No longer in use", "Depreciation": "fall in value of an asset"} >>> >>> There seems to be some confusion both in the question and the proposed solutions regarding "lowercase". >>> >>> Re your e.g. - is that the original or the result? >>> >>> It's best to show both. >>> >>> I have to assume that your e.g. is the original since it contains upper case letters. >>> >>> Do you want to change the case of the keys, values or both? >>> >>> -- >>> Bob Gailer >>> 919-636-4239 >>> Chapel Hill NC >> > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From ericschles at gmail.com Fri Oct 28 20:45:37 2011 From: ericschles at gmail.com (Eric Schles) Date: Fri, 28 Oct 2011 11:45:37 -0700 Subject: [Tutor] more trouble Message-ID: So far, I have tried a few things. Listed below was my original problem and my original help. Eric Schles wrote: > Hello, > > This is my first time using this service so I am unsure what proper > formatting should be. In any case here is my question. > > I just downloaded EasyInstall here: > http://peak.telecommunity.com/DevCenter/EasyInstall > > In the example section under > Downloading and Installing a > Package > which is in the website listed, there is an example called example 1. > > I can't get it to work. I was able to import easy_install into my python > GUI. But whenever I try using it I get the following message: >>>> easy_install SQLObject > SyntaxError: invalid syntax You are running Easy Install from inside Python, but using non-Python syntax. Normally you would run Easy Install from the shell. Under Linux, open your favourite xterm, console or terminal window. You should have a $ prompt instead of the Python prompt >>>. At the shell prompt, type: easy_install SQLObject and press the Enter key, and it should just work. (If you get "Permission Denied" errors, you may need to use sudo or run the command as the root user.) Under Windows will be similar, using command.com or cmd.exe. -- Steven The help steven gave me makes sense, except I don't know what it means. How do you run the command as root? When I try to run the command in the command line, I get the following error: C:\>easy_install SQLObject 'easy_install' is not recognized as an internal or external command, operable program or batch file. What does that mean? I also tried it in a python command prompt (just in case) and got >>> import easy_install >>> easy_install SQLObject File "", line 1 easy_install SQLObject ^ syntaxError: invalid syntax I understand that a syntax error happens when you enter something incorrectly. So this is likely the error steven was talking about. So, any more ideas? I greatly appreciate the help. Sincerely, Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Fri Oct 28 21:49:13 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Fri, 28 Oct 2011 21:49:13 +0200 Subject: [Tutor] more trouble In-Reply-To: References: Message-ID: <4EAB0739.90200@gmx.net> On 2011-10-28 20:45, Eric Schles wrote: > The help steven gave me makes sense, except I don't know what it means. How > do you run the command as root? > When I try to run the command in the command line, I get the following > error: > C:\>easy_install SQLObject > 'easy_install' is not recognized as an internal or external command, > operable program or batch file. > > What does that mean? Windows can't find the "easy_install.exe" because it's not in C:\ and not in your PATH environment variable. I've no windows here, but from reading the docs you've probably installed "easy_install" in your python scripts subdirectory. So you have to go there before you can run it: C:\>cd \Python2x\Scripts (x depends on your installed python version) C:\Python2x\Scripts>easy_install SQLObject Or you add the scripts directory to your PATH: http://peak.telecommunity.com/DevCenter/EasyInstall#id5 If you can't find out where it's installed, try searching for "easy_install.exe". HTH, Andreas From ericschles at gmail.com Fri Oct 28 22:10:23 2011 From: ericschles at gmail.com (Eric Schles) Date: Fri, 28 Oct 2011 13:10:23 -0700 Subject: [Tutor] Tutor Digest, Vol 92, Issue 118 In-Reply-To: References: Message-ID: Here is my original problem: Eric Schles wrote: > Hello, > > This is my first time using this service so I am unsure what proper > formatting should be. In any case here is my question. > > I just downloaded EasyInstall here: > http://peak.telecommunity.com/DevCenter/EasyInstall > > In the example section under > Downloading and Installing a > Package > which is in the website listed, there is an example called example 1. > > I can't get it to work. I was able to import easy_install into my python > GUI. But whenever I try using it I get the following message: >>>> easy_install SQLObject > SyntaxError: invalid syntax Here is the suggestions made thus far: > > > > > You are running Easy Install from inside Python, but using non-Python > syntax. > > Normally you would run Easy Install from the shell. Under Linux, open > your favourite xterm, console or terminal window. You should have a $ > prompt instead of the Python prompt >>>. > > At the shell prompt, type: > > easy_install SQLObject > > and press the Enter key, and it should just work. (If you get > "Permission Denied" errors, you may need to use sudo or run the command > as the root user.) > > Under Windows will be similar, using command.com or cmd.exe. > > > -- > Steven > > > Windows can't find the "easy_install.exe" because it's not in C:\ and > not in your PATH environment variable. > > I've no windows here, but from reading the docs you've probably > installed "easy_install" in your python scripts subdirectory. So you > have to go there before you can run it: > C:\>cd \Python2x\Scripts (x depends on your installed python version) > C:\Python2x\Scripts>easy_install SQLObject > > Or you add the scripts directory to your PATH: > http://peak.telecommunity.com/DevCenter/EasyInstall#id5 > > If you can't find out where it's installed, try searching for > "easy_install.exe". > > HTH, Andreas > > Unfortunately, none of it has worked. Maybe there is something I am > missing? I've never gotten a module to work before, at least not a third > party one. Thanks again in advance, Sincerely, Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Fri Oct 28 22:31:30 2011 From: wprins at gmail.com (Walter Prins) Date: Fri, 28 Oct 2011 21:31:30 +0100 Subject: [Tutor] Tutor Digest, Vol 92, Issue 118 In-Reply-To: References: Message-ID: Hi Eric, On 28 October 2011 21:10, Eric Schles wrote: > Or you add the scripts directory to your PATH: >> http://peak.telecommunity.com/DevCenter/EasyInstall#id5 >> >> If you can't find out where it's installed, try searching for >> "easy_install.exe". >> >> HTH, Andreas >> >> Unfortunately, none of it has worked. Maybe there is something I am >> missing? I've never gotten a module to work before, at least not a third >> party one. > > > Thanks again in advance, > > 1.) Please don't start new threads/post new messages for questions which you've already asked previously. 2.) The link suggested previously to you contains (amongst other things) the following instructions, which if correctly followed will solve your problem: "On Windows, an easy_install.exe launcher will also be installed, so that you can just type easy_install as long as it's on your PATH. If typing easy_install at the command prompt doesn't work, check to make sure your PATH includes the appropriate C:\Python2X\Scripts directory. On most current versions of Windows, you can change the PATH by right-clicking "My Computer", choosing "Properties" and selecting the "Advanced" tab, then clicking the "Environment Variables" button. PATH will be in the "System Variables" section, and you will need to exit and restart your command shell (command.com, cmd.exe, bash, or other) for the change to take effect. Be sure to add a ; after the last item on PATH before adding the scripts directory to it." Have you tried this, and if so and it appears not to work, what exactly did you enter and what are the error messages you received after applying the above instructions? (Remember you should edit the above paths to actually match your Python folder -- you would not literally use "Python2X" in the path you add, you would for example add "C:\Python27\Scripts" if you're using Python 2.7 etc.) For reference I googled and found this link that should help clarify the above: http://www.computerhope.com/issues/ch000549.htm Here's further education about the Windows environment: http://vlaurie.com/computers2/Articles/environment.htm Hope that helps, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Oct 29 02:05:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Oct 2011 01:05:26 +0100 Subject: [Tutor] more trouble In-Reply-To: References: Message-ID: On 28/10/11 19:45, Eric Schles wrote: > So far, I have tried a few things. Listed below was my original problem > and my original help. > The help steven gave me makes sense, except I don't know what it means. > How do you run the command as root? That's a Linux thing you don;t need that in Windows (usually). There are a mix of Linux, Windows and Mac users here so you can expect to get answers based on whatever the users preference is. Usually you can translate back to your own OS, although not always. So its a good idea to remind us of your OS when you ask questions,. > When I try to run the command in the command line, I get the following > error: > C:\>easy_install SQLObject > 'easy_install' is not recognized as an internal or external command, > operable program or batch file. > > What does that mean? That Windows can't find an executable program called easy_install, You probably need to navigate to the folder containing it and run it from there. You might like to find a basic tutorial on the Windows command prompt. When programming, in any language, not just Python, you often find yourself doing things from the command prompt rather than the GUI. There is one such here: http://www.pcstats.com/articleview.cfm?articleid=1723&page=1 -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From hoppenmaus at gmail.com Sat Oct 29 16:43:04 2011 From: hoppenmaus at gmail.com (Brian Stovall) Date: Sat, 29 Oct 2011 07:43:04 -0700 Subject: [Tutor] Methods defined in my class are affecting all the objects at runtime. Message-ID: Hello world! I obviously don't understand something important and basic, but I am having trouble figuring it out myself... I am running python v3.2.2 on a Win XP machine. My code: import card_model import random class Pile: """An Object reperesenting a list of 'Card' Objects: could be a hand, discard pile, tableau or anything really. Has a display_type that is used to clarify what kind of display to use, and .deal(cards[] , new_pile(Pile Object)) and .shuffle() methods.""" DISPLAY_TYPES = ["STACK", "FAN", "ACCORDION", "CASCADE"] def __init__(self, cards = [], display_type = "STACK"): self.cards = cards self.display_type = display_type def __str__(self): return_string = "" for i in self.cards: return_string = return_string + str(i) + "\n" return_string = return_string + str(self.display_type) return return_string def shuffle(self): random.shuffle(self.cards) def add(self, card_list): for i in card_list: self.cards.append(i) def deal(self, number_of_cards, position = 0): """Deletes the number of cards out of the pile, starting from position (default is the top) and returns that list of cards, for communication with other piles' .add methods.""" dealt_list = [] try: for i in range(number_of_cards): dealt_list.append(self.cards[position]) del self.cards[position] return(dealt_list) except IndexError: print("Error, out of cards!") return(None) I had been testing it with single objects favorably, but when I instantiate two Pile objects, methods like .add or .shuffle affect all of the Pile objects in memory. At first I thought the objects were all initializing to the same space in memory, but it wasn't true. If you need to see all my modules or my tester code, I will happily post. Thanks for helping a rank beginner! -Brian From __peter__ at web.de Sat Oct 29 17:26:02 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 29 Oct 2011 17:26:02 +0200 Subject: [Tutor] Methods defined in my class are affecting all the objects at runtime. References: Message-ID: Brian Stovall wrote: > Hello world! > > I obviously don't understand something important and basic, but I am > having trouble figuring it out myself... I am running python v3.2.2 on > a Win XP machine. > > My code: > > import card_model > import random > > class Pile: > """An Object reperesenting a list of 'Card' Objects: could be a > hand, discard pile, tableau > or anything really. Has a display_type that is used to clarify > what kind of display to use, and > .deal(cards[] , new_pile(Pile Object)) and .shuffle() methods.""" > > DISPLAY_TYPES = ["STACK", "FAN", "ACCORDION", "CASCADE"] > > def __init__(self, cards = [], display_type = "STACK"): That is a common pitfall: the default values of functions and methods are evaluated only once. Therefore all Pile instances created without an explicit cards argument p = Pile() end up sharing the same cards list. The idiomatic way to avoid that problem is a default value of None: def __init__(self, cards=None, display_type="STACK"): if cards is None: cards = [] # no list provided -> make a new one self.cards = cards self.display_type = display_type Note that this problem can only occur with "mutable" types (types whose internal state can be modified at any time); the default for display_type is immutable (its state is set once and for all when the object is created) and thus cannot cause that kind of trouble. > self.cards = cards > self.display_type = display_type > > def __str__(self): > return_string = "" > for i in self.cards: > return_string = return_string + str(i) + "\n" Have a look at str.join(). Example: "\n".join(str(card) for card in self.cards) > return_string = return_string + str(self.display_type) > return return_string > > def shuffle(self): > random.shuffle(self.cards) > > def add(self, card_list): > for i in card_list: > self.cards.append(i) Have a look at list.extend(). > def deal(self, number_of_cards, position = 0): > """Deletes the number of cards out of the pile, starting from > position (default is the top) and returns that list of cards, for > communication with other piles' .add methods.""" > > dealt_list = [] > try: > for i in range(number_of_cards): > dealt_list.append(self.cards[position]) > del self.cards[position] Have a look at list.pop() or slices like cards[position:position+number_of_cards] > return(dealt_list) > except IndexError: > print("Error, out of cards!") > > return(None) > > I had been testing it with single objects favorably, but when I > instantiate two Pile objects, methods like .add or .shuffle affect all > of the Pile objects in memory. At first I thought the objects were all > initializing to the same space in memory, but it wasn't true. If you > need to see all my modules or my tester code, I will happily post. > > Thanks for helping a rank beginner! > > -Brian > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sat Oct 29 17:33:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 30 Oct 2011 02:33:44 +1100 Subject: [Tutor] Methods defined in my class are affecting all the objects at runtime. In-Reply-To: References: Message-ID: <4EAC1CD8.6030504@pearwood.info> Brian Stovall wrote: > Hello world! > > I obviously don't understand something important and basic, but I am > having trouble figuring it out myself... I am running python v3.2.2 on > a Win XP machine. [...] > I had been testing it with single objects favorably, but when I > instantiate two Pile objects, methods like .add or .shuffle affect all > of the Pile objects in memory. At first I thought the objects were all > initializing to the same space in memory, but it wasn't true. The problem is not that all Pile objects are in the same space in memory, but that they all share the same cards. If you call: a = Pile() b = Pile() c = Pile() then all three Piles a, b, c share the same list of cards. If instead you explicitly call Pile([]) each time then I bet the problem will go away. Try it and see. The problem occurs in your __init__ method, where you use a default value of [] for cards: def __init__(self, cards = [], display_type = "STACK"): self.cards = cards self.display_type = display_type The thing is, in Python the default value is only calculated *once*, when the function or method is defined, and then reused each time. You can test this for yourself very easily: import time def test(t=time.asctime()): print(t) Call test(), wait a few seconds, and call it again, and precisely the same time will be printed. The default value for t is calculated once, then reused. Normally this is not a problem, but if the default value is a list or dict, it means that the method or function remembers state from one call to the next: >>> def test(x, alist=[]): ... alist.append(x) # Modify the list in place. ... return alist ... >>> test(2) # The first time you call the function, the default is [] [2] >>> test(3) # But now the default is [2] [2, 3] >>> test(5) # And now the default is [2, 3] [2, 3, 5] You can easily fix this problem by making sure each Pile instance gets its own brand new empty list of cards, instead of sharing the same one: def __init__(self, cards=None, display_type="STACK"): if cards is None: cards = [] self.cards = cards self.display_type = display_type A couple of other minor points: Your add method can be simplified to this: def add(self, card_list): self.cards.extend(card_list) Also, your __str__ method builds up the string by repeated concatenation: def __str__(self): return_string = "" for i in self.cards: return_string = return_string + str(i) + "\n" return_string = return_string + str(self.display_type) return return_string This is generally poor practice. Without going into a lot of detail, this risks being slow in Python. Very, very, VERY slow. Depending on the details of your operating system, exact version of Python, the specific strings being used, you may not notice any slowdown, but the risk is still there. The recommended way to build up a string out of many smaller substrings is like this: def __str__(self): # First build a list of all of the substrings. substrings = [] for card in self.cards: # Please use a more descriptive name than "i" substrings.append(str(card)) substrings.append(str(self.display_type)) # Now join all of the substrings in one fast operation. return '\n'.join(substrings) Hope this helps, -- Steven From hoppenmaus at gmail.com Sat Oct 29 18:13:18 2011 From: hoppenmaus at gmail.com (Brian Stovall) Date: Sat, 29 Oct 2011 09:13:18 -0700 Subject: [Tutor] Methods defined in my class are affecting all the objects at runtime. In-Reply-To: References: Message-ID: Thanks for all the wonderful help, everyone! On 10/29/11, Peter Otten <__peter__ at web.de> wrote: > Brian Stovall wrote: > >> Hello world! >> >> I obviously don't understand something important and basic, but I am >> having trouble figuring it out myself... I am running python v3.2.2 on >> a Win XP machine. >> >> My code: >> >> import card_model >> import random >> >> class Pile: >> """An Object reperesenting a list of 'Card' Objects: could be a >> hand, discard pile, tableau >> or anything really. Has a display_type that is used to clarify >> what kind of display to use, and >> .deal(cards[] , new_pile(Pile Object)) and .shuffle() methods.""" >> >> DISPLAY_TYPES = ["STACK", "FAN", "ACCORDION", "CASCADE"] >> >> def __init__(self, cards = [], display_type = "STACK"): > > That is a common pitfall: the default values of functions and methods are > evaluated only once. Therefore all Pile instances created without an > explicit cards argument > > p = Pile() > > end up sharing the same cards list. The idiomatic way to avoid that problem > is a default value of None: > > def __init__(self, cards=None, display_type="STACK"): > if cards is None: > cards = [] # no list provided -> make a new one > self.cards = cards > self.display_type = display_type > > Note that this problem can only occur with "mutable" types (types whose > internal state can be modified at any time); the default for display_type is > immutable (its state is set once and for all when the object is created) and > thus cannot cause that kind of trouble. > >> self.cards = cards >> self.display_type = display_type >> >> def __str__(self): >> return_string = "" >> for i in self.cards: >> return_string = return_string + str(i) + "\n" > > Have a look at str.join(). Example: > > "\n".join(str(card) for card in self.cards) > >> return_string = return_string + str(self.display_type) >> return return_string >> >> def shuffle(self): >> random.shuffle(self.cards) >> >> def add(self, card_list): >> for i in card_list: >> self.cards.append(i) > > Have a look at list.extend(). > >> def deal(self, number_of_cards, position = 0): >> """Deletes the number of cards out of the pile, starting from >> position (default is the top) and returns that list of cards, for >> communication with other piles' .add methods.""" >> >> dealt_list = [] >> try: >> for i in range(number_of_cards): >> dealt_list.append(self.cards[position]) >> del self.cards[position] > > Have a look at list.pop() or slices like > > cards[position:position+number_of_cards] > >> return(dealt_list) >> except IndexError: >> print("Error, out of cards!") >> >> return(None) >> >> I had been testing it with single objects favorably, but when I >> instantiate two Pile objects, methods like .add or .shuffle affect all >> of the Pile objects in memory. At first I thought the objects were all >> initializing to the same space in memory, but it wasn't true. If you >> need to see all my modules or my tester code, I will happily post. >> >> Thanks for helping a rank beginner! >> >> -Brian >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From joelmontes01 at gmail.com Sat Oct 29 18:25:15 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Sat, 29 Oct 2011 12:25:15 -0400 Subject: [Tutor] Method to create small and simple database Message-ID: <4EAC28EB.8030102@gmail.com> Hello everyone, About me: This is the first time I post to Tutor at Python.org. I am brand spanking new to Python. I can create simple application, gone through a few tutorials and watched the Google Python 2 day class on Youtube. (List of classes: http://goo.gl/Ud5rg) Just yesterday I figured out how to load up a GUI made in Glade and pass singles around and what not. Huge accomplishment for me since documentation is a bit shaky for noobs like me. :) I have some programming knowledge. I learned (self tough) VB when I was in middle school and then did a intro to C++ in college. Of course mentioning that is trivial since I haven't done any programming for about 5 years or so.. But I do know basic concepts. Just need a little push in the right direction.. -------------------------------------- I think I know how to design my application but I would like to put it on here for you guys to review and provide me with feedback/suggestions as to the best way to go about it. -------------------------------------- The application: I want to build a simple application that keeps track of items borrowers check out. So the end user types in the names of /borrowers/ and also types in a list of /items/. Then the end user checks out the /items/ to the /borrowers/. The category that my application would fall under is close to /collection management tools/. Here's a list of a few other applications that do something like what I am aiming for: http://www.makeuseof.com/tag/4-open-source-collection-manager-apps/ In addition to the application keeping track of who has what, I would like to code the date the items are out, which borrowers have not borrowed anything in the last month, and so on. That said, I need to setup some kind of database like file. I don't want to have a database server though. The reason I want to build a new tool is because: A) I want to play around with Python B) My friend needs the application to be simple and geared to his needs without too many extra bells & whistles -------------------------------------- My method: I was thinking of using the lxmal module to construct a XML file to read/write all the information. I figured this was the easiest way to do what I need since the information is setup as a tree. (Easy to think about and see) Example: John Doe Item1:Item2:||2011/4/2 Mary Doe Item3||2011/7/22 Item1 2011/2/1 32 Item2 2011/2/1 22 Item3 2011/2/1 1 The application will not be used in an enterprise kind of environment. The application is meant to hold about 80 borrowers and about 100 items and that's about it. Is this a good way to go about my project? Is there a better & easier way? I don't want to trade off "better" with "easy". Someone once suggested on Freenode #Python that I should use a sql database. I don't remember the name of it. It was something like lightsql or something like that. That particular database didn't use a server end. I guess it spit out a txt database or something... This might be a good time to mention I know very little about database construction or sql commands. Anyhow, I am looking forward to hearing opinion's and suggestions. Thanks! -- -Joel M -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Oct 29 19:29:59 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 29 Oct 2011 19:29:59 +0200 Subject: [Tutor] Method to create small and simple database References: <4EAC28EB.8030102@gmail.com> Message-ID: Joel Montes de Oca wrote: > Hello everyone, > > About me: > > This is the first time I post to Tutor at Python.org. > > I am brand spanking new to Python. I can create simple application, gone > through a few tutorials and watched the Google Python 2 day class on > Youtube. (List of classes: http://goo.gl/Ud5rg) > > Just yesterday I figured out how to load up a GUI made in Glade and pass > singles around and what not. Huge accomplishment for me since > documentation is a bit shaky for noobs like me. :) > > I have some programming knowledge. I learned (self tough) VB when I was > in middle school and then did a intro to C++ in college. Of course > mentioning that is trivial since I haven't done any programming for > about 5 years or so.. But I do know basic concepts. Just need a little > push in the right direction.. > > -------------------------------------- > > I think I know how to design my application but I would like to put it > on here for you guys to review and provide me with feedback/suggestions > as to the best way to go about it. > > -------------------------------------- > > The application: > > I want to build a simple application that keeps track of items borrowers > check out. So the end user types in the names of /borrowers/ and also > types in a list of /items/. Then the end user checks out the /items/ to > the /borrowers/. > > The category that my application would fall under is close to > /collection management tools/. Here's a list of a few other applications > that do something like what I am aiming for: > http://www.makeuseof.com/tag/4-open-source-collection-manager-apps/ > > In addition to the application keeping track of who has what, I would > like to code the date the items are out, which borrowers have not > borrowed anything in the last month, and so on. That said, I need to > setup some kind of database like file. I don't want to have a database > server though. > > The reason I want to build a new tool is because: > > A) I want to play around with Python > B) My friend needs the application to be simple and geared to his > needs without too many extra bells & whistles > > > -------------------------------------- > > > My method: > > I was thinking of using the lxmal module to construct a XML file to > read/write all the information. > > I figured this was the easiest way to do what I need since the > information is setup as a tree. (Easy to think about and see) Example: > > > > > John Doe > > Item1:Item2:||2011/4/2 > > Mary Doe > > Item3||2011/7/22 > > > > > Item1 > > 2011/2/1 > > 32 > > Item2 > > 2011/2/1 > > 22 > > Item3 > > 2011/2/1 > > 1 > > > > The application will not be used in an enterprise kind of environment. > The application is meant to hold about 80 borrowers and about 100 items > and that's about it. > > Is this a good way to go about my project? Is there a better & easier way? > > I don't want to trade off "better" with "easy". Someone once suggested > on Freenode #Python that I should use a sql database. I don't remember > the name of it. It was something like lightsql or something like that. > That particular database didn't use a server end. I guess it spit out a > txt database or something... This might be a good time to mention I know > very little about database construction or sql commands. > > Anyhow, I am looking forward to hearing opinion's and suggestions. Well, using sqlite http://docs.python.org/library/sqlite3.html may be both better and easier than lxml, but for the tiny amount of data you are planning to handle you can also make do with a few of Python's lists and dicts, and use pickle http://docs.python.org/library/pickle.html to save the data when you're done. It won't get easier than that. From fomcl at yahoo.com Sat Oct 29 19:46:01 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 29 Oct 2011 10:46:01 -0700 (PDT) Subject: [Tutor] PyQt book advise Message-ID: <1319910361.65080.YahooMailNeo@web110715.mail.gq1.yahoo.com> Hi, I'm looking for a book about PyQt. Can anybody recommend a good book? My shortlist is: Rapid GUI Programming with Python and QT: The Definitive Guide to PyQt Programming (Prentice Hall Open Source Software Development by Mark Summerfield Introduction to Python Programming and Developing GUI Applications with PyQT by B. M. Harwani? I have another book by Summerfield, and it's VERY good, but it's twice as expensive as the other book. ? Thank you in advance! Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From joelmontes01 at gmail.com Sat Oct 29 20:28:39 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Sat, 29 Oct 2011 14:28:39 -0400 Subject: [Tutor] Method to create small and simple database In-Reply-To: <4EAC4280.1050003@gmail.com> References: <4EAC28EB.8030102@gmail.com> <4EAC4280.1050003@gmail.com> Message-ID: <4EAC45D7.9000607@gmail.com> On Sat Oct 29 14:14:24 2011, Joel Montes de Oca wrote: > > On Sat Oct 29 13:29:59 2011, Peter Otten wrote: >> >> Joel Montes de Oca wrote: >> >>> >>> Hello everyone, >>> >>> About me: >>> >>> This is the first time I post to Tutor at Python.org. >>> >>> I am brand spanking new to Python. I can create simple application, >>> gone >>> through a few tutorials and watched the Google Python 2 day class on >>> Youtube. (List of classes: http://goo.gl/Ud5rg) >>> >>> Just yesterday I figured out how to load up a GUI made in Glade and >>> pass >>> singles around and what not. Huge accomplishment for me since >>> documentation is a bit shaky for noobs like me. :) >>> >>> I have some programming knowledge. I learned (self tough) VB when I was >>> in middle school and then did a intro to C++ in college. Of course >>> mentioning that is trivial since I haven't done any programming for >>> about 5 years or so.. But I do know basic concepts. Just need a little >>> push in the right direction.. >>> >>> -------------------------------------- >>> >>> I think I know how to design my application but I would like to put it >>> on here for you guys to review and provide me with feedback/suggestions >>> as to the best way to go about it. >>> >>> -------------------------------------- >>> >>> The application: >>> >>> I want to build a simple application that keeps track of items >>> borrowers >>> check out. So the end user types in the names of /borrowers/ and also >>> types in a list of /items/. Then the end user checks out the /items/ to >>> the /borrowers/. >>> >>> The category that my application would fall under is close to >>> /collection management tools/. Here's a list of a few other >>> applications >>> that do something like what I am aiming for: >>> http://www.makeuseof.com/tag/4-open-source-collection-manager-apps/ >>> >>> In addition to the application keeping track of who has what, I would >>> like to code the date the items are out, which borrowers have not >>> borrowed anything in the last month, and so on. That said, I need to >>> setup some kind of database like file. I don't want to have a database >>> server though. >>> >>> The reason I want to build a new tool is because: >>> >>> A) I want to play around with Python >>> B) My friend needs the application to be simple and geared to his >>> needs without too many extra bells& whistles >>> >>> >>> -------------------------------------- >>> >>> >>> My method: >>> >>> I was thinking of using the lxmal module to construct a XML file to >>> read/write all the information. >>> >>> I figured this was the easiest way to do what I need since the >>> information is setup as a tree. (Easy to think about and see) Example: >>> >>> >>> >>> >>> John Doe >>> >>> Item1:Item2:||2011/4/2 >>> >>> Mary Doe >>> >>> Item3||2011/7/22 >>> >>> >>> >>> >>> Item1 >>> >>> 2011/2/1 >>> >>> 32 >>> >>> Item2 >>> >>> 2011/2/1 >>> >>> 22 >>> >>> Item3 >>> >>> 2011/2/1 >>> >>> 1 >>> >>> >>> >>> The application will not be used in an enterprise kind of environment. >>> The application is meant to hold about 80 borrowers and about 100 items >>> and that's about it. >>> >>> Is this a good way to go about my project? Is there a better& easier >>> way? >>> >>> I don't want to trade off "better" with "easy". Someone once suggested >>> on Freenode #Python that I should use a sql database. I don't remember >>> the name of it. It was something like lightsql or something like that. >>> That particular database didn't use a server end. I guess it spit out a >>> txt database or something... This might be a good time to mention I >>> know >>> very little about database construction or sql commands. >>> >>> Anyhow, I am looking forward to hearing opinion's and suggestions. >> >> >> Well, using sqlite >> >> http://docs.python.org/library/sqlite3.html >> >> may be both better and easier than lxml, but for the tiny amount of >> data you >> are planning to handle you can also make do with a few of Python's >> lists and >> dicts, and use pickle >> >> http://docs.python.org/library/pickle.html >> >> to save the data when you're done. It won't get easier than that. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > > Awesome Peter, > > Yea, sqlite3 was what the good folks on irc.freenode.net #Python told > me to use but the pickle module seems like the simpliest way to get > the job done. > > I'll look into both of them. I'm going to have to rethink how I am > going to build the program using sqlite or pickle(). > > Thanks again > > -Joel M. After looking at the Python module documentation for sqlite3 (http://docs.python.org/library/sqlite3.html#module-sqlite3), it seems to me it's the best way to make the small database that I am looking for. Now I need to look for a basic tutorial on constructing a simple database (tables, rows, keys) and how to connect all that stuff together. If anyone happens to know of a good intro tutorial or documentation to database concepts, please forward it to me. Thanks! From thudfoo at gmail.com Sat Oct 29 21:19:33 2011 From: thudfoo at gmail.com (xDog Walker) Date: Sat, 29 Oct 2011 12:19:33 -0700 Subject: [Tutor] Method to create small and simple database In-Reply-To: <4EAC45D7.9000607@gmail.com> References: <4EAC28EB.8030102@gmail.com> <4EAC4280.1050003@gmail.com> <4EAC45D7.9000607@gmail.com> Message-ID: <201110291219.34033.thudfoo@gmail.com> On Saturday 2011 October 29 11:28, Joel Montes de Oca wrote: > After looking at the Python module documentation for sqlite3 > (http://docs.python.org/library/sqlite3.html#module-sqlite3), it seems > to me it's the best way to make the small database that I am looking for. First, have a look at shelve, it is in the std library. -- I have seen the future and I am not in it. From alan.gauld at btinternet.com Sun Oct 30 00:58:51 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Oct 2011 23:58:51 +0100 Subject: [Tutor] Method to create small and simple database In-Reply-To: <4EAC45D7.9000607@gmail.com> References: <4EAC28EB.8030102@gmail.com> <4EAC4280.1050003@gmail.com> <4EAC45D7.9000607@gmail.com> Message-ID: On 29/10/11 19:28, Joel Montes de Oca wrote: > After looking at the Python module documentation for sqlite3 > (http://docs.python.org/library/sqlite3.html#module-sqlite3), it seems > to me it's the best way to make the small database that I am looking for. SQLlite is a great way to build small scale SQL databases. However for this app I'd probably second the advice to use shelve. Shelve acts like a dictionary in a file so you can associate a list of items with a user very very easily. > Now I need to look for a basic tutorial on constructing a simple > database (tables, rows, keys) and how to connect all that stuff > together. If anyone happens to know of a good intro tutorial or > documentation to database concepts, please forward it to me. You can try the database topic in my tutorial(see below). It's only available for Python v2 at present but the translation to Python v3 (if that's what you are using) is trivial. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Sun Oct 30 02:31:38 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 29 Oct 2011 18:31:38 -0700 Subject: [Tutor] Installing the uncertainties module Message-ID: The uncertainties module () is now available for 64-bit Python 3.2. I've downloaded uncertainties-1.8.tar.gz. I need some utility that will handle both .gz and .tar, I presume. Looking for recommendations. Dick Moores Python 3.2.2 64-bit Win 7 From steve at pearwood.info Sun Oct 30 02:56:57 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 30 Oct 2011 12:56:57 +1100 Subject: [Tutor] Installing the uncertainties module In-Reply-To: References: Message-ID: <4EACAEE9.2080907@pearwood.info> Richard D. Moores wrote: > The uncertainties module () > is now available for 64-bit Python 3.2. I've downloaded > uncertainties-1.8.tar.gz. I need some utility that will handle both > .gz and .tar, I presume. Looking for recommendations. Winzip handles .tar.gz files, either separately or together. http://kb.winzip.com/kb/entry/254 So does Python: see the tarfile module. http://docs.python.org/library/tarfile.html -- Steven From rdmoores at gmail.com Sun Oct 30 05:37:01 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 29 Oct 2011 21:37:01 -0700 Subject: [Tutor] Installing the uncertainties module In-Reply-To: References: Message-ID: On Sat, Oct 29, 2011 at 18:31, Richard D. Moores wrote: > The uncertainties module () > is now available for 64-bit Python 3.2. I've downloaded > uncertainties-1.8.tar.gz. I need some utility that will handle both > .gz and .tar, I presume. Looking for recommendations. > > Dick Moores > Python 3.2.2 > 64-bit Win 7 > Thanks for the suggestions. Right after I posted, I remembered < http://www.snapfiles.com/freeware/freeware.html>, and went with Peazip, which did the job. I am curious about how I could have done this just with the tarfile module. I'll look into that. Dick Moores -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Oct 30 05:46:11 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 30 Oct 2011 15:46:11 +1100 Subject: [Tutor] Installing the uncertainties module In-Reply-To: References: Message-ID: On 10/30/2011 12:31 PM, Richard D. Moores wrote: > The uncertainties module () > is now available for 64-bit Python 3.2. I've downloaded > uncertainties-1.8.tar.gz. I need some utility that will handle both > .gz and .tar, I presume. Looking for recommendations. 7zip has always been my multi-format compressor of choice on Windows. From rdmoores at gmail.com Sun Oct 30 05:55:53 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 29 Oct 2011 21:55:53 -0700 Subject: [Tutor] Installing the uncertainties module In-Reply-To: References: Message-ID: On Sat, Oct 29, 2011 at 21:37, Richard D. Moores wrote: > > > On Sat, Oct 29, 2011 at 18:31, Richard D. Moores wrote: >> >> The uncertainties module () >> is now available for 64-bit Python 3.2. I've downloaded >> uncertainties-1.8.tar.gz. I need some utility that will handle both >> .gz and .tar, I presume. Looking for recommendations. >> >> Dick Moores >> Python 3.2.2 >> 64-bit Win 7 > > Thanks for the suggestions. Right after I posted, I remembered , and went with??Peazip, which did the job. > I am curious about how I could have done this just with??the tarfile module. I'll look into that. Hm. Problem: >>> import tarfile >>> tar = tarfile.open("C:\Users\Richard\Desktop\uncertainties-1.8.tar.gz") File "", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape What to do? Thanks, Dick From lie.1296 at gmail.com Sun Oct 30 06:06:16 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 30 Oct 2011 16:06:16 +1100 Subject: [Tutor] Installing the uncertainties module In-Reply-To: References: Message-ID: On 10/30/2011 03:55 PM, Richard D. Moores wrote: > On Sat, Oct 29, 2011 at 21:37, Richard D. Moores wrote: >> >> >> On Sat, Oct 29, 2011 at 18:31, Richard D. Moores wrote: >>> >>> The uncertainties module () >>> is now available for 64-bit Python 3.2. I've downloaded >>> uncertainties-1.8.tar.gz. I need some utility that will handle both >>> .gz and .tar, I presume. Looking for recommendations. >>> >>> Dick Moores >>> Python 3.2.2 >>> 64-bit Win 7 >> >> Thanks for the suggestions. Right after I posted, I remembered, and went with Peazip, which did the job. >> I am curious about how I could have done this just with the tarfile module. I'll look into that. > > Hm. Problem: > >>>> import tarfile >>>> tar = tarfile.open("C:\Users\Richard\Desktop\uncertainties-1.8.tar.gz") > File "", line 1 > SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes > in position 2-4: truncated \UXXXXXXXX escape > use forward slash for file names even in Windows, or you had to escape the backslashes 'C:\\Users\\Richard\\Desktop\\uncertainties-1.8.tar.gz' or use raw string r"C:\Users\Richard\Desktop\uncertainties-1.8.tar.gz" From rdmoores at gmail.com Sun Oct 30 06:33:49 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 29 Oct 2011 22:33:49 -0700 Subject: [Tutor] Installing the uncertainties module In-Reply-To: References: Message-ID: On Sat, Oct 29, 2011 at 22:06, Lie Ryan wrote: > On 10/30/2011 03:55 PM, Richard D. Moores wrote: >> >> Hm. Problem: >> >>>>> import tarfile >>>>> tar = tarfile.open("C:\Users\Richard\Desktop\uncertainties-1.8.tar.gz") >> >> ? File "", line 1 >> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes >> in position 2-4: truncated \UXXXXXXXX escape >> > > use forward slash for file names even in Windows, or you had to escape the > backslashes 'C:\\Users\\Richard\\Desktop\\uncertainties-1.8.tar.gz' or use > raw string r"C:\Users\Richard\Desktop\uncertainties-1.8.tar.gz" Should have thought of that. >>> tar = tarfile.open("C:/Users/Richard/Desktop/uncertainties-1.8.tar.gz") >>> tar.extractall() >>> tar.close() >>> Thanks! Dick From rinu.matrix at gmail.com Sun Oct 30 14:23:04 2011 From: rinu.matrix at gmail.com (Rinu Boney) Date: Sun, 30 Oct 2011 18:53:04 +0530 Subject: [Tutor] Setting Up Emacs Message-ID: I am New To Python. I Would Like To Setup Emacs As A Python IDE. I Don't Know Anything About Emacs! Can Someone Help Me ? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Oct 30 16:25:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 31 Oct 2011 02:25:23 +1100 Subject: [Tutor] Setting Up Emacs In-Reply-To: References: Message-ID: <4EAD6C63.6020105@pearwood.info> Rinu Boney wrote: > I am New To Python. > I Would Like To Setup Emacs As A Python IDE. > I Don't Know Anything About Emacs! If you don't know anything about emacs, and you don't know anything about Python, why do you want to make things ten times more difficult by learning a new language AND the most heavyweight, complex editor at the same time? I recommend you use a more friendly editor. You haven't mentioned what operating system you are using. If you are using Linux with the KDE desktop, I recommend you use a good, modern GUI editor like Kate as your editor. Other people might prefer different editors, but I've come to like Kate the best. Personally, I recommend against IDEs. I find that they are over-complicated and get in the way. I've seen too many people struggling because their IDE changes the way their code works. I recommend you keep your code open in an editor, an interactive session open in a good xterm, and a second xterm tab open for running your script. That's my preference. But, if you still want to use Emacs as a Python IDE, have you tried searching for "python emacs ide"? https://duckduckgo.com/html/?q=python%20emacs%20ide -- Steven From tim at akwebsoft.com Sun Oct 30 16:53:15 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sun, 30 Oct 2011 07:53:15 -0800 Subject: [Tutor] Setting Up Emacs In-Reply-To: <4EAD6C63.6020105@pearwood.info> References: <4EAD6C63.6020105@pearwood.info> Message-ID: <20111030155315.GB10605@akwebsoft.com> * Steven D'Aprano [111030 07:40]: > Rinu Boney wrote: > >I am New To Python. > >I Would Like To Setup Emacs As A Python IDE. > >I Don't Know Anything About Emacs! > > If you don't know anything about emacs, and you don't know anything > about Python, why do you want to make things ten times more difficult by > learning a new language AND the most heavyweight, complex editor at the > same time? > > I recommend you use a more friendly editor. You haven't mentioned what > operating system you are using. If you are using Linux with the KDE > desktop, I recommend you use a good, modern GUI editor like Kate as your > editor. Other people might prefer different editors, but I've come to > like Kate the best. I've used emacs extensively in the past and now use vim. They are both rewarding to use, but to support Steven, it could be a nightmare for Rinu to to learn both python and emacs or vim. I believe that idle is part of the python distro on both linux and darwin (Mac OSX). That is worth consideration, I would think. If Rinu is on windows, there is pythonwin and there is an extremely good, well supported and easy-to-learn shareware editor called Boxer. I would recommend either to any programmer in a windows environment. > Personally, I recommend against IDEs. I find that they are > over-complicated and get in the way. I've seen too many people > struggling because their IDE changes the way their code works. I > recommend you keep your code open in an editor, an interactive session > open in a good xterm, and a second xterm tab open for running your > script. That's my preference. Yeah. What he said. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From alan.gauld at btinternet.com Sun Oct 30 18:20:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Oct 2011 17:20:18 +0000 Subject: [Tutor] Setting Up Emacs In-Reply-To: References: Message-ID: On 30/10/11 13:23, Rinu Boney wrote: > I am New To Python. Welcome to the group. Do you know any other languages or are you new to programming as well? > I Would Like To Setup Emacs As A Python IDE. > I Don't Know Anything About Emacs! If you don;t know emacs then don;t bother. emacs is a fantastic editor and general user environment but it is big and complex and takes long time to gt "just right" for you. If you were already an emacs user I'd say go right ahead, but as a newbie learning Python will be a big enough challenge. If you are used to IDEs like MS Visual Studio or Eclipse then the best bet is to use Eclipse with the PyDev plug-in. (Or Netbeans if you prefer it to Eclipse, I've used and liked both, and they both support Python well) If you are on a Mac you can use the Apple XDeveloper tools (XCode etc) or install Eclipse. If you are not a died in the wool IDE user then try something simpler like IDLE or Pythonwin for Windows (But the fact you even mention Emacs suggests you are not using Windows) Or go for the minimalist approach suggested by Stephen. Many of us(including me) favor 3 separate windows - a text editor to type the final code - an interpreter to try out ideas and snippets - A vanilla OS prompt to test the "production" code Occasionally you may open a debugger window too, but mostly in Python you don't need that. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From tim at akwebsoft.com Sun Oct 30 18:41:48 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sun, 30 Oct 2011 09:41:48 -0800 Subject: [Tutor] Setting Up Emacs In-Reply-To: References: Message-ID: <20111030174148.GC9335@akwebsoft.com> * Alan Gauld [111030 09:26]: > On 30/10/11 13:23, Rinu Boney wrote: > >I am New To Python. > > Welcome to the group. > Do you know any other languages or are you new to programming > as well? > > >I Would Like To Setup Emacs As A Python IDE. > >I Don't Know Anything About Emacs! > > If you are on a Mac you can use the Apple XDeveloper > tools (XCode etc) or install Eclipse. > If you are not a died in the wool IDE user then try something > simpler like IDLE or Pythonwin for Windows (But the fact you > even mention Emacs suggests you are not using Windows) IDLE came pre-installed on my mac. I believe that I had to add it on my ubuntu PC. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From joelmontes01 at gmail.com Sun Oct 30 20:33:23 2011 From: joelmontes01 at gmail.com (Joel M.) Date: Sun, 30 Oct 2011 15:33:23 -0400 Subject: [Tutor] Method to create small and simple database In-Reply-To: References: <4EAC28EB.8030102@gmail.com> <4EAC4280.1050003@gmail.com> <4EAC45D7.9000607@gmail.com> Message-ID: On Sat, Oct 29, 2011 at 6:58 PM, Alan Gauld wrote: > On 29/10/11 19:28, Joel Montes de Oca wrote: > > After looking at the Python module documentation for sqlite3 >> (http://docs.python.org/**library/sqlite3.html#module-**sqlite3), >> it seems >> to me it's the best way to make the small database that I am looking for. >> > > SQLlite is a great way to build small scale SQL databases. > However for this app I'd probably second the advice to use shelve. > Shelve acts like a dictionary in a file so you can associate a list of > items with a user very very easily. > > > > Now I need to look for a basic tutorial on constructing a simple >> database (tables, rows, keys) and how to connect all that stuff >> together. If anyone happens to know of a good intro tutorial or >> documentation to database concepts, please forward it to me. >> > > You can try the database topic in my tutorial(see below). > It's only available for Python v2 at present but the translation > to Python v3 (if that's what you are using) is trivial. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > I will take a look into Shelve and Alan's tutorial sometime this coming week. Keep the suggestions coming if there's more. :) -Joel M. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Mon Oct 31 03:52:40 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sun, 30 Oct 2011 21:52:40 -0500 Subject: [Tutor] Setting Up Emacs In-Reply-To: <20111030174148.GC9335@akwebsoft.com> References: <20111030174148.GC9335@akwebsoft.com> Message-ID: > > On 30/10/11 13:23, Rinu Boney wrote: > > >I am New To Python. > > > > > >I Would Like To Setup Emacs As A Python IDE. > > >I Don't Know Anything About Emacs! > > > > As others have also mentioned, try IDLE. It comes packaged with Python for Windows and is easily available for Python on Linux. It will do most of what you really, really need. --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From neubyr at gmail.com Mon Oct 31 05:40:14 2011 From: neubyr at gmail.com (neubyr) Date: Sun, 30 Oct 2011 23:40:14 -0500 Subject: [Tutor] importing modules and packages Message-ID: Is it possible to tell whether import statement is importing a module or package? I am going through some example code with some import statements - like 'import os, sys, time', 'import packed'. I know os, sys and time are (built-in) modules and 'packed' is a package here . But can I determine whether it's a package or module using any command/method or by following some naming convention? - thanks, neuby.r From cyclicflux at yahoo.com Mon Oct 31 05:40:36 2011 From: cyclicflux at yahoo.com (cyclicflux at yahoo.com) Date: Mon, 31 Oct 2011 00:40:36 -0400 Subject: [Tutor] Python Editor to Start Out WithTutor Digest, Vol 92, Issue 123 In-Reply-To: References: Message-ID: With reference to a beginning editor, if you want to go heavy-weight go vim. Now I'm not a python expert, but I will say vim is prolly a little harder than emacs, however scripting in vim has many similarities to various types in python. The python forloop is definitely very similar to that of vim. Plus, vim may be configured for use with ipython(enhanced interactive python shell) But those are as previously mentioned very complex editors. There are others that although aren't totally as powerful will make things infinitely easier to learn. The thing that's nice about others that are ready to roll once installed, the ease in use let's you focus on learning the programming. Some of these more user friendly editors are: spyder(python editor with lots of features), or geany, which is probably the more widespread. These will with a click or few clicks provide syntax+highlighting+syntax error-checking setup. This can be difficult in the traditional text editors vim+ emacs,(I know vim) have to be compiled with certain support, as well as then have plugins installed/created, and alot of things configured. But if you wanna go w/a text editor+ python try out swaroop's site. He has two books, A Byte of Python, and A Byte of Vim. They are great for introduction stuff. But in the end learning one well makes it far easier than learning both at the same time. Good Luck!! Connected by DROID on Verizon Wireless -----Original message----- From: tutor-request at python.org To: tutor at python.org Sent: Mon, Oct 31, 2011 02:55:23 GMT+00:00 Subject: Tutor Digest, Vol 92, Issue 123 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Setting Up Emacs (Rinu Boney) 2. Re: Setting Up Emacs (Steven D'Aprano) 3. Re: Setting Up Emacs (Tim Johnson) 4. Re: Setting Up Emacs (Alan Gauld) 5. Re: Setting Up Emacs (Tim Johnson) 6. Re: Method to create small and simple database (Joel M.) 7. Re: Setting Up Emacs (Bill Allen) ---------------------------------------------------------------------- Message: 1 Date: Sun, 30 Oct 2011 18:53:04 +0530 From: Rinu Boney To: tutor at python.org Subject: [Tutor] Setting Up Emacs Message-ID: Content-Type: text/plain; charset="iso-8859-1" I am New To Python. I Would Like To Setup Emacs As A Python IDE. I Don't Know Anything About Emacs! Can Someone Help Me ? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Mon, 31 Oct 2011 02:25:23 +1100 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] Setting Up Emacs Message-ID: <4EAD6C63.6020105 at pearwood.info> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Rinu Boney wrote: > I am New To Python. > I Would Like To Setup Emacs As A Python IDE. > I Don't Know Anything About Emacs! If you don't know anything about emacs, and you don't know anything about Python, why do you want to make things ten times more difficult by learning a new language AND the most heavyweight, complex editor at the same time? I recommend you use a more friendly editor. You haven't mentioned what operating system you are using. If you are using Linux with the KDE desktop, I recommend you use a good, modern GUI editor like Kate as your editor. Other people might prefer different editors, but I've come to like Kate the best. Personally, I recommend against IDEs. I find that they are over-complicated and get in the way. I've seen too many people struggling because their IDE changes the way their code works. I recommend you keep your code open in an editor, an interactive session open in a good xterm, and a second xterm tab open for running your script. That's my preference. But, if you still want to use Emacs as a Python IDE, have you tried searching for "python emacs ide"? https://duckduckgo.com/html/?q=python%20emacs%20ide -- Steven ------------------------------ Message: 3 Date: Sun, 30 Oct 2011 07:53:15 -0800 From: Tim Johnson To: tutor at python.org Subject: Re: [Tutor] Setting Up Emacs Message-ID: <20111030155315.GB10605 at akwebsoft.com> Content-Type: text/plain; charset=us-ascii * Steven D'Aprano [111030 07:40]: > Rinu Boney wrote: > >I am New To Python. > >I Would Like To Setup Emacs As A Python IDE. > >I Don't Know Anything About Emacs! > > If you don't know anything about emacs, and you don't know anything > about Python, why do you want to make things ten times more difficult by > learning a new language AND the most heavyweight, complex editor at the > same time? > > I recommend you use a more friendly editor. You haven't mentioned what > operating system you are using. If you are using Linux with the KDE > desktop, I recommend you use a good, modern GUI editor like Kate as your > editor. Other people might prefer different editors, but I've come to > like Kate the best. I've used emacs extensively in the past and now use vim. They are both rewarding to use, but to support Steven, it could be a nightmare for Rinu to to learn both python and emacs or vim. I believe that idle is part of the python distro on both linux and darwin (Mac OSX). That is worth consideration, I would think. If Rinu is on windows, there is pythonwin and there is an extremely good, well supported and easy-to-learn shareware editor called Boxer. I would recommend either to any programmer in a windows environment. > Personally, I recommend against IDEs. I find that they are > over-complicated and get in the way. I've seen too many people > struggling because their IDE changes the way their code works. I > recommend you keep your code open in an editor, an interactive session > open in a good xterm, and a second xterm tab open for running your > script. That's my preference. Yeah. What he said. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com ------------------------------ Message: 4 Date: Sun, 30 Oct 2011 17:20:18 +0000 From: Alan Gauld To: tutor at python.org Subject: Re: [Tutor] Setting Up Emacs Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 30/10/11 13:23, Rinu Boney wrote: > I am New To Python. Welcome to the group. Do you know any other languages or are you new to programming as well? > I Would Like To Setup Emacs As A Python IDE. > I Don't Know Anything About Emacs! If you don;t know emacs then don;t bother. emacs is a fantastic editor and general user environment but it is big and complex and takes long time to gt "just right" for you. If you were already an emacs user I'd say go right ahead, but as a newbie learning Python will be a big enough challenge. If you are used to IDEs like MS Visual Studio or Eclipse then the best bet is to use Eclipse with the PyDev plug-in. (Or Netbeans if you prefer it to Eclipse, I've used and liked both, and they both support Python well) If you are on a Mac you can use the Apple XDeveloper tools (XCode etc) or install Eclipse. If you are not a died in the wool IDE user then try something simpler like IDLE or Pythonwin for Windows (But the fact you even mention Emacs suggests you are not using Windows) Or go for the minimalist approach suggested by Stephen. Many of us(including me) favor 3 separate windows - a text editor to type the final code - an interpreter to try out ideas and snippets - A vanilla OS prompt to test the "production" code Occasionally you may open a debugger window too, but mostly in Python you don't need that. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ------------------------------ Message: 5 Date: Sun, 30 Oct 2011 09:41:48 -0800 From: Tim Johnson To: tutor at python.org Subject: Re: [Tutor] Setting Up Emacs Message-ID: <20111030174148.GC9335 at akwebsoft.com> Content-Type: text/plain; charset=us-ascii * Alan Gauld [111030 09:26]: > On 30/10/11 13:23, Rinu Boney wrote: > >I am New To Python. > > Welcome to the group. > Do you know any other languages or are you new to programming > as well? > > >I Would Like To Setup Emacs As A Python IDE. > >I Don't Know Anything About Emacs! > > If you are on a Mac you can use the Apple XDeveloper > tools (XCode etc) or install Eclipse. > If you are not a died in the wool IDE user then try something > simpler like IDLE or Pythonwin for Windows (But the fact you > even mention Emacs suggests you are not using Windows) IDLE came pre-installed on my mac. I believe that I had to add it on my ubuntu PC. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com ------------------------------ Message: 6 Date: Sun, 30 Oct 2011 15:33:23 -0400 From: "Joel M." To: Tutor Python Subject: Re: [Tutor] Method to create small and simple database Message-ID: Content-Type: text/plain; charset="iso-8859-1" On Sat, Oct 29, 2011 at 6:58 PM, Alan Gauld wrote: > On 29/10/11 19:28, Joel Montes de Oca wrote: > > After looking at the Python module documentation for sqlite3 >> (http://docs.python.org/**library/sqlite3.html#module-**sqlite3), >> it seems >> to me it's the best way to make the small database that I am looking for. >> > > SQLlite is a great way to build small scale SQL databases. > However for this app I'd probably second the advice to use shelve. > Shelve acts like a dictionary in a file so you can associate a list of > items with a user very very easily. > > > > Now I need to look for a basic tutorial on constructing a simple >> database (tables, rows, keys) and how to connect all that stuff >> together. If anyone happens to know of a good intro tutorial or >> documentation to database concepts, please forward it to me. >> > > You can try the database topic in my tutorial(see below). > It's only available for Python v2 at present but the translation > to Python v3 (if that's what you are using) is trivial. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > I will take a look into Shelve and Alan's tutorial sometime this coming week. Keep the suggestions coming if there's more. :) -Joel M. -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 7 Date: Sun, 30 Oct 2011 21:52:40 -0500 From: Bill Allen To: tutor at python.org Subject: Re: [Tutor] Setting Up Emacs Message-ID: Content-Type: text/plain; charset="iso-8859-1" > > On 30/10/11 13:23, Rinu Boney wrote: > > >I am New To Python. > > > > > >I Would Like To Setup Emacs As A Python IDE. > > >I Don't Know Anything About Emacs! > > > > As others have also mentioned, try IDLE. It comes packaged with Python for Windows and is easily available for Python on Linux. It will do most of what you really, really need. --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 92, Issue 123 ************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 31 10:20:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 31 Oct 2011 09:20:00 +0000 Subject: [Tutor] Python Editor to Start Out WithTutor Digest, Vol 92, Issue 123 In-Reply-To: References: Message-ID: On 31/10/11 04:40, cyclicflux at yahoo.com wrote: > With reference to a beginning editor, I agree with most of this but... > ... scripting in vim has many similarities to various types > in python. The python forloop is definitely very similar Thats probably because you have a vim that has been compiled with Python scripting built in. There are various scripting options for vim and the original scripting language was not like Python at all! So it will depend on which vim scripting engine you have installed. > with a click or few clicks provide syntax+highlighting+syntax > error-checking setup. This can be difficult in the traditional text > editors vim+ emacs,(I know vim) have to be compiled with certain > support, as well as then have plugins installed/created, It shouldn't be the case. The latest versions of both vim and emacs come with syntax highlighting set up by default and auto recognize many languages (based on file extension). So this should not be a deciding factor. Much more of an issue for a newbie is, in both vim and emacs, the completely non standard keybindings. Neither use the "normal" keys for movement, cut n paste, searching etc And its adapting to the keybindings that will (a) take time and (b) be a source of frustration while learning. And both editors are only really efficient if you drive them from the keyboard, they do support mice/menus etc but they are not optimised for that. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Oct 31 10:38:07 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 31 Oct 2011 20:38:07 +1100 Subject: [Tutor] importing modules and packages In-Reply-To: References: Message-ID: <4EAE6C7F.6090003@pearwood.info> neubyr wrote: > Is it possible to tell whether import statement is importing a module > or package? I am going through some example code with some import > statements - like 'import os, sys, time', 'import packed'. I know os, > sys and time are (built-in) modules and 'packed' is a package here . > But can I determine whether it's a package or module using any > command/method or by following some naming convention? Consider: >>> import curses # A package. >>> curses.__file__ '/usr/lib/python2.5/curses/__init__.pyc' >>> curses.__path__ ['/usr/lib/python2.5/curses'] Compare to: >>> import string # A plain module. >>> string.__file__ '/usr/lib/python2.5/string.pyc' >>> string.__path__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__path__' Does this help? -- Steven From rinu.matrix at gmail.com Mon Oct 31 13:56:11 2011 From: rinu.matrix at gmail.com (Rinu Boney) Date: Mon, 31 Oct 2011 18:26:11 +0530 Subject: [Tutor] Tutor Digest, Vol 92, Issue 123 In-Reply-To: References: Message-ID: I Use Windows.I Already Know C/C++ which makes python syntax seem very easy. Maybe Setting Up Emacs With Python Will Make Me Productive. I Have Eclipse With PyDev. Why Is There Not A Pythonic Emacs? On Mon, Oct 31, 2011 at 8:23 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Setting Up Emacs (Rinu Boney) > 2. Re: Setting Up Emacs (Steven D'Aprano) > 3. Re: Setting Up Emacs (Tim Johnson) > 4. Re: Setting Up Emacs (Alan Gauld) > 5. Re: Setting Up Emacs (Tim Johnson) > 6. Re: Method to create small and simple database (Joel M.) > 7. Re: Setting Up Emacs (Bill Allen) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sun, 30 Oct 2011 18:53:04 +0530 > From: Rinu Boney > To: tutor at python.org > Subject: [Tutor] Setting Up Emacs > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > I am New To Python. > I Would Like To Setup Emacs As A Python IDE. > I Don't Know Anything About Emacs! > Can Someone Help Me ? > Thanks. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20111030/ad7f346e/attachment-0001.html > > > > ------------------------------ > > Message: 2 > Date: Mon, 31 Oct 2011 02:25:23 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Setting Up Emacs > Message-ID: <4EAD6C63.6020105 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Rinu Boney wrote: > > I am New To Python. > > I Would Like To Setup Emacs As A Python IDE. > > I Don't Know Anything About Emacs! > > If you don't know anything about emacs, and you don't know anything > about Python, why do you want to make things ten times more difficult by > learning a new language AND the most heavyweight, complex editor at the > same time? > > I recommend you use a more friendly editor. You haven't mentioned what > operating system you are using. If you are using Linux with the KDE > desktop, I recommend you use a good, modern GUI editor like Kate as your > editor. Other people might prefer different editors, but I've come to > like Kate the best. > > Personally, I recommend against IDEs. I find that they are > over-complicated and get in the way. I've seen too many people > struggling because their IDE changes the way their code works. I > recommend you keep your code open in an editor, an interactive session > open in a good xterm, and a second xterm tab open for running your > script. That's my preference. > > But, if you still want to use Emacs as a Python IDE, have you tried > searching for "python emacs ide"? > > https://duckduckgo.com/html/?q=python%20emacs%20ide > > > > -- > Steven > > > ------------------------------ > > Message: 3 > Date: Sun, 30 Oct 2011 07:53:15 -0800 > From: Tim Johnson > To: tutor at python.org > Subject: Re: [Tutor] Setting Up Emacs > Message-ID: <20111030155315.GB10605 at akwebsoft.com> > Content-Type: text/plain; charset=us-ascii > > * Steven D'Aprano [111030 07:40]: > > Rinu Boney wrote: > > >I am New To Python. > > >I Would Like To Setup Emacs As A Python IDE. > > >I Don't Know Anything About Emacs! > > > > If you don't know anything about emacs, and you don't know anything > > about Python, why do you want to make things ten times more difficult by > > learning a new language AND the most heavyweight, complex editor at the > > same time? > > > > I recommend you use a more friendly editor. You haven't mentioned what > > operating system you are using. If you are using Linux with the KDE > > desktop, I recommend you use a good, modern GUI editor like Kate as your > > editor. Other people might prefer different editors, but I've come to > > like Kate the best. > > I've used emacs extensively in the past and now use vim. They are > both rewarding to use, but to support Steven, it could be a > nightmare for Rinu to to learn both python and emacs or vim. > > I believe that idle is part of the python distro on both linux and > darwin (Mac OSX). That is worth consideration, I would think. > > If Rinu is on windows, there is pythonwin and there is an > extremely good, well supported and easy-to-learn shareware editor > called Boxer. I would recommend either to any programmer in a > windows environment. > > > Personally, I recommend against IDEs. I find that they are > > over-complicated and get in the way. I've seen too many people > > struggling because their IDE changes the way their code works. I > > recommend you keep your code open in an editor, an interactive session > > open in a good xterm, and a second xterm tab open for running your > > script. That's my preference. > > Yeah. What he said. > > -- > Tim > tim at tee jay forty nine dot com or akwebsoft dot com > http://www.akwebsoft.com > > > ------------------------------ > > Message: 4 > Date: Sun, 30 Oct 2011 17:20:18 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Setting Up Emacs > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 30/10/11 13:23, Rinu Boney wrote: > > I am New To Python. > > Welcome to the group. > Do you know any other languages or are you new to programming > as well? > > > I Would Like To Setup Emacs As A Python IDE. > > I Don't Know Anything About Emacs! > > If you don;t know emacs then don;t bother. > emacs is a fantastic editor and general user environment but > it is big and complex and takes long time to gt "just right" > for you. > > If you were already an emacs user I'd say go right ahead, > but as a newbie learning Python will be a big enough challenge. > > If you are used to IDEs like MS Visual Studio or Eclipse then > the best bet is to use Eclipse with the PyDev plug-in. > (Or Netbeans if you prefer it to Eclipse, I've used and > liked both, and they both support Python well) > > If you are on a Mac you can use the Apple XDeveloper > tools (XCode etc) or install Eclipse. > > If you are not a died in the wool IDE user then try something > simpler like IDLE or Pythonwin for Windows (But the fact you > even mention Emacs suggests you are not using Windows) > > Or go for the minimalist approach suggested by Stephen. > Many of us(including me) favor 3 separate windows > - a text editor to type the final code > - an interpreter to try out ideas and snippets > - A vanilla OS prompt to test the "production" code > > Occasionally you may open a debugger window too, > but mostly in Python you don't need that. > > HTH, > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > Message: 5 > Date: Sun, 30 Oct 2011 09:41:48 -0800 > From: Tim Johnson > To: tutor at python.org > Subject: Re: [Tutor] Setting Up Emacs > Message-ID: <20111030174148.GC9335 at akwebsoft.com> > Content-Type: text/plain; charset=us-ascii > > * Alan Gauld [111030 09:26]: > > On 30/10/11 13:23, Rinu Boney wrote: > > >I am New To Python. > > > > Welcome to the group. > > Do you know any other languages or are you new to programming > > as well? > > > > >I Would Like To Setup Emacs As A Python IDE. > > >I Don't Know Anything About Emacs! > > > > If you are on a Mac you can use the Apple XDeveloper > > tools (XCode etc) or install Eclipse. > > If you are not a died in the wool IDE user then try something > > simpler like IDLE or Pythonwin for Windows (But the fact you > > even mention Emacs suggests you are not using Windows) > > IDLE came pre-installed on my mac. I believe that I had to add it > on my ubuntu PC. > > -- > Tim > tim at tee jay forty nine dot com or akwebsoft dot com > http://www.akwebsoft.com > > > ------------------------------ > > Message: 6 > Date: Sun, 30 Oct 2011 15:33:23 -0400 > From: "Joel M." > To: Tutor Python > Subject: Re: [Tutor] Method to create small and simple database > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > On Sat, Oct 29, 2011 at 6:58 PM, Alan Gauld >wrote: > > > On 29/10/11 19:28, Joel Montes de Oca wrote: > > > > After looking at the Python module documentation for sqlite3 > >> (http://docs.python.org/**library/sqlite3.html#module-**sqlite3< > http://docs.python.org/library/sqlite3.html#module-sqlite3>), > >> it seems > >> to me it's the best way to make the small database that I am looking > for. > >> > > > > SQLlite is a great way to build small scale SQL databases. > > However for this app I'd probably second the advice to use shelve. > > Shelve acts like a dictionary in a file so you can associate a list of > > items with a user very very easily. > > > > > > > > Now I need to look for a basic tutorial on constructing a simple > >> database (tables, rows, keys) and how to connect all that stuff > >> together. If anyone happens to know of a good intro tutorial or > >> documentation to database concepts, please forward it to me. > >> > > > > You can try the database topic in my tutorial(see below). > > It's only available for Python v2 at present but the translation > > to Python v3 (if that's what you are using) is trivial. > > > > -- > > Alan G > > Author of the Learn to Program web site > > http://www.alan-g.me.uk/ > > > > > > ______________________________**_________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/**mailman/listinfo/tutor< > http://mail.python.org/mailman/listinfo/tutor> > > > > > > I will take a look into Shelve and Alan's tutorial sometime this coming > week. > > Keep the suggestions coming if there's more. :) > > -Joel M. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20111030/dd2ee420/attachment-0001.html > > > > ------------------------------ > > Message: 7 > Date: Sun, 30 Oct 2011 21:52:40 -0500 > From: Bill Allen > To: tutor at python.org > Subject: Re: [Tutor] Setting Up Emacs > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > > > On 30/10/11 13:23, Rinu Boney wrote: > > > >I am New To Python. > > > > > > > > >I Would Like To Setup Emacs As A Python IDE. > > > >I Don't Know Anything About Emacs! > > > > > > > As others have also mentioned, try IDLE. It comes packaged with Python > for Windows and is easily available for Python on Linux. It will do most > of what you really, really need. > > --Bill > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20111030/ce73f11c/attachment.html > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 92, Issue 123 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joelmontes01 at gmail.com Mon Oct 31 16:41:05 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Mon, 31 Oct 2011 11:41:05 -0400 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly Message-ID: <4EAEC191.3060208@gmail.com> Hello everyone, I am having a little trouble with a block of code that isn't behaving the way I would expect. Maybe you can give me a hand and point where it is going wrong. The function that is not working correctly belongs to a Paper Rock Scissor game I am making. This particular function is responsible to: a) Get the user's choice (Paper, Rock, or Scissors) b) Return the user's choice within the variable choice to the function that called it. The function works correctly as long as the user _does not try to enter a string other than_ 'P', 'R', or 'S'. Logic: Take the user's string and put it in the variable choice. If choice is not 'P', 'R', or 'S'then pass a message to the user and call the function again. If the choice is 'P', 'R', or 'S'then return choice to where it was called from. The problem is this. When the user enters a string other than the valid ones, the if statements catches it and calls the same function again so the user can enter a valid string. But the variable choice does not get assigned the new string entered by the user, instead it is empty. I would expect if the function runs again, the variable choice would be updated to the last value given by the user. The function: ( http://dpaste.com/644857/) def UserChoice (): # The function that returns the choice from the user print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' choice = raw_input('What is your selection?:') if choice.lower() not in ('p', 'r','s'): # Converts the user's choice to lowercase and confirms the choice is valid print 'I am sorry, you entered\'' + choice.upper() + '\' which is an invalid response. Please try again.' raw_input('Press Enter to try again.') UserChoice () # If the choice is not valid, run the function over else: return choice Output with no problems: ( http://dpaste.com/644866/) Welcome to the PRS game. Please select (P) for paper, (R) for Rock, or (S) for Scissors. What is your selection?: s You threw down Scissors while the computer threw down Rock LOOSE Output with problems: ( http://dpaste.com/644868/) Welcome to the PRS game. Please select (P) for paper, (R) for Rock, or (S) for Scissors. What is your selection?: L I am sorry, you entered 'L' which is an invalid response. Please try again. Press Enter to try again. Please select (P) for paper, (R) for Rock, or (S) for Scissors. What is your selection?: s You threw down None while the computer threw down Paper LOOSE Here's the full source code in case the problem is outside of the function: ( http://dpaste.com/644873/) import random # Import the random library def main (): # The main function that gets called from main() print '\nWelcome to the PRS game.\n' choice = UserChoice () # Gets the choice from the user cchoice = ComputerChoice () # Gets the choice from the computer PrintOutcome (choice, cchoice) # Passes both choices to the PrintChoice function for display return 0 def UserChoice (): # The function that returns the choice from the user print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' choice = raw_input('What is your selection?:') if choice.lower() not in ('p', 'r','s'): # Converts the user's choice to lowercase and confirms the choice is valid print 'I am sorry, you entered\'' + choice.upper() + '\' which is an invalid response. Please try again.' raw_input('Press Enter to try again.') UserChoice () # If the choice is not valid, run the function over else: return choice def ComputerChoice (): # The function that returns the choice from the computer PRS = ['Rock', 'Paper', 'Scissors'] # A list of choices cchoice = random.choice(PRS) # Choose a random item from the list return cchoice # Return the function def PrintOutcome (UC, CC): # Function responsable to display the choices and results PRS = ['Rock', 'Paper', 'Scissors'] # Convert the letters to words if UC == 'r': UC = PRS[0] elif UC == 'p': UC = PRS[1] elif UC == 's': UC = PRS[2] print '\n\tYou threw down', UC, 'while the computer threw down', CC +'\n' # find the outcome of the game if UC == CC: print 'We have a tie, both players gain a point!' elif UC == 'Rock' and CC == 'Scissors': print 'WIN' elif UC == 'Paper' and CC == 'Rock': print 'WIN' elif UC == 'Scissors' and CC == 'Paper': print 'WIN' else: print 'LOOSE' return 0 main() I am using Python 2.7 I am running on Ubuntu 11.10 Thanks for any help -- -Joel M. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Mon Oct 31 16:59:47 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Mon, 31 Oct 2011 21:29:47 +0530 Subject: [Tutor] Tutor Digest, Vol 92, Issue 127 In-Reply-To: References: Message-ID: > From: Joel Montes de Oca > To: Tutor Python > Subject: [Tutor] Paper Rock Scissors game - User's choice not returned > properly > Message-ID: <4EAEC191.3060208 at gmail.com> > Content-Type: text/plain; charset="iso-8859-1"; Format="flowed" > > Hello everyone, > > > The function: ( http://dpaste.com/644857/) > > def UserChoice (): # The function that returns the choice from the > user > print 'Please select (P) for paper, (R) for Rock, or (S) for > Scissors.' > choice = raw_input('What is your selection?:') > > if choice.lower() not in ('p', 'r','s'): # Converts the > user's choice to lowercase and confirms the choice is valid > print 'I am sorry, you entered\'' + choice.upper() + > '\' which is an invalid response. Please try again.' > raw_input('Press Enter to try again.') > UserChoice () # If the choice is not valid, run > the function over > You should use return UserChoice() > else: > return choice > > Asokan Pichai SVP - Learning and Development ?Faith consists in believing when it is beyond the power of reason to believe. " Voltaire -------------- next part -------------- An HTML attachment was scrubbed... URL: From joelmontes01 at gmail.com Mon Oct 31 17:03:52 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Mon, 31 Oct 2011 12:03:52 -0400 Subject: [Tutor] Tutor Digest, Vol 92, Issue 127 In-Reply-To: References: Message-ID: <4EAEC6E8.9030009@gmail.com> On Mon 31 Oct 2011 11:59:47 AM EDT, Asokan Pichai wrote: > > From: Joel Montes de Oca > > To: Tutor Python > > Subject: [Tutor] Paper Rock Scissors game - User's choice not returned > properly > Message-ID: <4EAEC191.3060208 at gmail.com > > > Content-Type: text/plain; charset="iso-8859-1"; Format="flowed" > > Hello everyone, > > > The function: ( http://dpaste.com/644857/) > > def UserChoice (): # The function that returns the choice > from the user > print 'Please select (P) for paper, (R) for Rock, or (S) > for Scissors.' > choice = raw_input('What is your selection?:') > > if choice.lower() not in ('p', 'r','s'): # Converts > the user's choice to lowercase and confirms the choice is valid > print 'I am sorry, you entered\'' + > choice.upper() + '\' which is an invalid response. Please try > again.' > raw_input('Press Enter to try again.') > > UserChoice () # If the choice is not > valid, run the function over > > > You should use > return UserChoice() > > else: > return choice > > > Asokan Pichai > SVP - Learning and Development > > ?Faith consists in believing when it is beyond the power of reason to > believe. " > Voltaire > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I am not sure if I understand, why doesn't my way work and what do you mean I should return UserChoice()? -- -Joel M. From hugo.yoshi at gmail.com Mon Oct 31 17:14:40 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 31 Oct 2011 17:14:40 +0100 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: <4EAEC191.3060208@gmail.com> References: <4EAEC191.3060208@gmail.com> Message-ID: On Mon, Oct 31, 2011 at 4:41 PM, Joel Montes de Oca wrote: > Hello everyone, > > I am having a little trouble with a block of code that isn't behaving the > way I would expect. Maybe you can give me a hand and point where it is going > wrong. > > The function that is not working correctly belongs to a Paper Rock Scissor > game I am making. > > This particular function is responsible to: > ? a) Get the user's choice (Paper, Rock, or Scissors) > ? b) Return the user's choice within the variable choice to the function > that called it. > > The function works correctly as long as the user does not try to enter a > string other than 'P', 'R', or 'S'. > > Logic: > ??? Take the user's string and put it in the variable choice. > ??? If choice is not 'P', 'R', or 'S' then pass a message to the user and > call the function again. > ??? If the choice is 'P', 'R', or 'S' then return choice to where it was > called from. > > The problem is this. > > When the user enters a string other than the valid ones, the if statements > catches it and calls the same function again so the user can enter a valid > string. But the variable choice does not get assigned the new string entered > by the user, instead it is empty. > > I would expect if the function runs again, the variable choice would be > updated to the last value given by the user. > > The function: ( http://dpaste.com/644857/) > > def UserChoice (): # The function that returns the choice from the user > print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' > choice = raw_input('What is your selection?: ') > > if choice.lower() not in ('p', 'r','s'): # Converts the user's choice to > lowercase and confirms the choice is valid > print 'I am sorry, you entered \'' + choice.upper() + '\' which is an > invalid response. Please try again.' > raw_input('Press Enter to try again.') > UserChoice () # If the choice is not valid, run the function over > else: > return choice > Your problem is that you don't quite understand recursion. When a function calls itself, it's not actually any different from when a function A calls another function B. Once function B is done running and returns, control goes back to function A. It doesn't matter if function B is actually the same function as A. In fact, even if A and B are the same function, they don't "share" any variables and are totally separate as if they were two different functions that just happened to do the same thing. So, how does this apply to your function? Let's go through a run of it. We call UserChoice (this is function A) and we input a wrong letter. So, A calls UserChoice again (this is function B), and this time we input something valid. So, function B runs the line "return choice." Control now returns to function A, right at the point where we called function B. So what do we do here with the choice that was just returned from function B? Well, looking at the line where it's called, it's just "UserChoice()". So we do nothing. We just throw it away. Then, we continue on with function A, move out of the if statement, and "fall off the end" of the function. And when that happens, Python returns None from function A to show you that nothing was returned. If you understood all that, you should be able to fix your problem. Hugo From neubyr at gmail.com Mon Oct 31 17:27:19 2011 From: neubyr at gmail.com (neubyr) Date: Mon, 31 Oct 2011 11:27:19 -0500 Subject: [Tutor] importing modules and packages In-Reply-To: <4EAE6C7F.6090003@pearwood.info> References: <4EAE6C7F.6090003@pearwood.info> Message-ID: On Mon, Oct 31, 2011 at 4:38 AM, Steven D'Aprano wrote: > neubyr wrote: >> >> Is it possible to tell whether import statement is importing a module >> or package? ?I am going through some example code with some import >> statements - like 'import os, sys, time', 'import packed'. I know os, >> sys and time are (built-in) modules and 'packed' is a package here . >> But can I determine whether it's a package or module using any >> command/method or by following some naming convention? > > Consider: > >>>> import curses ?# A package. >>>> curses.__file__ > '/usr/lib/python2.5/curses/__init__.pyc' >>>> curses.__path__ > ['/usr/lib/python2.5/curses'] > > > Compare to: > >>>> import string ?# A plain module. >>>> string.__file__ > '/usr/lib/python2.5/string.pyc' >>>> string.__path__ > Traceback (most recent call last): > ?File "", line 1, in > AttributeError: 'module' object has no attribute '__path__' > > > > Does this help? > > That's helpful. Thanks a lot.. - neuby.r From joelmontes01 at gmail.com Mon Oct 31 18:09:16 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Mon, 31 Oct 2011 13:09:16 -0400 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: References: <4EAEC191.3060208@gmail.com> Message-ID: <4EAED63C.90603@gmail.com> On Mon 31 Oct 2011 12:14:40 PM EDT, Hugo Arts wrote: > > On Mon, Oct 31, 2011 at 4:41 PM, Joel Montes de Oca > wrote: >> >> Hello everyone, >> >> I am having a little trouble with a block of code that isn't behaving the >> way I would expect. Maybe you can give me a hand and point where it >> is going >> wrong. >> >> The function that is not working correctly belongs to a Paper Rock >> Scissor >> game I am making. >> >> This particular function is responsible to: >> a) Get the user's choice (Paper, Rock, or Scissors) >> b) Return the user's choice within the variable choice to the function >> that called it. >> >> The function works correctly as long as the user does not try to enter a >> string other than 'P', 'R', or 'S'. >> >> Logic: >> Take the user's string and put it in the variable choice. >> If choice is not 'P', 'R', or 'S' then pass a message to the user and >> call the function again. >> If the choice is 'P', 'R', or 'S' then return choice to where it was >> called from. >> >> The problem is this. >> >> When the user enters a string other than the valid ones, the if >> statements >> catches it and calls the same function again so the user can enter a >> valid >> string. But the variable choice does not get assigned the new string >> entered >> by the user, instead it is empty. >> >> I would expect if the function runs again, the variable choice would be >> updated to the last value given by the user. >> >> The function: ( http://dpaste.com/644857/) >> >> def UserChoice (): # The function that returns the choice from the user >> print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' >> choice = raw_input('What is your selection?: ') >> >> if choice.lower() not in ('p', 'r','s'): # Converts the user's choice to >> lowercase and confirms the choice is valid >> print 'I am sorry, you entered \'' + choice.upper() + '\' which is an >> invalid response. Please try again.' >> raw_input('Press Enter to try again.') >> UserChoice () # If the choice is not valid, run the function over >> else: >> return choice >> > > > Your problem is that you don't quite understand recursion. > > When a function calls itself, it's not actually any different from > when a function A calls another function B. Once function B is done > running and returns, control goes back to function A. It doesn't > matter if function B is actually the same function as A. In fact, even > if A and B are the same function, they don't "share" any variables and > are totally separate as if they were two different functions that just > happened to do the same thing. > > So, how does this apply to your function? Let's go through a run of > it. We call UserChoice (this is function A) and we input a wrong > letter. So, A calls UserChoice again (this is function B), and this > time we input something valid. So, function B runs the line "return > choice." > > Control now returns to function A, right at the point where we called > function B. So what do we do here with the choice that was just > returned from function B? Well, looking at the line where it's called, > it's just "UserChoice()". So we do nothing. We just throw it away. > Then, we continue on with function A, move out of the if statement, > and "fall off the end" of the function. And when that happens, Python > returns None from function A to show you that nothing was returned. > > If you understood all that, you should be able to fix your problem. > > Hugo Hey Hugo, I think I understand your explanation. Let me see if I get it. The code: def UserChoice (): *# I WILL CALL THIS FUNCTION A* print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' choice = raw_input('What is your selection?:') if choice.lower() not in ('p', 'r','s'): print 'I am sorry, you entered\'' + choice.upper() + '\' which is an invalid response. Please try again.' raw_input('Press Enter to try again.') UserChoice () *# I WILL CALL THIS FUNCTION B* else: return choice*# I WILL CALL THE ORIGINAL CALLING FUNCTION, FUNCTION MAIN* OK so when the user uses a valid letter, the variable choice gets returned to FUNCTION MAIN. Everything works fine. When the user enters an invalid letter, FUNCTION B calls FUNCTION A. FUNCTION A returns choice to FUNCTION B. FUNCTION B does nothing with the return, FUNCTION MAIN gets nothing to returned to it, thus choice is NONE. FUN MAIN | | |__ FUN A | | |_ FUN B This is how I understand it. So if I want this to work, I need FUN B to give something back to FUN A so that FUN A will have something to give back to FUN MAIN but that doesn't feel right. Is there a way to say GO TO FUN A instead of calling the function? I also found this Youtube video on the topic of recursion in python. http://www.youtube.com/watch?v=72hal4Cp_2I -- -Joel M. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Mon Oct 31 18:26:21 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Mon, 31 Oct 2011 22:56:21 +0530 Subject: [Tutor] Tutor Digest, Vol 92, Issue 128 In-Reply-To: References: Message-ID: Hugo's explanation is nice and clear. You may also want to look at this way Consider the most simplified form of the issue def alpha(): if X: beta() else: return q Here in the* if branch* nothing is returned while in the *else branch *something is being returned. That is whenever X is True nothing is returned from alpha(). Even if beta() returns something that is not being used. But when X is False something (q in this simplistic example) is being returned So this is a bug. HTH Asokan Pichai SVP - Learning and Development ?Faith consists in believing when it is beyond the power of reason to believe. " Voltaire -------------- next part -------------- An HTML attachment was scrubbed... URL: From joelmontes01 at gmail.com Mon Oct 31 18:40:44 2011 From: joelmontes01 at gmail.com (Joel M.) Date: Mon, 31 Oct 2011 13:40:44 -0400 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: <4EAED63C.90603@gmail.com> References: <4EAEC191.3060208@gmail.com> <4EAED63C.90603@gmail.com> Message-ID: On Mon, Oct 31, 2011 at 1:09 PM, Joel Montes de Oca wrote: > On Mon 31 Oct 2011 12:14:40 PM EDT, Hugo Arts wrote: > > > On Mon, Oct 31, 2011 at 4:41 PM, Joel Montes de Oca > wrote: > > > Hello everyone, > > I am having a little trouble with a block of code that isn't behaving the > way I would expect. Maybe you can give me a hand and point where it is > going > wrong. > > The function that is not working correctly belongs to a Paper Rock Scissor > game I am making. > > This particular function is responsible to: > a) Get the user's choice (Paper, Rock, or Scissors) > b) Return the user's choice within the variable choice to the function > that called it. > > The function works correctly as long as the user does not try to enter a > string other than 'P', 'R', or 'S'. > > Logic: > Take the user's string and put it in the variable choice. > If choice is not 'P', 'R', or 'S' then pass a message to the user and > call the function again. > If the choice is 'P', 'R', or 'S' then return choice to where it was > called from. > > The problem is this. > > When the user enters a string other than the valid ones, the if statements > catches it and calls the same function again so the user can enter a valid > string. But the variable choice does not get assigned the new string > entered > by the user, instead it is empty. > > I would expect if the function runs again, the variable choice would be > updated to the last value given by the user. > > The function: ( http://dpaste.com/644857/) > > def UserChoice (): # The function that returns the choice from the user > print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' > choice = raw_input('What is your selection?: ') > > if choice.lower() not in ('p', 'r','s'): # Converts the user's choice to > lowercase and confirms the choice is valid > print 'I am sorry, you entered \'' + choice.upper() + '\' which is an > invalid response. Please try again.' > raw_input('Press Enter to try again.') > UserChoice () # If the choice is not valid, run the function over > else: > return choice > > > > Your problem is that you don't quite understand recursion. > > When a function calls itself, it's not actually any different from > when a function A calls another function B. Once function B is done > running and returns, control goes back to function A. It doesn't > matter if function B is actually the same function as A. In fact, even > if A and B are the same function, they don't "share" any variables and > are totally separate as if they were two different functions that just > happened to do the same thing. > > So, how does this apply to your function? Let's go through a run of > it. We call UserChoice (this is function A) and we input a wrong > letter. So, A calls UserChoice again (this is function B), and this > time we input something valid. So, function B runs the line "return > choice." > > Control now returns to function A, right at the point where we called > function B. So what do we do here with the choice that was just > returned from function B? Well, looking at the line where it's called, > it's just "UserChoice()". So we do nothing. We just throw it away. > Then, we continue on with function A, move out of the if statement, > and "fall off the end" of the function. And when that happens, Python > returns None from function A to show you that nothing was returned. > > If you understood all that, you should be able to fix your problem. > > Hugo > > > Hey Hugo, > > I think I understand your explanation. Let me see if I get it. > > The code: > > def UserChoice (): *# I WILL CALL THIS FUNCTION A* > > > print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' > choice = raw_input('What is your selection?: ') > > if choice.lower() not in ('p', 'r','s'): > > print 'I am sorry, you entered \'' + choice.upper() + '\' which is an invalid response. Please try again.' > raw_input('Press Enter to try again.') > > UserChoice () *# I WILL CALL THIS FUNCTION B* > else: > return choice *# I WILL CALL THE ORIGINAL CALLING FUNCTION, FUNCTION MAIN* > > > OK so when the user uses a valid letter, the variable choice gets > returned to FUNCTION MAIN. Everything works fine. > > When the user enters an invalid letter, FUNCTION B calls FUNCTION A. > FUNCTION A returns choice to FUNCTION B. FUNCTION B does nothing with the > return, FUNCTION MAIN gets nothing to returned to it, thus choice is NONE. > > FUN MAIN > | > | > |__ FUN A > | > | > |_ FUN B > > This is how I understand it. So if I want this to work, I need FUN B to > give something back to FUN A so that FUN A will have something to give back > to FUN MAIN but that doesn't feel right. > > Is there a way to say GO TO FUN A instead of calling the function? > > > > I also found this Youtube video on the topic of recursion in python. > http://www.youtube.com/watch?v=72hal4Cp_2I > > -- > -Joel M. > > After a little digging around, I found that there's no goto or label functions. http://entrian.com/goto/ had me excited for a few minutes until I read the top red text where it reads that the goto module was an April Fools joke. haha -------------- next part -------------- An HTML attachment was scrubbed... URL: From joelmontes01 at gmail.com Mon Oct 31 18:57:24 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Mon, 31 Oct 2011 13:57:24 -0400 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: <4EAEC191.3060208@gmail.com> References: <4EAEC191.3060208@gmail.com> Message-ID: <4EAEE184.4040604@gmail.com> On 10/31/2011 11:41 AM, Joel Montes de Oca wrote: > Hello everyone, > > I am having a little trouble with a block of code that isn't behaving > the way I would expect. Maybe you can give me a hand and point where > it is going wrong. > > The function that is not working correctly belongs to a Paper Rock > Scissor game I am making. > > This particular function is responsible to: > a) Get the user's choice (Paper, Rock, or Scissors) > b) Return the user's choice within the variable choice to the > function that called it. > > The function works correctly as long as the user _does not try to > enter a string other than_ 'P', 'R', or 'S'. > > Logic: > Take the user's string and put it in the variable choice. > If choice is not 'P', 'R', or 'S'then pass a message to the user > and call the function again. > If the choice is 'P', 'R', or 'S'then return choice to where it > was called from. > > The problem is this. > > When the user enters a string other than the valid ones, the if > statements catches it and calls the same function again so the user > can enter a valid string. But the variable choice does not get > assigned the new string entered by the user, instead it is empty. > > I would expect if the function runs again, the variable choice would > be updated to the last value given by the user. > > The function: ( http://dpaste.com/644857/) > > def UserChoice (): # The function that returns the choice from the user > print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' > choice = raw_input('What is your selection?:') > > if choice.lower() not in ('p', 'r','s'): # Converts the user's choice to lowercase and confirms the choice is valid > print 'I am sorry, you entered\'' + choice.upper() + '\' which is an invalid response. Please try again.' > raw_input('Press Enter to try again.') > UserChoice () # If the choice is not valid, run the function over > else: > return choice > > > Output with no problems: ( http://dpaste.com/644866/) > > Welcome to the PRS game. > > Please select (P) for paper, (R) for Rock, or (S) for Scissors. > What is your selection?: s > > You threw down Scissors while the computer threw down Rock > > LOOSE > Output with problems: ( http://dpaste.com/644868/) > > Welcome to the PRS game. > > Please select (P) for paper, (R) for Rock, or (S) for Scissors. > What is your selection?: L > I am sorry, you entered 'L' which is an invalid response. Please try again. > Press Enter to try again. > Please select (P) for paper, (R) for Rock, or (S) for Scissors. > What is your selection?: s > > You threw down None while the computer threw down Paper > > LOOSE > Here's the full source code in case the problem is outside of the > function: ( http://dpaste.com/644873/) > > import random # Import the random library > > def main (): # The main function that gets called from main() > print '\nWelcome to the PRS game.\n' > > choice = UserChoice () # Gets the choice from the user > cchoice = ComputerChoice () # Gets the choice from the computer > > PrintOutcome (choice, cchoice) # Passes both choices to the PrintChoice function for display > > > return 0 > > def UserChoice (): # The function that returns the choice from the user > print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' > choice = raw_input('What is your selection?:') > > if choice.lower() not in ('p', 'r','s'): # Converts the user's choice to lowercase and confirms the choice is valid > print 'I am sorry, you entered\'' + choice.upper() + '\' which is an invalid response. Please try again.' > raw_input('Press Enter to try again.') > UserChoice () # If the choice is not valid, run the function over > else: > return choice > > def ComputerChoice (): # The function that returns the choice from the computer > PRS = ['Rock', 'Paper', 'Scissors'] # A list of choices > > cchoice = random.choice(PRS) # Choose a random item from the list > > return cchoice # Return the function > > def PrintOutcome (UC, CC): # Function responsable to display the choices and results > PRS = ['Rock', 'Paper', 'Scissors'] > > # Convert the letters to words > if UC == 'r': > UC = PRS[0] > elif UC == 'p': > UC = PRS[1] > elif UC == 's': > UC = PRS[2] > > print '\n\tYou threw down', UC, 'while the computer threw down', CC +'\n' > > # find the outcome of the game > if UC == CC: > print 'We have a tie, both players gain a point!' > elif UC == 'Rock' and CC == 'Scissors': > print 'WIN' > elif UC == 'Paper' and CC == 'Rock': > print 'WIN' > elif UC == 'Scissors' and CC == 'Paper': > print 'WIN' > else: > print 'LOOSE' > > return 0 > > main() > I am using Python 2.7 > I am running on Ubuntu 11.10 > > Thanks for any help > -- > -Joel M. OK everyone, After burning my little noob brain cells a bit, I came up with this to solve the problem. def UserChoice (): # The function that returns the choice from the user while 1: print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' choice = raw_input('What is your selection?:') if choice.lower() in ('p', 'r','s'): # Converts the user's choice to lowercase and confirms the choice is valid return choice break else: print 'Try again.' It puts the choice into a loop and only exits when the user enters a valid value. It works and it's so much easier to read too! Thanks for all the help! :) -- -Joel M. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Oct 31 19:14:21 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 31 Oct 2011 11:14:21 -0700 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: <4EAEE184.4040604@gmail.com> References: <4EAEC191.3060208@gmail.com> <4EAEE184.4040604@gmail.com> Message-ID: On Mon, Oct 31, 2011 at 10:57 AM, Joel Montes de Oca wrote: > > ?I came up with this to solve the problem. > > def UserChoice (): ? ?# The function that returns the choice from the user > ? ? while 1: > > ? ? ? ? print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' > ? ? ? ? choice = raw_input('What is your selection?: ') > ? ? ? ? if choice.lower() in ('p', 'r','s'): ? ?# Converts the user's choice to lowercase and confirms the choice is valid > ? ? ? ? ? ? return choice > ? ? ? ? ? ? break > ? ? ? ? else: > ? ? ? ? ? ? print 'Try again.' > > It puts the choice into a loop and only exits when the user enters a valid value. It works and it's so much easier to read too! > You could simplify it even further by actually using the "while": > def UserChoice (): ? ?# The function that returns the choice from the user > ? ?choice = '' > ? ?attempt = 0 > ? ?while choice.lower() not in ('p', 'r','s'): > ? ? ? ?if attempt > 0: print 'Please try again.' > ? ? ? ?print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' > ? ? ? ?choice = raw_input('What is your selection?: ') > ? ? ? ?attempt +=1 > ? ?return choice.lower() It's a matter of personal preference, but I try to avoid "while 1" or "while True" loops if at all possible. For one thing, it seems counter-productive to set up a loop that doesn't exit, and then to have to use 'break' to get out of it! One last thing: HTML formatting is pretty, but it tends to screw things up. Someone else is bound to say it if I don't, so: please use plain text only when submitting code to the list. Thanks! From ramit.prasad at jpmorgan.com Mon Oct 31 19:13:53 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 31 Oct 2011 14:13:53 -0400 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: <4EAEE184.4040604@gmail.com> References: <4EAEC191.3060208@gmail.com> <4EAEE184.4040604@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF2C22A2@EMARC112VS01.exchad.jpmchase.net> Just a minor note, this break is redundant. Breaks are used to exit (for/while) loops but keep control in the function. A return exits the function immediately. if choice.lower() in ('p', 'r','s'): # Converts the user's choice to lowercase and confirms the choice is valid return choice break There is also a "continue" which is similar to a break, but instead of exiting the loop, it will start the loop code over for the next value (thus "continuing" the loop). >>> t = [ 'not this', 'do this', 'not this either', 'most definitely do this' ] >>> for string in t: ... if string.startswith( 'not' ): ... continue # I want to keep working with the other elements in the list ... print string ... do this most definitely do this >>> for string in t: ... if string.startswith( 'not' ): ... break # I want to abort the entire loop now ... print string ... >>> Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Mon Oct 31 19:37:38 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 31 Oct 2011 18:37:38 +0000 Subject: [Tutor] Tutor Digest, Vol 92, Issue 123 In-Reply-To: References: Message-ID: On 31/10/11 12:56, Rinu Boney wrote: > I Use Windows.I Already Know C/C++ which makes python syntax seem very easy. > Maybe Setting Up Emacs With Python Will Make Me Productive. If you learn emacs then it will. But learning emacs is almost as big a task as learning Python, it is a complete user environment not just a text editor. > I Have Eclipse With PyDev. Then you will have most of the features you would get from emacs just in a more Windows-like style. > Why Is There Not A Pythonic Emacs? There is, in that there is a python mode plug-in that provides an interactive prompt, syntax highlighting, auto-completion, debugging support etc. but it's all integrated with the standard emacs way of working because thats what emacs users expect. Python works just like perl, C++, Lisp, Smalltalk and all the other languages that are supported on emacs. But that is the point, emacs makes everything look like emacs. emacs does not try to look like every other Windows IDE. And emacs looks a lot more like Unix than it does like Windows... And there is no python macro language for emacs because emacs is a macro language. The original emacs was just a set of macros for the Teco editor. That got rewritten in lisp to become emacs as we know it but 99% of what you see in emacs is implemented in lisp macros over a very small core of C code. That's what gives it its power and its complexity because users have written macros to read mail, usenet, browse the web, do ftp transfers etc etc... And writing Python programs is just one more set of macros. > On Mon, Oct 31, 2011 at 8:23 AM, > wrote: > > Send Tutor mailing list submissions to > tutor at python.org > BTW please do not send the entire contents of the digest with your mails. Its not good for those who pay by the byte... or have small memory devices(like smart phones). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From joelmontes01 at gmail.com Mon Oct 31 19:45:25 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Mon, 31 Oct 2011 14:45:25 -0400 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF2C22A2@EMARC112VS01.exchad.jpmchase.net> References: <4EAEC191.3060208@gmail.com> <4EAEE184.4040604@gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF2C22A2@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4EAEECC5.6080603@gmail.com> On 10/31/2011 02:13 PM, Prasad, Ramit wrote: > Just a minor note, this break is redundant. Breaks are used to exit (for/while) loops but keep control in the function. A return exits the function immediately. > > if choice.lower() in ('p', 'r','s'): # Converts the user's choice to lowercase and confirms the choice is valid > return choice > break > > > There is also a "continue" which is similar to a break, but instead of exiting the loop, it will start the loop code over for the next value (thus "continuing" the loop). > >>>> t = [ 'not this', 'do this', 'not this either', 'most definitely do this' ] >>>> for string in t: > ... if string.startswith( 'not' ): > ... continue # I want to keep working with the other elements in the list > ... print string > ... > do this > most definitely do this >>>> for string in t: > ... if string.startswith( 'not' ): > ... break # I want to abort the entire loop now > ... print string > ... > > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > -- > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Awesome, thanks for the tip. I removed the break from the code. Thanks again. -- -Joel M. From alan.gauld at btinternet.com Mon Oct 31 19:46:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 31 Oct 2011 18:46:57 +0000 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: <4EAED63C.90603@gmail.com> References: <4EAEC191.3060208@gmail.com> <4EAED63C.90603@gmail.com> Message-ID: On 31/10/11 17:09, Joel Montes de Oca wrote: > FUN MAIN > | > | > |__ FUN A > | > | > |_ FUN B > > This is how I understand it. So if I want this to work, I need FUN B to > give something back to FUN A so that FUN A will have something to give > back to FUN MAIN but that doesn't feel right. It is right. You need to add a return statement to your code like so: def UserChoice (): .... if choice.lower() not in ('prs'): # NB use a single string ... raw_input('Press Enter to try again.') return UserChoice () # must return the value to caller else: return choice # just as you do here But this is not the best way to use recursion... > Is there a way to say GO TO FUN A instead of calling the function? Yes, in a while loop. As a later post shows you figured out! That's a much better solution. But this shows that you could have used recursion if you really wanted to. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From joelmontes01 at gmail.com Mon Oct 31 19:47:56 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Mon, 31 Oct 2011 14:47:56 -0400 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: References: <4EAEC191.3060208@gmail.com> <4EAEE184.4040604@gmail.com> Message-ID: <4EAEED5C.1050400@gmail.com> On 10/31/2011 02:14 PM, Marc Tompkins wrote: > On Mon, Oct 31, 2011 at 10:57 AM, Joel Montes de Oca > wrote: >> I came up with this to solve the problem. >> >> def UserChoice (): # The function that returns the choice from the user >> while 1: >> >> print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' >> choice = raw_input('What is your selection?: ') >> if choice.lower() in ('p', 'r','s'): # Converts the user's choice to lowercase and confirms the choice is valid >> return choice >> break >> else: >> print 'Try again.' >> >> It puts the choice into a loop and only exits when the user enters a valid value. It works and it's so much easier to read too! >> > You could simplify it even further by actually using the "while": > >> def UserChoice (): # The function that returns the choice from the user >> choice = '' >> attempt = 0 >> while choice.lower() not in ('p', 'r','s'): >> if attempt> 0: print 'Please try again.' >> print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' >> choice = raw_input('What is your selection?: ') >> attempt +=1 >> return choice.lower() > It's a matter of personal preference, but I try to avoid "while 1" or > "while True" loops if at all possible. For one thing, it seems > counter-productive to set up a loop that doesn't exit, and then to > have to use 'break' to get out of it! > > One last thing: HTML formatting is pretty, but it tends to screw > things up. Someone else is bound to say it if I don't, so: please > use plain text only when submitting code to the list. Thanks! Things for the tip Mark, I have set up Thunderbird to send text only when emailing the python.org domain. -- -Joel M. From alan.gauld at btinternet.com Mon Oct 31 19:50:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 31 Oct 2011 18:50:56 +0000 Subject: [Tutor] Use of subject line [Was: Re: Tutor Digest, Vol 92, Issue 127] In-Reply-To: References: Message-ID: On 31/10/11 15:59, Asokan Pichai wrote: > > From: Joel Montes de Oca > > To: Tutor Python > > Subject: [Tutor] Paper Rock Scissors game - User's choice not returned > properly If replying via the digest please change the subject line to something meaningful - preferably the same as the original! Alan G. List moderator From waynejwerner at gmail.com Mon Oct 31 20:07:22 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 31 Oct 2011 14:07:22 -0500 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: References: <4EAEC191.3060208@gmail.com> <4EAEE184.4040604@gmail.com> Message-ID: On Mon, Oct 31, 2011 at 1:14 PM, Marc Tompkins wrote: > > You could simplify it even further by actually using the "while": > > > def UserChoice (): # The function that returns the choice from the > user > > choice = '' > > attempt = 0 > > while choice.lower() not in ('p', 'r','s'): > > if attempt > 0: print 'Please try again.' > > print 'Please select (P) for paper, (R) for Rock, or (S) for > Scissors.' > > choice = raw_input('What is your selection?: ') > > attempt +=1 > > return choice.lower() > > It's a matter of personal preference, but I try to avoid "while 1" or > "while True" loops if at all possible. For one thing, it seems > counter-productive to set up a loop that doesn't exit, and then to > have to use 'break' to get out of it! > As a slight aside, I came up with a (fairly) simple recipe for this sort of occasion: def prompt(choices): try: for choice, desc in choices: print("%2s. %s" % (choice, desc)) prompt.choice = input("Choice: ") #use raw_input in Python 2.x print() return prompt.choice except TypeError: raise ValueError("prompt expects collection of pairs") Then you can do something like this: while prompt([("P", "Paper"), ("R", "Rock"), ("S", "Scissors)]).lower() not in ('p', 'r', 's'): print("Error: ", prompt.choice, " is not a valid choice!") #do something with prompt.choice here It handles keeping track of whatever the last choice was for you, and all you have to do is pass it a collection of pairs. If you wanted to make it specifically for your application, you could just change it to this: def prompt(): print("(P)aper") print("(R)ock") print("or (S)cissors?") prompt.choice = raw_input("Choice: ") return prompt.choice while prompt().lower() not in ('p', 'r', 's'): #print error message HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at akwebsoft.com Mon Oct 31 20:31:42 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Mon, 31 Oct 2011 11:31:42 -0800 Subject: [Tutor] Tutor Digest, Vol 92, Issue 123 In-Reply-To: References: Message-ID: <20111031193142.GF9335@akwebsoft.com> * Rinu Boney [111031 07:03]: > I Use Windows.I Already Know C/C++ which makes python syntax seem very easy. > Maybe Setting Up Emacs With Python Will Make Me Productive. > I Have Eclipse With PyDev. > Why Is There Not A Pythonic Emacs? Rinu, by this time I believe that Alan has addressed your question above. He has also (wisely) provided caveats regarding the difficulty of learning emacs itself. I'll take a reverse of Alan's comments, not to contradict him, but to give a possible different perspective: If you learn to use emacs with python, you will essentially be learning *two* programming languages: Python _and_ elisp, which is the internal programming language of emacs. Emacs is essentially an elisp interpreter. There may be advantages to learning two languages simultaneously. This will take time. A lot of time. Do you have the time? Will you be compensated for the time? :) having two additional programming languages "under your belt" may be considered compensation. In case you do not know this: Emacs has the ability to run the python or language-your-choice interpreter asynchronous within the editor, in it's own window. There could be great advantages to this. I have in the past, written elisp code that allows me two write code in one window and have it evaluated in the 'python window' or 'language-of-your-choice window'. I'll reiterate what I said earlier, I no longer use emacs, but have great respect for it. I use vim linked against the python binary so that I can use python code to enhance my (hand-rolled) "IDE". I much prefer python code to elisp code. I hope my comments are of some help. I'm sure that you have been well informed as to what you would be getting youself into. :) regards -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From __peter__ at web.de Mon Oct 31 21:22:21 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 31 Oct 2011 21:22:21 +0100 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly References: <4EAEC191.3060208@gmail.com> <4EAED63C.90603@gmail.com> Message-ID: Alan Gauld wrote: > if choice.lower() not in ('prs'): # NB use a single string That's not a good idea. If a user accidentally enters PR (for example) your version will mistake that for a valid choice. From __peter__ at web.de Mon Oct 31 21:40:30 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 31 Oct 2011 21:40:30 +0100 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly References: <4EAEC191.3060208@gmail.com> <4EAEE184.4040604@gmail.com> Message-ID: Joel Montes de Oca wrote: > def UserChoice (): # The function that returns the choice from the > user > while 1: > > print 'Please select (P) for paper, (R) for Rock, or (S) for > Scissors.' > choice = raw_input('What is your selection?:') > if choice.lower() in ('p', 'r','s'): # Converts the > user's choice to lowercase and confirms the choice is valid > return choice > break > else: > print 'Try again.' There's a problem with this code that I think nobody has addressed yet: if you enter a lowercase letter, say "p", your function returns "p", if you enter an uppercase "P" it returns "P". The calling code in http://dpaste.com/644873/copy/ # Convert the letters to words if UC == 'r': UC = PRS[0] elif UC == 'p': UC = PRS[1] elif UC == 's': UC = PRS[2] doesn't handle this case correctly. The best way is of course to normalize the code returned by the UserChoice() function ... choice = raw_input('What is your selection?:').lower() if choice in ('p', 'r', 's'): return choice ... From steve at pearwood.info Mon Oct 31 21:55:54 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Nov 2011 07:55:54 +1100 Subject: [Tutor] Tutor Digest, Vol 92, Issue 128 In-Reply-To: References: Message-ID: <4EAF0B5A.7070001@pearwood.info> Asokan Pichai wrote: > Hugo's explanation is nice and clear. [...] Who are you replying to, and what was the question? Thank you for NOT quoting the entire digest, hundreds and hundreds of lines! You would be amazed at how many people do that. But in future, could you please quote *just enough* so that we can see who you are replying to, and what the context of your comments are? Because I have no idea what you are talking about in your email. And finally, please change the subject line to something meaningful, not "Re Tutor Digest". This is especially important because replying to a digest breaks email threading. You may prefer to change to individual emails instead of digest mode. In my opinion, digest mode is only useful when you want to read other people's comments without commenting yourself. -- Steven From alan.gauld at btinternet.com Mon Oct 31 23:04:25 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 31 Oct 2011 22:04:25 +0000 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: References: <4EAEC191.3060208@gmail.com> <4EAED63C.90603@gmail.com> Message-ID: On 31/10/11 20:22, Peter Otten wrote: > Alan Gauld wrote: > >> if choice.lower() not in ('prs'): # NB use a single string > > That's not a good idea. If a user accidentally enters PR (for example) your > version will mistake that for a valid choice. Good point, although you could test the first character only... if choice[0].lower() not in ('prs'): # NB use a single string -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Oct 31 23:09:52 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 31 Oct 2011 22:09:52 +0000 Subject: [Tutor] Tutor Digest, Vol 92, Issue 128 In-Reply-To: <4EAF0B5A.7070001@pearwood.info> References: <4EAF0B5A.7070001@pearwood.info> Message-ID: On 31/10/11 20:55, Steven D'Aprano wrote: > You may prefer to change to individual emails instead of digest mode. In > my opinion, digest mode is only useful when you want to read other > people's comments without commenting yourself. It depends, I've used digests from other lists that delivered the mails as embedded messages that you could open individually and replies then followed the original. I think that requires MIME encoding in the digest. But I've never tried it on the tutor list so I don't know if it works here. And digests are useful if you are on a tariff that limits the number of messages received because they see the digest as one message. But OTOH I haven't seen anyone offering message based access for a quite a few years now. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Mon Oct 31 23:20:38 2011 From: d at davea.name (Dave Angel) Date: Mon, 31 Oct 2011 18:20:38 -0400 Subject: [Tutor] Tutor Digest, Vol 92, Issue 128 In-Reply-To: References: <4EAF0B5A.7070001@pearwood.info> Message-ID: <4EAF1F36.3070305@davea.name> On 10/31/2011 06:09 PM, Alan Gauld wrote: > On 31/10/11 20:55, Steven D'Aprano wrote: > >> You may prefer to change to individual emails instead of digest mode. In >> my opinion, digest mode is only useful when you want to read other >> people's comments without commenting yourself. > > It depends, I've used digests from other lists that delivered > the mails as embedded messages that you could open individually > and replies then followed the original. I think that requires > MIME encoding in the digest. But I've never tried it on the > tutor list so I don't know if it works here. > > And digests are useful if you are on a tariff that limits the > number of messages received because they see the digest as > one message. But OTOH I haven't seen anyone offering message > based access for a quite a few years now. > I used digest mode (here and in python-list) up until a few weeks ago. It worked fine (in Thunderbird) replying to one of the embedded messages. I don't remember just what digest mode I had picked, but not all choices worked this way. Anyway, when I got a new email address, I also switched to individual emails. -- DaveA From bgailer at gmail.com Mon Oct 31 23:48:55 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 31 Oct 2011 18:48:55 -0400 Subject: [Tutor] Tutor Digest, Vol 92, Issue 128 In-Reply-To: References: Message-ID: <4EAF25D7.5010709@gmail.com> On 10/31/2011 1:26 PM, Asokan Pichai wrote: > Hugo's explanation is nice and clear. > > You may also want to look at this way > Consider the most simplified form of the issue > > def alpha(): > if X: > beta() > else: > return q > > Here in the*if branch* nothing is returned None is returned, not nothing. > while in the *else branch *something is being returned. > > That is whenever X is True nothing is returned from alpha(). > Even if beta() returns something that is not being used. > > But when X is False something (q in this simplistic example) > is being returned > > So this is a bug. > > HTH > > Asokan Pichai > SVP - Learning and Development > > "Faith consists in believing when it is beyond the power of reason to > believe. " > Voltaire > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: