[Tutor] Extending a list within a list comprehension
Hi all, I have solved my problem, but would like to know if what I accomplished can be done with different data using list comprehensions. the list I want to sort has the following format: elements = [ (codigo, [ cant, importe, porc]), (codigo, [ cant, importe, porc]), ... ] Actual data is: In [129]: elements[0:5] Out[129]: [('2712', [22.0, 3618.80999, 0.0032389476163069883]), ('2713', [19.0, 6551.81004, 0.0058640739309320719]), ('2710', [21.0, 2553.57999, 0.0022855336019435113]), ('2716', [19.0, 8215.27004, 0.0073529224203034461]), ('4305', [4.0, 348.37, 0.00031180199598565978])] And I want to sort descending on 'importe', which is x[1][1] for x in elements. What I did was the following, following the Schwarzian Transform: temporal = [] temporal = [ [x[1][1], (x[0], description[x[0]], x[1][0], x[1][1], x[1][2] ) ] for x in elements ] temporal.sort() temporal.reverse() # sort descending elements = [ x[1] for x in temporal ] If the second element in each array passed as x is of variable length (that is, it has a different element count than three, in this case), the program needs to extend the list instead. Without list comprehensions, and the added capability to utilize and sized list as a second element, my code ended up looking like the following: temporal = [] for x in elements: lst = [x[0], description[x[0]]] lst.extend(x[1]) temporal.append([x[1][1], lst]) temporal.sort() temporal.reverse() # sort descending elements = [ x[1] for x in temporal ] Is there a way to use list comprehensions to append or extend the array as needed by the second code listing? Thanks. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] [Fwd: Re: Extending a list within a list comprehension]
I sent this to John directly. Posting to the list. Forwarded Message From: Victor Bouffier [EMAIL PROTECTED] To: John Fouhy [EMAIL PROTECTED] Subject: Re: [Tutor] Extending a list within a list comprehension Date: Tue, 11 Apr 2006 18:03:41 -0500 On Wed, 2006-04-12 at 10:29 +1200, John Fouhy wrote: On 12/04/06, Victor Bouffier [EMAIL PROTECTED] wrote: elements = [ (codigo, [ cant, importe, porc]), (codigo, [ cant, importe, porc]), ... ] And I want to sort descending on 'importe', which is x[1][1] for x in elements. In python 2.4, you could achieve this by saying: elements.sort(key=lambda x: x[1][1]) In earlier versions of python, you can do: elements.sort(lambda x, y: cmp(x[1][1], y[1][1])) (but this is less efficient than key= in 2.4) There's also the decorate-sort-undecorate idiom: dec = [(x[1][1], x) for x in elements] dec.sort() elements = [x[1] for x in dec] Hi John, Thanks for your help. This is very nice and I will definitely use it when sorting a fixed list. However, I forgot to point out I am including an extra element: item description from a dict, where its key=codigo (x[0]). This is why I write the whole list as a single element. Still I could follow your suggestion and do: dec = [(x[1][1], x, description[x[0]]) for x in elements] dec.sort() elements = [x[1], x[2] for x in dec] It is still better, but not quite there. Any feedback will be gladly taken. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extending a list within a list comprehension
On Tue, 2006-04-11 at 23:42 +0100, Alan Gauld wrote: Hi Victor, I've gotta say that I much prefer the second version here. temporal = [] temporal = [ [x[1][1], (x[0], description[x[0]], x[1][0], x[1][1], x[1][2] ) ] for x in elements ] temporal.sort() temporal.reverse() # sort descending elements = [ x[1] for x in temporal ] temporal = [] for x in elements: lst = [x[0], description[x[0]]] lst.extend(x[1]) temporal.append([x[1][1], lst]) temporal.sort() temporal.reverse() # sort descending elements = [ x[1] for x in temporal ] That looks a lot easier to rtead (and debug) and will I suspect be easier to maintain. Copmprehensions are great but unfortunately can rapidly become incomprehensible! Is there a way to use list comprehensions to append or extend the array as needed by the second code listing? There may be but I wouldn't try. I might however look at using a simple list or dictionary of objects based on a class... It might be easier. Alan G Hi Alan, I believe you are right. The most pythonic way is not always the most perlish way ;-) (no offense intended to Perl-comers, but Perl does tend to promote nesting of expressions). It is much easier to read and maintain, which is what I will need to do eventually. Thanks for the feedback. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extending a list within a list comprehension
On Tue, 2006-04-11 at 22:17 -0400, Kent Johnson wrote: Victor Bouffier wrote: If the second element in each array passed as x is of variable length (that is, it has a different element count than three, in this case), the program needs to extend the list instead. Without list comprehensions, and the added capability to utilize and sized list as a second element, my code ended up looking like the following: temporal = [] for x in elements: lst = [x[0], description[x[0]]] lst.extend(x[1]) temporal.append([x[1][1], lst]) temporal.sort() temporal.reverse() # sort descending elements = [ x[1] for x in temporal ] Is there a way to use list comprehensions to append or extend the array as needed by the second code listing? I think you are looking for temporal = [ [x[0], description[x[0]]] + x[1] for x in elements ] Hi Kent, I try this one and get the following error: TypeError: list objects are unhashable I figured it is because of the x[0] element being used as a dict key. Can you explain further where this error comes from? Are you getting it too? but I would make two steps, one for the sort using just [ (x[0], x) for x in elements ] You are right. This is cleaner and not a big deal to do in two steps. However for the issue at hand, it still keeps x as a two element list: [codigo, [ cant, importe, porc]], which I would like to have extended: [codigo, cant, importe, porc] It is not a big deal. That is why I finally went with the longer version Alan suggested. Before the sort I get a two element list, the second element being the list I finally want as output. then when you pick the data back out you can format it how you like. Right. After the sort I just get that second element in another list comprehension lines = [ x[1] for x in temp ] Thanks for your help. Victor Kent PS to John: the original solution is using DSU, aka Schwarzian Transform ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bigrams and nested dictionaries
On Wed, 2006-03-29 at 00:15 -0500, Michael Broe wrote: Aha! John wrote: Are you sure you haven't mistakenly assigned something other than a dict to D or D['d'] ? Thanks for the tip! Yup that was it (and apologies for not reporting the problem more precisely). I hadn't initialized the nested dictionary before trying to assign to it. (I think Perl doesn't require initialization of dictionaries prior to assignment, which in this case, would be a nice thing...) D['c']['a'] = 1 #ooops Traceback (most recent call last): File stdin, line 1, in ? KeyError: 'c' D['c'] = {} D['c']['a'] = 1 D {'a': {'a': 1, 'b': 2}, 'c': {'a': 1}} You can check if the dictionary key exists prior to assigning to it: if not D.has_key('c'): ...D['c'] = {} D['c']['a'] = 1 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bigrams and nested dictionaries
On Mon, 2006-04-03 at 11:39 -0700, Danny Yoo wrote: You can check if the dictionary key exists prior to assigning to it: if not D.has_key('c'): ...D['c'] = {} D['c']['a'] = 1 Hi Victor, Another approach is to use the badly-named setdefault() method which is a close analogue to Perl's autovivification feature: ## D = {} D.setdefault('c', {})['a'] = 1 D {'c': {'a': 1}} ## Good luck! Thanks to both Danny and Alan. Great tips. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Guessing a number with limited no. of tries game gone wrong.
Hi Ros, Look what happens when the user tried for more than 5 times: if tries 5: break This just takes you out of the loop, but it does not handle the issue that the user did not guess correctly. The next statement will be to print the congratulations message. You should instead tell the user they did not make it and exit the program altogether, probably letting them know what the actual number was. Something like: if tries 5: print Too bad. You tried one too many times. print The number was, the_number sys.exit() You have to 'import sys' first though. Try it out and analyze the flow of the program. Use the debugger to try your code one step at a time to see what is going wrong. I would also change the initial guess to specify the range, like: guess = int(raw_input(Take a guess between 1 and 100: )) Best of luck. Victor On Tue, 2006-03-28 at 12:20 -0500, Ros Daniel wrote: I am a newbie at Python. Just bought Python Programming 2nd ed. by Michael Dawson. While I understand the concepts as the book is going through the code, and I am able get the same results, when it comes to applying what I've learned to the exercises at the end of each chapter, I seem to be stumped. I think my logic is off somehow. I am able to get the program to work if it's just a case of the user guessing the random number, and then being told they guessed correctly in a certain number of tries. It's when the user has a limited number of guesses that I am stumped. Either I get an infinite loop, or the program will say I guessed right in a certain number of tries, but the guess is not correct Can anyone explain to me what I'm missing and doing wrong? Thanks. # Modify the Guess My Number game so that the player has a limited number of guesses. If the player fails to guess in time, the program should display an appropriately chastising message. import random print Welcome to the new and improved 'Guess My Number' game. print This time you have a limited number of guesses, so guess wisely.\n the_number = random.randrange(100) + 1 guess = int(raw_input(Take a guess: )) tries = 1 # guessing loop while (guess != the_number): if tries 5: break elif guess the_number: print Lower... elif guess the_number: print Higher... guess = int(raw_input(Guess again:)) tries += 1 # message of congratulations print You guessed it! The number was, the_number print And it only took you, tries, tries!\n ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Splitting long string into same len parts
Aha!!! I believe this is what I was looking for in the first place (not that I will use it anyway, given the alternatives provided by others). I guess that coming from a Perl background, which as you know includes regexes as part of the core language, you tend to look to all solutions through this lens. I faced this problem before and solved it using regexes but could not remember how. Your re.findall() suggestion is nice though. Very clean. Thanks Danny. On Wed, 2006-02-08 at 18:55 -0800, Danny Yoo wrote: On Wed, 8 Feb 2006, Victor Bouffier wrote: Hi to all, I'd like to split a long string into equally long strings (len(str) = 3). I did the following using regexes: n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' o = re.split(r'(...)', n) print o ['', 'xb1', '', 'jyz', '', 'qnd', '', '1ee', '', 'nko', '', 'kqn', '', 'hep', '', '6vp', '', '692', '', 'qi9', '', 'tma', '', 'g3o', '', 'wzq', '', 'w0s', '', 'dq3', '', 'zjf', ''] Which gives me empty strings between each value. Hi Victor, Try using re.findall() instead of re.split(). The behavior you're seeing with split is perfectly logical: each pair of empty strings is being split by that three-character sequence. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Splitting long string into same len parts
On Thu, 2006-02-09 at 09:45 +, Alan Gauld wrote: Define easier :-) Right! You could just use string slicing and a stepsize of 3 in range: lst = [mystring[index : index+3] for index in range(0,len(mystring),3)] Ever since I found them, list comprehensions are my favorites. ... and you still have problems where the string is not exactly divisible by 3, should you add padding? Alan, I understand where you are coming from. However, in this case I don't have a problem since the incoming string will always be divisible by 3, in this particular case. Thanks for pointing it out though. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Iterating over a string: index and value
On Fri, 2006-02-10 at 12:42 -0800, Carroll, Barry wrote: I seem to recall reading somewhere that it is possible to concurrently generate the index and value of a string’s characters in a single for statement. Is this true or did imagine it? Here is the scenario: Given an ASCII string of arbitrary length and content, generate a sequence of tuples whose elements are: the index of each character in the string, and data based on the ordinal value of the character in the ASCII collating sequence. Hi Barry, Have a look at enumerate: list(enumerate('abcdefghijk')) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k')] You need to work on each tuple in the iterable, but the function takes you halfway. Hope it helps. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Splitting long string into same len parts
Hi to all, I'd like to split a long string into equally long strings (len(str) = 3). I did the following using regexes: n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' o = re.split(r'(...)', n) print o ['', 'xb1', '', 'jyz', '', 'qnd', '', '1ee', '', 'nko', '', 'kqn', '', 'hep', '', '6vp', '', '692', '', 'qi9', '', 'tma', '', 'g3o', '', 'wzq', '', 'w0s', '', 'dq3', '', 'zjf', ''] Which gives me empty strings between each value. So to actually have this working I ended up filtering through a list comprehension: o = [ x for x in re.split(r'(...)', n) if x ] print o ['xb1', 'jyz', 'qnd', '1ee', 'nko', 'kqn', 'hep', '6vp', '692', 'qi9', 'tma', 'g3o', 'wzq', 'w0s', 'dq3', 'zjf'] This is what I needed. Is there an easier or more straightforward way to do this? Thanks. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Splitting long string into same len parts
Hi Emile and John, Thanks a lot for your insight. There is always a better way, or at least a more pythonic one. Take care. Victor. On Wed, 2006-02-08 at 22:36 -0800, Emile van Sebille wrote: Andre Roberge [EMAIL PROTECTED] wrote in message There's a tongue-in-cheek quote that I really like: Sometimes you have a programming problem and it seems like the best solution is to use regular expressions; now you have two problems. +1 -- There are some things re is good for, but mainly it's good motivation to just do it in python... n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' length = len(n) o = [] for i in range(0, length, 3): o.append(n[i:i+3]) Or as a one-liner... o = [ n[ii:ii+3] for ii in range(0,len(n),3) ] Emile ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionaries
On Fri, 2006-01-27 at 13:20 -0500, Kent Johnson wrote: It doesn't make much difference for small dictionaries. keys(), values() and items() create new lists with the specified elements. iterkeys(), itervalues() and iteritems() create iterators that return the specified elements in sequence. So for the common case of iterating over dict elements with a for loop, the 'iter' variants conserve memory and may be faster (but always check!) because of the cost of creating the list. The iter variants are relatively new (since Python 2.2). I used to use the older variants in examples here so I wouldn't have to explain the difference :-) but ISTM that modern usage is heading to prefer the iter versions and I am starting to use them myself. But I guess you will not notice any difference in performance until you have dicts with many thousands of elements. Kent Hi Kent and Alan, Thanks to both for your response. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionaries
Hi Alan and Ken, I think know the difference between using items() vs. iteritems() and their equivalent for keys and values. I notice Ken suggests iteritems(), while Alan suggests items() only. Does one approach have an advantage over the other? Should we use only one of them favorably? Thanks. Victor On Thu, 2006-01-26 at 13:43 +, Alan Gauld wrote: How would I modify this to just print either the values or keys? Just ask for the values or the keys! for value in pairs.values() print value for key in pairs.keys() print key for key,value in pairs.items() print key print value ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Linux Python install?
I highly recommend you have a look into ipython. It is a breeze to work with. I usually have a couple of terminal screens open, one with the ipython interpreter, which helps me a lot when testing code snipplets. You can install it using yumex, or just run 'yum install ipython' from the root command line. If you just started with Fedora, go into this site and follow the tips provided. It really improves your working environment. It will also provide you with extra repositories which allow you the installation of ipython among other packages. Fedora Core 4 Tips and Tricks http://home.gagme.com/greg/linux/fc4-tips.php On Mon, 2006-01-23 at 10:06 -0500, Python wrote: On Mon, 2006-01-23 at 09:28 -0500, CPIM Ronin wrote: Sorry to bother the list with so simple a question but on moving to Linux from Windows XP, it's not clear to me how to accomplish a Python install on Linux. On XP it was mostly point and click on a .msi file (with msi standing for Microsoft install). I've loaded the latest Fedora/Redhat release on an old AMD machine. How do I install Python such that it shows up as a selection under the Programming task bar with EMACS? I assume you are using yum for package management. It should have been installed by default. As root, you can issue the command yum install python python-docs python-devel python-tools The package yumex provides a GUI interface to the yum package manager. You can think of yumex as the Windows Add/Remove Programs application on steroids. yum install yumex The yumex install view with a filter of python will provide an extensive list of additional python packages. Finally, I do not know if this includes the best python integration with EMACS. I assume I have to do this under root, right? Step by step please. Thanks. _ Dont just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Re] Fwd: Strings backwards
On Thu, 2006-01-19 at 16:49 -0500, Orri Ganel wrote: Victor Bouffier wrote: I had to do the string-to-list-then-reverse-string-then-back-to-string process myself before knowing about this marvelous operand. It works on tuples (all immutable objects) too: [SNIP] Not all immutable objects, just those that define __getslice__ (basically, those that use indexes: sequences). Ints, for example, are immutable and don't work: 12[::-1] Traceback (most recent call last): File pyshell#23, line 1, in -toplevel- 12[::-1] TypeError: unsubscriptable object - Orri I see. Thanks for the correction Orri Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Re] Fwd: Strings backwards
This was just posted by John Fouhy (snipped part of it): Basically, the syntax is [start:stop:step]. If step is negative, you work backwards. eg: string.lowercase[20:10:-2] # letters 20, 18, 16, 14, 12 'usqom' And if you omit the start or stop parameters, and step is negative, then start defaults to the end of the list and stop to the beginning. So string.lowercase[::-1] will step backwards, starting at the end and finishing at the start. So to reverse a string, you would only need to do the following: print 'hello world'[::-1] dlrow olleh I had to do the string-to-list-then-reverse-string-then-back-to-string process myself before knowing about this marvelous operand. It works on tuples (all immutable objects) too: digits = (0,1,2,3,4,5,6,7,8,9) print digits[::-1] (9, 8, 7, 6, 5, 4, 3, 2, 1, 0) Best of Luck Victor On Thu, 2006-01-19 at 08:26 +0100, János Juhász wrote: Hi Ryan, I just extended Adam's code with a speech-to-text recepi from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114216. On 18/01/06, ryan luna [EMAIL PROTECTED] wrote: Hello, what i need to do is get user input and then print the string backwards ^^ i have no idea how to do that, print Enter a word and i well tell you how to say it backwards word = raw_input(Your word: ) print word all that is simple enough im sure printing it out backwards is to, just dont know how ^^, thanks for any help. import sys from win32com.client import constants import win32com.client import string speaker = win32com.client.Dispatch(SAPI.SpVoice) print Type word or phrase, then enter. print Ctrl+Z then enter to exit. def backword(word): l = list(word) l.reverse() return ''.join(l) def backsentence(sentence): words = sentence.split(' ') words = [backword(word) for word in words] return ' '.join(words) while 1: try: s = raw_input() rev = backsentence(s) print 'I would say: ', rev speaker.Speak(rev) except: if sys.exc_type is EOFError: sys.exit() It works on my xp :) Yours sincerely, __ János Juhász ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string object into reference
Pujo, I think your solution does not address Kirk's problem. You don't mention the addition of surface areas. If for any reason he had more than two types of amino acids, then he would need to use a dictionary for the totals, with each key being a specific amino acid. The actual steps to follow are: 1. open the file to read 2. initialize the dictionary to empty 3. for each line in the file 4. see if the key for that amino acid already \ exists in the dictionary 5. if it does not exist, create a new dictionary \ key for that new amino acid, and initialize it \ to zero 6. add the surface area of the current line to the \ corresponding dictionary key 7. print the totals dictionary Kirk, I would write the program (would take me less time), but the idea is for yo uto learn to program in Python ;-) Post your code for review. Regards. Victor On Tue, 2006-01-17 at 22:08 +0100, Pujo Aji wrote: Hello Kirk, If I'm not mistaken your idea is referencing two columns: first column is your acid name and the later is your surface area. Later you want to connect the surface area if you name the acid name. If that what you want another question arises... is your acid name is unique. If it is you can make dictionary types. A csb B dsk C dsk you can create mydic = [] mydic['A'] = 'csb' mydic['B'] = 'dsk' mydic['C'] = 'dsk' you have to transform the file into a list and after that start building the dictionary variable. After this dictionary variable is filled. you can get the surface area by typing the acid name such as: print mydic['A'] # will result 'csb' Cheers, pujo On 1/17/06, Kirk Vander Meulen [EMAIL PROTECTED] wrote: Hi, just joined. I've got a question that I'm guessing there's a ridiculously easy answer to, but I'm having trouble (no excuses, I'm just dumb!)... My problem is I want to make a string object into a reference to another object. To be more specific, I'm reading through a text file of amino acids. The first item on each line is the amino acid name, and a later item is its exposed surface area. For each amino acid, I want to add up the surface area as I go through the text file. So what I'm doing is, for each line, assigning the reference 'residue' to the amino acid name. I'd like to then make the string referred to by 'residue' (eg, 'CYS' or 'TRP') a reference to an object that I will subsquently increment by the surface area value. Thanks for any help. Perhaps I just need to be pointed to a relevent thread or given the correct words to search for in the archives or manual. Kirk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string object into reference
Ooops. Did not respond to the mailing list. Here is my replied-to post. -- Hi Kirk, There is nothing as a dumb question. I am assuming your source file will have a amino acid residue ('CYS' or 'TRP'), followed by a space, and then the corresponding surface area. You have to define a variable for adding the surface areas of each residue type. As you only have one of two options, the easiest way is to define a variable for each (e.g. cys, trp) and then open the file and process each line, adding the surface area to the corresponding amino acid. As for reference, look for working with files (I/O), string variable splitting (split function), and basic operations to add each new surface area. Try writing some code and posting it back. Would be glad to review it. Victor On Tue, 2006-01-17 at 11:50 -0600, Kirk Vander Meulen wrote: Hi, just joined. I've got a question that I'm guessing there's a ridiculously easy answer to, but I'm having trouble (no excuses, I'm just dumb!)... My problem is I want to make a string object into a reference to another object. To be more specific, I'm reading through a text file of amino acids. The first item on each line is the amino acid name, and a later item is its exposed surface area. For each amino acid, I want to add up the surface area as I go through the text file. So what I'm doing is, for each line, assigning the reference 'residue' to the amino acid name. I'd like to then make the string referred to by 'residue' (eg, 'CYS' or 'TRP') a reference to an object that I will subsquently increment by the surface area value. Thanks for any help. Perhaps I just need to be pointed to a relevent thread or given the correct words to search for in the archives or manual. Kirk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionaries [Was: Re: string object into reference]
Hi Danny, On Tue, 2006-01-17 at 16:03 -0800, Danny Yoo wrote: My problem is I want to make a string object into a reference to another object. To be more specific, I'm reading through a text file of amino acids. The first item on each line is the amino acid name, and a later item is its exposed surface area. These kind of bulk questions are fairly easy to answer if we collect all the key-value pairs in a single dictionary container, because we're just asking that one container. But it's much harder to answer this if we use individual variables for each key-value pair, since we don't tell the system that those variables are somehow related as a group --- as far as Python knows, they're just disconnected variables. I couldn't agree more. I love using dictionaries. I don't know why I suggested individual variables instead of the usage of a dictionary in the first place. The terminology that the original poster uses (references to another object) sounds a lot like the original usage of symbolic soft references in Perl. (http://www.perl.com/doc/manual/html/pod/perlref.html) Perl programmers, for the most part, avoid them now because they're so error prone. So if the original poster is thinking about symbolic references, then we should encourage the poster to look into dictionaries, since dictionaries are a fairly direct replacement for that usage. I did not know Perl programmers were moving away from references. That's new to me, and an interesting point. On the other hand, Kirk's comment about references to another object takes us into a discussion over references, when we actually should be focusing on Perl's hashes (or references to hashes for that matter). Or better still, get away from Perl and start programming in Python and use dictionaries instead! ;-) Best of wishes! Thanks a lot. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python debugger bummer
Hi to all, I tried to look for a reference to this issue in the ASPN archive, but I can't seem to find an answer. I currently work under Linux and have never been able to properly use the Python debugger. Coming from a Perl background, I fail to find a similar simple way to step through my code the way I am able to do it through the -d flag using Perl on the command line. It is so painless. I have used Python on Windows, usually writing my programs using Vim, and entering the PythonWin environment to debug my programs. It is a good environment to do that, although I prefer my independent editor for writing my programs. I once paid for ActiveState's Komodo for Linux to use as an IDE, but I find it bloated and slow, not to mention the need to constantly upgrade if you want to keep up with versions (have not done it yet). Does anyone have any suggestions as to an alternative to PythonWin, or even better still, a reference to a good tutorial on how to use my current tools: how to use the python debugger as the way Perl debugger works? I am certain the Python interpreter (being better that Perl in that sense) must have a way to use the debugger. I work under Linux using vi/gvim and ipython (I have never really tried IDLE). Thanks in advance for any help. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python debugger bummer
Hi again, I was going through the Python library documentation and I found something I never saw before. $ python -m pdb myscript.py This is what I was looking for! Great help. Any further reference could of course help a lot. I never was able to get the hang of it until now. Victor On Mon, 2006-01-16 at 13:12 -0600, Victor Bouffier wrote: Hi to all, I tried to look for a reference to this issue in the ASPN archive, but I can't seem to find an answer. I currently work under Linux and have never been able to properly use the Python debugger. Coming from a Perl background, I fail to find a similar simple way to step through my code the way I am able to do it through the -d flag using Perl on the command line. It is so painless. I have used Python on Windows, usually writing my programs using Vim, and entering the PythonWin environment to debug my programs. It is a good environment to do that, although I prefer my independent editor for writing my programs. I once paid for ActiveState's Komodo for Linux to use as an IDE, but I find it bloated and slow, not to mention the need to constantly upgrade if you want to keep up with versions (have not done it yet). Does anyone have any suggestions as to an alternative to PythonWin, or even better still, a reference to a good tutorial on how to use my current tools: how to use the python debugger as the way Perl debugger works? I am certain the Python interpreter (being better that Perl in that sense) must have a way to use the debugger. I work under Linux using vi/gvim and ipython (I have never really tried IDLE). Thanks in advance for any help. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python debugger bummer
Thanks Alan. As always, you are very helpful. Victor On Mon, 2006-01-16 at 23:35 +, Alan Gauld wrote: I was going through the Python library documentation and I found something I never saw before. $ python -m pdb myscript.py I was just about to suggest loading pdb... And of course there is also a graphical debugger in IDLE as well as PythonWin. The paper version of my book contains a chapter (not on the web site) on how to use pdb to debug a script. pdb has its limitations but if you are used to gdb then its not too bad. (pdb) help is your friend. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Paradox database files
Hi all, I know this is OT from Python, but does anybody know how to fix my library issues. I get some awkward dependencies issues from these pylib libraries. # rpm -Uvh pxlib-0.4.3-1.i386.rpm error: Failed dependencies: libbz2.so.1.0 is needed by pxlib-0.4.3-1.i386 but when I look into my libraries I find the necessary ones under /usr/lib: # ll /usr/lib/libbz2* -rwxr-xr-x 1 root root 67594 Jun 15 2004 /usr/lib/libbz2.a lrwxrwxrwx 1 root root11 Feb 6 11:02 /usr/lib/libbz2.so - libbz2.so.1 lrwxrwxrwx 1 root root15 Feb 6 10:10 /usr/lib/libbz2.so.1 - libbz2.so.1.0.2 lrwxrwxrwx 1 root root24 Mar 8 09:41 /usr/lib/libbz2.so.1.0 - /usr/lib/libbz2.so.1.0.2 -rwxr-xr-x 1 root root 71724 Jun 15 2004 /usr/lib/libbz2.so.1.0.2 I created the second-to-last symlink with no success. I also added '/usr/lib' to /etc/ld.so.conf as suggested in a newsgroup. I've got a Fedora Core3 with both apt and yum installed, and both tell me I've got the latest libraries (bzip2-libs). If you believe I should post my question elsewhere, please let me know. Thanks. Victor apple_py wrote: ---Original Message--- From: Danny Yoo [EMAIL PROTECTED] Subject: Re: [Tutor] Paradox database files Sent: 08 Mar 2005 01:51:35 On Mon, 7 Mar 2005, Victor Bouffier wrote: Does anybody know of a Python module to read from Paradox database files? I don't need to write back to the files. These files are being exported using a proprietary application and I need to parse them to extract transaction information. Hi Victor, You might be interested in 'pxview': http://pxlib.sourceforge.net/pxview.html which can extract CSV-formatted files out of Paradox Database files. Once you have your data in CSV format, then Python's csv module can come into play: http://www.python.org/doc/lib/module-csv.html Alternatively, you might be able to use the pxlib Python bindings directly. According to: http://pxlib.sourceforge.net/documentation.php?manpage=pxlib a Python binding exists somewhere out there, though I haven't been able to find it yet... ok, found it, but it appears you might need to check it out of CVS: http://cvs.sourceforge.net/viewcvs.py/pxlib/bindings/ so this might not be as easy to use right out of the box. ---Original Message--- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Victor Bouffier Finance Manager www.grupoandersons.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Paradox database files
Hi all. Does anybody know of a Python module to read from Paradox database files? I don't need to write back to the files. These files are being exported using a proprietary application and I need to parse them to extract transaction information. I found something about ODBC being able to connect to several database types, but I am not even sure how this would work with Paradox. Any OS solution you suggest works fine for me, since I have access to both a unix (linux) box and Python on Windows too. Thanks. -- Victor Bouffier Finance Manager www.grupoandersons.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] MySQLdb error while inserting records
Hi all, I consider myself fairly proficient with SQL, but I'm still getting the hang of the MySQL API. I am working through the examples in Open Source Web Development with LAMP: Using Linux, Apache, MySQL, Perl, and PHP by James Lee and Brent Ware, and trying to make the third P to be Python. :) There is an example in the book which is written in Perl, used to insert new records to MySQL. I tried it as it is written and it works fine. I have migrated to Python another example that gets all of the records in the age_information table (SELECT query), and it is getting the data successfully. However, I am having problems with the program to insert records. The following is my modified code in Python: -- 1 #!/usr/bin/python 2 # connect.py 3 4 import sys 5 import MySQLdb 6 7 if len(sys.argv) != 4: 8 print You have to enter lastname, firstname and age\n 9 sys.exit(1) 10 11 # This is to change the age type from str to int 12 last, first, strAge = sys.argv[1:] 13 age = int(strAge) 14 15 # Some debugging lines 16 print last, first, age 17 print type(last), type(first), type(age) 18 print 19 #sys.exit() 20 21 22 try: 23 conn = MySQLdb.connect(host='localhost', 24 user='apache', passwd='LampIsCool', db='people') 25 except: 26 print Could not connect\n 27 sys.exit(1) 28 29 c = conn.cursor() 30 31 # prepare the SQL, exit() if the preparation fails 32 query = ''' 33 INSERT INTO age_information 34 (lastname, firstname, age) 35 VALUES (?, ?, ?) 36 ''' 37 38 # execute the SQL 39 records = c.execute(query, (last, first, age)) 40 if records = 1: 41 print Succesfully inserted %d records % records 42 else: 43 print Could not insert anything, sorry. 44 45 c.commit() 46 c.close() 47 conn.close() 48 -- Executing the script from the command line, I get the following output: -- $ ./insert.py Cool Joe 13 Cool Joe 13 type 'str' type 'str' type 'int' Traceback (most recent call last): File ./insert.py, line 39, in ? records = c.execute(query, (last, first, age)) File /usr/lib/python2.3/site-packages/MySQLdb/cursors.py, line 95, in execute return self._execute(query, args) File /usr/lib/python2.3/site-packages/MySQLdb/cursors.py, line 110, in _execute self.errorhandler(self, TypeError, m) File /usr/lib/python2.3/site-packages/MySQLdb/connections.py, line 33, in defaulterrorhandler raise errorclass, errorvalue TypeError: not all arguments converted during string formatting -- I was getting this same error so I entered lines 12 and 13 to change the age from type string to integer. No change. Do you know what am I missing? Thanks to all. -- Victor Bouffier Finance Manager www.grupoandersons.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor