Re: Photoimage on button appears pixelated when button is disabled
On May 17, 7:11 am, Tim Golden m...@timgolden.me.uk wrote: Dustan wrote: On May 15, 2:59 pm, Dustan dustangro...@gmail.com wrote: In tkinter, when I place a photoimage on a button and disable the button, the image has background dots scattered through the image. Searching the web, I wasn't able to find any documentation on this behavior, nor how to turn it off. So here I am. How do I keep this from happening? Also, how can I extract the base-64 encoding of a GIF, so I can put the image directly into the code instead of having to keep a separate file for the image? All responses appreciated, Dustan At the very least, someone ought to be able to provide an answer to the second question. Well I know nothing about Tkinter, but to do base64 encoding, you want to look at the base64 module. TJG Thanks. And for my former question, I worked something out, figuring there must be no solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: Photoimage on button appears pixelated when button is disabled
On May 15, 2:59 pm, Dustan dustangro...@gmail.com wrote: In tkinter, when I place a photoimage on a button and disable the button, the image has background dots scattered through the image. Searching the web, I wasn't able to find any documentation on this behavior, nor how to turn it off. So here I am. How do I keep this from happening? Also, how can I extract the base-64 encoding of a GIF, so I can put the image directly into the code instead of having to keep a separate file for the image? All responses appreciated, Dustan At the very least, someone ought to be able to provide an answer to the second question. -- http://mail.python.org/mailman/listinfo/python-list
Photoimage on button appears pixelated when button is disabled
In tkinter, when I place a photoimage on a button and disable the button, the image has background dots scattered through the image. Searching the web, I wasn't able to find any documentation on this behavior, nor how to turn it off. So here I am. How do I keep this from happening? Also, how can I extract the base-64 encoding of a GIF, so I can put the image directly into the code instead of having to keep a separate file for the image? All responses appreciated, Dustan -- http://mail.python.org/mailman/listinfo/python-list
How do I escape slashes the string formatting operator? (or: why is it behaving this way?)
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. 'HELP!%(xyz)/' % {'xyz':' PLEASE! '} Traceback (most recent call last): File stdin, line 1, in module ValueError: unsupported format character '/' (0x2f) at index 11 It doesn't like the forward slash after the closed parentheses. I don't know what it is expecting, but I need that slash there (obviously this is a simplified example). All help appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I escape slashes the string formatting operator? (or: why is it behaving this way?)
On May 6, 6:51 pm, marek.ro...@wp.pl wrote: Dustan napisa³(a): Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. 'HELP!%(xyz)/' % {'xyz':' PLEASE! '} Traceback (most recent call last): File stdin, line 1, in module ValueError: unsupported format character '/' (0x2f) at index 11 It doesn't like the forward slash after the closed parentheses. I don't know what it is expecting, but I need that slash there (obviously this is a simplified example). All help appreciated. Strign formatting docs (http://docs.python.org/library/ stdtypes.html#string-formatting) say that specifying a conversion type is mandatory. So you actually should write something like: 'HELP!%(xyz)s/' % {'xyz':' PLEASE! '} Thanks. That seems to have worked nicely. -- http://mail.python.org/mailman/listinfo/python-list
Re: Do any of you recommend Python as a first programming language?
On Mar 22, 10:40 am, jmDesktop [EMAIL PROTECTED] wrote: For students 9th - 12th grade, with at least Algebra I. Do you think Python is a good first programming language for someone with zero programming experience? Using Linux and Python for first exposure to programming languages and principles. Yes. Thank you. You're welcome. -- http://mail.python.org/mailman/listinfo/python-list
Re: List question
On Mar 21, 3:57 pm, Paul Rubin http://[EMAIL PROTECTED] wrote: [EMAIL PROTECTED] writes: if 'one' and 'two' in f: alist.append(f) Use: if 'one' in f and 'two' in f: ... Personally, I would put parentheses around to be clearer: if ('one' in f) and ('two' in f): ... I'm not saying to put parentheses around everything, but in the more ambiguous cases, it certainly helps. -- http://mail.python.org/mailman/listinfo/python-list
Re: This actually works.
On Mar 13, 6:19 pm, Dotan Cohen [EMAIL PROTECTED] wrote: On 14/03/2008, Dustan [EMAIL PROTECTED] wrote: you.screw() Ah, you are pushing sex pills. self.thank(God, encapsulation) And bibles? Interesting combination. not self.want_to_know(you.screw.func_code) Unsubscribe? I know better... Dotan Cohen http://what-is-what.comhttp://gibberish.co.il א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? SyntaxError: invalid syntax -- http://mail.python.org/mailman/listinfo/python-list
Re: List mutation method gotcha - How well known?
On Mar 13, 1:56 pm, yoz [EMAIL PROTECTED] wrote: This will cause a hidden feature of python and the OS, known as the 'python easter egg', to activate - erasing all data on the hard disk and then reporting how many bytes of data are left. Usually None ;-} - This really is a 'gotcha' (Aren't you sorry you cheated and typed this in !!) So the answer is 5 ? Good one. You got a smile out of me. -- http://mail.python.org/mailman/listinfo/python-list
Re: List mutation method gotcha - How well known?
On Mar 13, 2:36 am, Hendrik van Rooyen [EMAIL PROTECTED] wrote: Hi, I am surprised that it took me so long to bloody my nose on this one. It must be well known - and I would like to find out how well known. So here is a CLOSED BOOK multiple choice question - no RTFM, no playing at the interactive prompt: Given the following three lines of code at the interactive prompt: foo = [1,2,3,4] x = foo.append(5) print x What will be the output (choose one): 1) [1,2,3,4] 2) [1,2,3,4,5] 3) That famous picture of Albert Einstein sticking out his tongue 4) Nothing - no output 5) None of the above 5. -- http://mail.python.org/mailman/listinfo/python-list
Re: This actually works.
On Mar 13, 3:16 pm, [EMAIL PROTECTED] wrote: not self.believe programming.screw() self.serious; this.works make_money(EASY) anyone.can_do(this) you.screw() self.thank(God, encapsulation) not self.want_to_know(you.screw.func_code) programming.is_good -- http://mail.python.org/mailman/listinfo/python-list
Re: iter(lambda:f.read(8192),'')
On Feb 24, 5:11 am, gert [EMAIL PROTECTED] wrote: what is the difference between iter(lambda:f.read(8192), ') and iter(f.read(8192),'') ? One does not work, and one is syntactically incorrect: iter(f.read(8192),'') Traceback (most recent call last): File pyshell#0, line 1, in module iter(f.read(8192),'') TypeError: iter(v, w): v must be callable iter(lambda:f.read(8192), ') SyntaxError: EOL while scanning single-quoted string To clarify: f.read(8192) returns the next 8192 bytes of the file in a string, or whatever is leftover, or an empty string when the file is exhausted. lambda: f.read(8192) is a function that will return the next 8192 bytes of the file every time it is called. So iter(f.read(8192),'') is evaluated as iter(some_string, ''). When iter receives two arguments, it expects the first to be a function, not a string. iter(lambda:f.read(8192), '') (what you probably meant) is what it looks like: iter(some_func, ''). -- http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
On Feb 16, 4:40 pm, Zack [EMAIL PROTECTED] wrote: what method can you use on x to find all available attributes for that class? class Foo(object): bar = hello, world! def __init__(self, baz): self.baz = baz x = Foo(42) x.__dict__.keys() # Does not include bar ['baz'] dir(x) # Includes bar plus some methods ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'bar', 'baz'] -- http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
On Feb 16, 5:59 pm, Zack [EMAIL PROTECTED] wrote: Zack wrote: Diez B. Roggisch wrote: Zack schrieb: If I have a class static variable it doesn't show up in the __dict__ of an instance of that class. class C: n = 4 x = C() print C.__dict__ {'__module__': '__main__', '__doc__': None, 'n': 4} print x.__dict__ {} This behavior makes sense to me as n is not encapsulated in x's namespace but what method can you use on x to find all available attributes for that class? x.__class__.__dict__ Diez This would leave out any attributes of base classes. Not that I asked for that functionality in my original post but is there a way to get all attributes qualified by x. ? I see that I could walk the dict of x, x.__class__ and x.__class__.__bases__ until I exhaust the tree. But is there a built in method for doing this? I believe this accomplishes what I'm looking for. I'm not positive it is correct or if there are cases I've missed. It would be nice if there is a simple python builtin for finding the fully qualified dict. def fullDict(obj): ''' Returns a dict with all attributes qualified by obj. obj is an instance of a class ''' d = obj.__dict__ # update existing items into new items to preserve inheritance tmpD = obj.__class__.__dict__ tmpD.update(d) d = tmpD supers = list(obj.__class__.__bases__) for c in supers: tmpD = c.__dict__ tmpD.update(d) d = tmpD supers.extend(c.__bases__) return d I know you're probably dumping this for dir(), but I should still warn you: This function modifies the class dictionary, which might not have been what you intended. -- http://mail.python.org/mailman/listinfo/python-list
Re: Edit Python code programmatically
On Feb 9, 6:10 am, Alex [EMAIL PROTECTED] wrote: Guilherme Polo wrote: 2008/2/9, Alex [EMAIL PROTECTED]: Which library could you recommend to perform simple editing of Python code (from Python program)? For example, open *.py file, find specific function definition, add another function call inside, find existing call and change parameter value, etc. You are after inspect, it is included with python. Yes, I forgot to mention - I'm new to Python. I didn't necessary mention 3rd party library. Simply such wasn't mentioned in library review and tutorials, so I didn't know of it. What's the module's name? inspect. What I'm trying to implement isn't a real visual programming tool, but some code-generation is necessary. For now I think I can generate Python syntax manually (like any text file), but it can become more complicated in future (like partially implementing code-generation library), plus there'll always be possibility of corrupting files and losing data (or having to recover valid Python syntax manually) due to coding mistake. Generating code like this is always dangerous. Maybe you could generate some other kind of file, then use some library or build one, to operator over this file. No, the code by itself is the goal. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not a Python compiler?
On Feb 5, 2:37 am, Kay Schluehr [EMAIL PROTECTED] wrote: On Feb 5, 9:19 am, Santiago Romero [EMAIL PROTECTED] wrote: ( Surely if this question has been asked for a zillion of times... ) Sure. You can access comp.lang.python via groups .google.com. It has a search function. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python feature request : operator for function composition
On Feb 4, 10:11 am, Arnaud Delobelle [EMAIL PROTECTED] wrote: This is nice. Thanks. * I wouldn't choose '' as the composing operator as when I read 'double square' I think 'take an x, double it square it' which is the wrong interpretation (perhaps instead?). A very good point that I didn't think about; I just blindly took the OP's chosen operator. Another thing I realized after writing this was that I could have also written a corresponding __rand__ method (__rlshift__ with your alternative operator), in case the object to the right of the operator is a composer object and to the left is a simple function. * I would call the decorator 'composable'. The thing about that, though, is that this can also be used as a composition in function style. However, I can't think of any name that encompasses both uses. And you're right in that composer wasn't a very good choice of name. As I say, it was written in haste. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python feature request : operator for function composition
On Feb 2, 11:09 pm, Kay Schluehr [EMAIL PROTECTED] wrote: [snip] While you're waiting for it to be implemented, you can build your own version as a decorator. Here's an example written in haste: class composer(object): def __init__(self, *funcs): self.funcs = funcs def __and__(self, other): if isinstance(other, composer): return composer(*(self.funcs+other.funcs)) else: return composer(*(self.funcs+(other,))) def __call__(self, *args, **kargs): for func in reversed(self.funcs): args = (func(*args, **kargs),) if kargs: kargs = {} return args[0] @composer def double(x): return 2*x @composer def square(x): return x*x double_square = double square square_double = square double double_square(2) 8 square_double(2) 16 double_square(3) 18 square_double(3) 36 double_square(4) 32 square_double(4) 64 Probably not the best implementation, but you get the idea. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary Keys question
On Jan 30, 7:02 pm, FireNWater [EMAIL PROTECTED] wrote: Thank you for the explanation. . . I think I now have a (foggy) understanding of hash tables. It seems to be a way to create order (an index) out of disorder (random numbers or characters) behind the scenes. . The key thing to realize is, quite simply, don't rely on order in a dictionary. If you do, bad things can happen. The underlying implementation is not important to know. But if you really do want to know, let me correct you here, and give a perhaps clearer explanation (if not, there's no need to read any further): The 'order' that your speaking of is not implemented by the hash *table*, per se, but rather by the hash function, which returns an integer (the hash code). The hash table takes the hash code and calculates where in its list to place the object (as explained before, using modulo to shrink the integer into the range of the list). If multiple items end up in the same list, they are placed into a kind of linked list, with each node containing an object and pointing to the next. Of course, if too many objects end up in the same bucket, the efficiency of finding an object in the hash table reduces to that of a linked list, so hash functions are generally implemented to ensure a unique number (or as unique as possible) to every object. Python dictionaries are hash tables that automatically grow as space is needed. While integers in the range of the list will never change location unless the list shrinks, larger hash codes can move around quite apparently randomly. Space available is also a factor, as others have found out on this list. The order of a dictionary *is* determined, but factors involved in deciding that order may appear surprisingly mundane, and certainly variable across runs of your program. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary Keys question
On Jan 31, 7:35 am, Ben Finney [EMAIL PROTECTED] wrote: Dustan [EMAIL PROTECTED] writes: On Jan 30, 7:02 pm, FireNWater [EMAIL PROTECTED] wrote: Thank you for the explanation. . . I think I now have a (foggy) understanding of hash tables. It seems to be a way to create order (an index) out of disorder (random numbers or characters) behind the scenes. . The key thing to realize is, quite simply, don't rely on order in a dictionary. The poster to which you replied is using order as contrasted with disorder. Clearly dictionaries *do* have order that can be relied upon. He was referring to the index. So was I, as in: Don't rely on the index, because the size of the dictionary can vary, and therefore, the index can vary, and therefore, the programmer must recognize that the order of looping can vary. If you're referring to the actual order of looping, then I and every good Python Guru (of which I am not one) disagrees with you. If not, then you're confusing the different meanings of order in this context. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary Keys question
On Jan 30, 4:47 pm, FireNWater [EMAIL PROTECTED] wrote: I'm curious why the different outputs of this code. If I make the dictionary with letters as the keys, they are not listed in the dictionary in alphabetical order, but if I use the integers then the keys are in numerical order. I know that the order of the keys is not important in a dictionary, but I was just curious about what causes the differences. Thanks!! list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] list2 = [1,2,3,4,5,6,7,8] Dictionary = dict(zip(list1, list2)) print Dictionary Dictionary1 = dict(zip(list2, list1)) print Dictionary1 The underlying order is a result, in part, of the key's hash codes*. Integers are hash coded by their integer values, therefore, they appear in numeric order. Strings, however, use an algorithm that ensures as unique hash codes as possible. Notice the difference: map(hash, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 1, 2, 3, 4, 5, 6, 7, 8]) [-468864544, -340864157, -212863774, -84863387, 43136996, 171137383, 299137766, 427138153, 1, 2, 3, 4, 5, 6, 7, 8] * emphasis on the in part. Other factors include the amount of memory space available, order added, the current size of the underlying hash table, etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k feature proposal: field auto-assignment in constructors
On Jan 27, 12:41 pm, Torsten Bronger [EMAIL PROTECTED] wrote: Hallöchen! Wildemar Wildenburger writes: André wrote: Personally, I like the idea you suggest, with the modification that I would use . instead of @, as in class Server(object): def __init__(self, .host, .port, .protocol, .bufsize, .timeout): pass I like :) However, you can probably cook up a decorator for this (not certain, I'm not a decorator Guru), which is not that much worse. Still, I'd support that syntax (and the general idea.). Well, you save one or two lines per class. Not enough in my opinion. Are you referring to the alternate syntax or to the decorator? Either way, you could be saving 4 or 5 or more lines, if you have enough arguments. -- http://mail.python.org/mailman/listinfo/python-list
Re: strange syntax rules on list comprehension conditions
On Jan 18, 1:04 pm, Chris Mellon [EMAIL PROTECTED] wrote: On Jan 18, 2008 12:53 PM, Nicholas [EMAIL PROTECTED] wrote: I was quite delighted today, after extensive searches yielded nothing, to discover how to place an else condition in a list comprehension. Trivial mask example: [True if i 5 else False for i in range(10)] # A [True, True, True, True, True, False, False, False, False, False] I then experimented to drop the else statement which yields an error [i if i3 for i in range(10)] That would be: [i for i in range(10) if i3] Traceback ( File interactive input, line 1 this syntax works of course [i if i3 else i for i in range(10)] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -- http://mail.python.org/mailman/listinfo/python-list
Re: anti-spam policy for c.l.py?
On Jan 16, 11:31 am, _wolf [EMAIL PROTECTED] wrote: On Jan 16, 3:11 pm, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: Jeroen Ruigrok van der Werven a écrit : -On [20080116 12:51], Bruno Desthuilliers ([EMAIL PROTECTED]) wrote: Apart from checking posts headers and complaining about the relevant ISPs, there's not much you can do AFAIK. This is usenet, not a mailing-list. It is both actually. [EMAIL PROTECTED] is linked to comp.lang.python due to a news gateway. Yes, I know - but the OP explicitely mentionned c.l.py (re-read the title), not the ML. technically correct, but the idea is of course to keep all those archives relatively clean and informative. the new fad i've observed seems to be to initiate whole threads where previously spam very often stopped short of any second post. The ones that have received more than 2 responses have, the vast majority of the time, been cross posts. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple List division problem
On Jan 12, 2:25 pm, Paul Rubin http://[EMAIL PROTECTED] wrote: marcstuart [EMAIL PROTECTED] writes: what I would like to get is 3 sublists print z[0] = [1,2,3] print z[2] = [4,5,6] print z[3] = [7,8,9,10] Are you SURE you want that? In almost every situation I've seen, print z[0] = [1,2,3] print z[2] = [4,5,6] print z[3] = [7,8,9] print z[4] = [10] is preferable. Even more preferable is: print z[0] = [1,2,3] print z[1] = [4,5,6] print z[2] = [7,8,9] print z[3] = [10] -- http://mail.python.org/mailman/listinfo/python-list
Re: What is lambda x=x : ... ?
On Jan 10, 12:36 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I've figured it out, it is default argument. print y() gives 13 as result. It's a bit evil though. Why? It's the same syntax as with functions: x=3 def y(x=x): return x+10 print y(2) # prints 12 print y() # prints 13 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's great, in a word
On Jan 7, 7:09 am, [EMAIL PROTECTED] wrote: I'm a Java guy who's been doing Python for a month now and I'm convinced that 1) a multi-paradigm language is inherently better than a mono-paradigm language 2) Python writes like a talented figure skater skates. Would you Python old-timers try to agree on a word or two that completes: The best thing about Python is ___. Please, no laundry lists, just a word or two. I'm thinking fluid or grace but I'm not sure I've done enough to choose. Here's a modest list: Masterly, tops, best obtainable, high-grade, very good, select, outstanding, exemplary, top-notch, boss, first-rate, crack, smashing, excelling, prime, skilled, crackerjack, sublime, super, terrific, peerless, notable, paramount, divine, premium, hand-picked, estimable, admirable, prize, choice, competent, desirable, attractive, foremost, to be desired, A-one, top-flight, dandy, incomparable, grade A, capital, great, dynamite, heavenly, unique, refined, matchless, high- quality, well-done, A-OK, blue-chip, frontline, sensational, highest, jim-dandy, splendid, extraordinary, exquisite, superlative, worthy, masterful, distinguished, magnificent, tiptop, accomplished, all right, first, first-class, fine, very fine, ace-high, exceptional, sharp, supreme, marvelous, transcendent, praiseworthy, custom-made, remarkable, world-class, invaluable, groovy, champion, rare, best, wonderful, superb, choicest, enticing, top, superfine, commendable, skillful, neat, striking, distinctive, priceless, sterling, superior, cool, classy, finest, hot, keen, above par. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's great, in a word
On Jan 7, 11:40 am, Martin Marcher [EMAIL PROTECTED] wrote: it's pythonicness. it is pythonicness??? -- http://mail.python.org/mailman/listinfo/python-list
Re: fastest method to choose a random element
On Jan 5, 4:16 am, [EMAIL PROTECTED] wrote: The warning The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet. means a person, but not a bot, may see my email address, so it is safe to use my real address next time... Wrong. A bot may be able to read and scan all messages sent through Usenet. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does __builtins__ mean different things...
On Dec 22, 1:59 pm, James Stroud [EMAIL PROTECTED] wrote: Dustan wrote: On Dec 21, 8:11 pm, James Stroud [EMAIL PROTECTED] wrote: I swear there is another thread going on here of which I am not aware. You just keep on telling yourself that. Is there a cricket here? No, but you can tell yourself that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does __builtins__ mean different things...
On Dec 21, 8:11 pm, James Stroud [EMAIL PROTECTED] wrote: I swear there is another thread going on here of which I am not aware. You just keep on telling yourself that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance on local constants?
On Dec 22, 6:04 am, John Machin [EMAIL PROTECTED] wrote: t3 = re.compile('whatever').search Ack! No! Too Pythonic! GETITOFF! GETITOFF!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python implementation of include
[EMAIL PROTECTED] wrote: Hello, I've been using the Python-based Karrigell web application framework. It has the very handy word include that inserts a code file into into the stream of execution. E.g. if myFile.py contains the code: print This is a message from myFile.pybr and my script is: print Somethingbr include myFile.py print Something morebr The output would be: Something This is a message from myFile.py Something more Since I'm considering moving my application to a different web application framework, I'd like to replace include with a pure python construct. I've discovered several ways to do it, but they all seem kludgy in one way or another. Is there a simple, elegant way to do this? No. Python is not C. The closest you can get is: from myFile import * print some_variable_from_myFile But instead, you should probably just import: import myFile print myFile.some_variable_from_myFile -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuning question
On Nov 28, 3:15 pm, Wally Lepore [EMAIL PROTECTED] wrote: Hi Graham Is this email still good? Not anymore. You just gave it out to millions of spammers on Usenet. Its been awhile since we spoke last on the tuning list. Are you still on Yahoo messenger? Also, what is your email address please. You told me to email you when I had questions that seemed too basic for the tuning list. Thanks Graham. My email is [EMAIL PROTECTED] Stay well Walter (Wally) Lepore -- http://mail.python.org/mailman/listinfo/python-list
Re: How to use list as key of dictionary?
On Nov 6, 3:58 am, Duncan Booth [EMAIL PROTECTED] wrote: Wildemar Wildenburger [EMAIL PROTECTED] wrote: maybe something like this could help: def tupleize(non_tuple): try: return tuple(tupleize(thing) for thing in non_tuple) except TypeError: # non_tuple is not iterable return non_tuple Just don't try passing that a string or anything containing a string. Untested def tupleize(non_tuple): if isinstance(non_tuple, str): return non_tuple try: return tuple(tupleize(thing) for thing in non_tuple) except TypeError: # non_tuple is not iterable return non_tuple -- http://mail.python.org/mailman/listinfo/python-list
Re: how does google search in phrase
On Nov 4, 6:21 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: hi my friends; google can searching in phrase but it is imposible. it have a lot of page in data base and quadrillions sentence it can't search in fulltxt all of them .it need a super algorithm. ý need the algorithm now. if you have a idea ,pls share to me Ummm... What? Do you want to use Google or create another Google? thanks (sorry for my bad english :( ) -- http://mail.python.org/mailman/listinfo/python-list
Re: how does google search in phrase
On Nov 5, 7:14 am, Jeff [EMAIL PROTECTED] wrote: Here is a detailed explanation: http://www.google.com/technology/pigeonrank.html Ha ha... Hilarious. -- http://mail.python.org/mailman/listinfo/python-list
Re: setting variables in outer functions
On Oct 31, 5:59 pm, Chris Mellon [EMAIL PROTECTED] wrote: On Oct 31, 2007 5:49 PM, Dustan [EMAIL PROTECTED] wrote: [snip] I'm not going to respond to any of this, but I'm just going to say: I'm not claiming that the use of closures is common. I'm just claiming that it can be useful. I have used closures exactly once. I feel that that one time, it was for a good cause. -- http://mail.python.org/mailman/listinfo/python-list
Re: setting variables in outer functions
On Oct 30, 11:29 am, Duncan Booth [EMAIL PROTECTED] wrote: Neil Cerutti [EMAIL PROTECTED] wrote: It's allows a standard programming idiom which provides a primitive form of object oriented programming using closures to represent state. def account(opening_balance): balance = opening_balance def get_balance(): nonlocal balance return balance def post_transaction(x): nonlocal balance balance += x return balance, post_transaction fred_balance, fred_post = account(1500) joe_balance, joe_post = account(12) fred_post(20) joe_post(-10) fred_balance() TypeError: 'int' object is not callable 1520 joe_balance() TypeError: 'int' object is not callable 2 Python classes will of course nearly always win, though the idiom looks like it might be faster (I don't have Python 3000 to try it out). Python classes might be less error prone. Why would using classes make your code any less prone to typographical errors? -- http://mail.python.org/mailman/listinfo/python-list
Re: setting variables in outer functions
On Oct 31, 7:08 am, Duncan Booth [EMAIL PROTECTED] wrote: Dustan [EMAIL PROTECTED] wrote: On Oct 30, 11:29 am, Duncan Booth [EMAIL PROTECTED] wrote: Neil Cerutti [EMAIL PROTECTED] wrote: It's allows a standard programming idiom which provides a primitive form of object oriented programming using closures to represent state. def account(opening_balance): balance = opening_balance def get_balance(): nonlocal balance return balance def post_transaction(x): nonlocal balance balance += x return balance, post_transaction fred_balance, fred_post = account(1500) joe_balance, joe_post = account(12) fred_post(20) joe_post(-10) fred_balance() TypeError: 'int' object is not callable 1520 joe_balance() TypeError: 'int' object is not callable 2 Python classes will of course nearly always win, though the idiom looks like it might be faster (I don't have Python 3000 to try it out). Python classes might be less error prone. Why would using classes make your code any less prone to typographical errors? Lots of reasons: shorter and clearer code being high on the list. It wouldn't be necessarily shorter, depending on what you're working with. Clearer is a matter of opinion. The class equivalent would be: class Account(object): def __init__(self, opening_balance): self.balance = opening_balance def post_transaction(self, x): self.balance += x fred = Account(1500) joe = Account(12) fred.post_transaction(20) joe.post_transaction(-10) fred.balance 1520 joe.balance 2 There is no scope for the particular error I highlighted: you no longer have the duplication of declaring the functions and then returning them. The 'particular error' you highlighted was a typographical error, which can happen in any code. Sure, you can't have the exact same typographical error, but that's what happens when you switch between paradigms. Also you don't need the accessor function at all (and if at some point in the future you do want it you can make it a property). You don't have to invent separate names for each of the returned functions: the dot notation suddenly makes that a no brainer. Fair enough; you got two valid arguments there. Also the class is easier to extend: you no longer have to find and change every call to account() if you want to add another method: just add it. Of course, there are cases where you'll never want to extend it. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Python 3000 Question
On Oct 29, 7:59 pm, Wildemar Wildenburger [EMAIL PROTECTED] wrote: Bjoern Schliessmann wrote: The inconsistencies arise, IMHO, if an OO language introduces non-object types for performance reasons, after that gets wrapper classes to wrap those primitives, and even later gets the ability to automatically cast a primitive into a wrapper class instance. That's just ugly. If you mean Java, then just say Java. There was no need to; it was heavily implied. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using msvcrt (in Windows), how to catch Enter key?
On Oct 29, 4:26 am, Dick Moores [EMAIL PROTECTED] wrote: Windows XP Pro, Python 2.5.1 import msvcrt while True: if msvcrt.kbhit(): key = msvcrt.getch() if key == 'Enter' do something Is there a way to catch the pressing of the 'Enter' key? Thanks, Dick Moores Let's find out: from msvcrt import getch while True: ... key = getch() ... if key: print repr(key)+',', ... 'p', 'r', 'e', 's', 's', 'i', 'n', 'g', ' ', 'e', 'n', 't', 'e', 'r', ':', ' ', '\r', Gee, I pressed enter, and it returned '\r'. I wonder... import msvcrt while True: ... if msvcrt.kbhit(): ... key = msvcrt.getch() ... if key == '\r': ... print success! ... success! -- http://mail.python.org/mailman/listinfo/python-list
Re: and and or on every item in a list
On Oct 29, 5:57 pm, GHZ [EMAIL PROTECTED] wrote: Is this the best way to test every item in a list? No. The biggest problem is, obviously, you don't take advantage of builtins any() and all(), or write corresponding short-circuiting versions for python versions before 2.5. The second problem is you build an entire list that gets disposed of just as quickly. The third problem is you use lambda, which makes your call to map() time inefficient as well as space inefficient. Both of these problems can be fixed by using generator expressions. def alltrue(f,l): return reduce(bool.__and__,map(f,l)) def onetrue(f,l): return reduce(bool.__or__,map(f,l)) alltrue(lambda x:x1,[1,2,3]) False all(x1 for x in [1,2,3]) False alltrue(lambda x:x=1,[1,2,3]) True all(x=1 for x in [1,2,3]) True Thanks HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: simple question on dictionary usage
On Oct 27, 1:16 am, Frank Millman [EMAIL PROTECTED] wrote: On Oct 27, 8:02 am, Frank Millman [EMAIL PROTECTED] wrote: This should work - egt = dict([i for i in d.items() if i[0].startswith('E')]) Of course I meant record.items(), not d.items(). Sorry. Frank On reflection, although my solution is a bit shorter than some others, it may not be as efficient, as it retrieves the key and value for *every* entry in 'record' before testing whether the key begins with 'E'. That can be fixed by using record.iteritems() instead of record.items(). If the dictionary is large, this may be a consideration. Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic invoke
On Oct 19, 6:34 am, Nils [EMAIL PROTECTED] wrote: Use apply(): http://docs.python.org/lib/non-essential-built-in-funcs.html Did you actually read the title of the page you linked to (Non- essential Built-in Functions)? -- http://mail.python.org/mailman/listinfo/python-list
Re: calling a function from string
On Oct 22, 4:41 am, Francesco Guerrieri [EMAIL PROTECTED] wrote: On 10/22/07, james_027 [EMAIL PROTECTED] wrote: hi, i have a function that I could like to call, but to make it more dynamic I am constructing a string first that could equivalent to the name of the function I wish to call. how could I do that? the string could might include name of the module. for example a_string = 'datetime.' + 'today()' how could I call a_string as function? you could use getattr: function_name = 'time' # this is a string module_name = 'time' # this is a string, too my_function = getattr(module_name, function_name) # this is the function object, # equivalent to my_function = time.time Not quite. function_name = 'time' # this is a string module_name = 'time' # this is a string, too my_function = getattr(module_name, function_name) Traceback (most recent call last): File pyshell#3, line 1, in module my_function = getattr(module_name, function_name) AttributeError: 'str' object has no attribute 'time' It's actually equivalent to: time.time Traceback (most recent call last): File pyshell#0, line 1, in module time.time AttributeError: 'str' object has no attribute 'time' -- http://mail.python.org/mailman/listinfo/python-list
Re: calling a function from string
On Oct 22, 5:46 am, Jarek Zgoda [EMAIL PROTECTED] wrote: Do not use eval(). Not only it's deprecated, it's also unsafe. I don't think it's deprecated; it doesn't say so: http://docs.python.org/lib/built-in-funcs.html#l2h-25 -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob: Loops and the 'else' construct
On Oct 19, 3:12 am, Thorsten Kampe [EMAIL PROTECTED] wrote: So a for/else loop is exactly the same thing as a for loop with the else clause outside the loop (except for break)? Am I missing something here? It sounds to me like you just described two identical constructs. Guess that's why I never used that... Thorsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange behaviour with reversed()
On Oct 18, 3:52 am, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Thu, 18 Oct 2007 15:24:27 +1000, Ben Finney wrote: Steven D'Aprano [EMAIL PROTECTED] writes: and help(reversed) but neither gives any insight to what happens when you use reversed() on a sequence, then modify the sequence. I would think the answer is the same for any question about modifying sequences while iterating: undefined, therefore don't do that. That's not correct. You can modify sequences while iterating, and the results are often perfectly predictable (but watch out for off-by-one errors): Perhaps a better word to use here would have been undocumented, and therefore unsafe to use, as it might differ in different versions, or in different data-types. Dictionaries cannot continue iteration once they have changed size. -- http://mail.python.org/mailman/listinfo/python-list
Re: Last value of yield statement
On Oct 10, 5:19 am, Shriphani [EMAIL PROTECTED] wrote: Hello all, Let us say I have a function like this: def efficientFiller(file): Note that you are shadowing the built-in variable 'file' here. Better use 'filename', or something to that effect. worthless_list = [] pot_file = open(file,'r') pot_file_text = pot_file.readlines() for line in pot_file_text: if line.find(msgid) != -1: message_id = shlex.split(line)[1] if message_id in dictionary: number = pot_file_text.index(line) corresponding_crap = dictionary.get(message_id) final_string = 'msgstr' + + '' + corresponding_crap + '' + '\n' pot_file_text[number+1] = final_string yield pot_file_text efficient_filler = efficientFiller(libexo-0.3.pot) new_list = list(efficient_filler) print new_list I want to plainly get the last value the yield statement generates. How can I go about doing this please? Regards, Shriphani Palakodety efficient_filler = efficientFiller(libexo-0.3.pot) new_list = list(efficient_filler) last_value = new_list[-1] print last_value # OR efficient_filler = efficientFiller(libexo-0.3.pot) for last_value in efficient_filler: pass print last_value The latter assumes that the last value is the only value you want. -- http://mail.python.org/mailman/listinfo/python-list
Re: hi every one
On Oct 10, 7:19 pm, kasim [EMAIL PROTECTED] wrote: Dear __, __.dear() Traceback (most recent call last): File pyshell#0, line 1, in module __.dear() NameError: name '__' is not defined __ = self __.dear() Traceback (most recent call last): File pyshell#1, line 1, in module __.dear() TypeError: dear() takes at least 3 arguments (1 given) __.dear(sender = 'kasim', message = snipped_message) Traceback (most recent call last): File pyshell#1, line 1, in module __.dear('kasim') ValueError: Received spam __.dear(sender = 'ka$im', message = modified_message) -- http://mail.python.org/mailman/listinfo/python-list
Re: novice list
On Oct 5, 6:01 am, István [EMAIL PROTECTED] wrote: Could somebody suggest me a novice Python list, please? Thanks, Istvan You're there. -- http://mail.python.org/mailman/listinfo/python-list
Re: scope, modyfing outside object from inside the method
On Sep 24, 2:13 am, Peter Otten [EMAIL PROTECTED] wrote: @property def value(self): return self._resultset[self._row][self._col] I remember a thread where someone created a version of property that worked like this, but it's not in the standard python release, unless it is in python 3000. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sets in Python
On Sep 19, 10:58 pm, Bryan Olson [EMAIL PROTECTED] wrote: Bad news: Python 3000 has no immutable type for byte-strings. The new bytes type cannot serve for dict keys or set members. Many things one would want to hash are unhashable -- for example, the results of the hash functions in hashlib. Are you serious -- http://mail.python.org/mailman/listinfo/python-list
Re: Sets in Python
On Sep 18, 7:39 pm, sapsi [EMAIL PROTECTED] wrote: Hello, I recently tried using the set function in Python and was surprised to find that a=[ 1, 2,3, [1,2] ] doesn't work with 'set', throwing TyperError (unhashable exception). I found out that this is because lists can't be hashed. So,this implies 'a' cannot be a set in python which i think is quite unfortunate, after all 'a' does look like a mathematical set. It is not the variable *a* itself that's a problem when constructing a set (ie. set(a)); it is the content. set() goes through each of the items and adds that item to the set. 1, 2, and 3 are valid because they can be hashed. The next item in the list, however, is [1,2], and cannot be hashed because it is a mutable list. The solution is as Raymond Hettinger said: a = set([1, 2, 3, frozenset([1, 2])]) My question is, 1) Why can't lists be hashed? They're mutable. and 2) This is not related, but is there i neat way (without pop and list comprehension) to convert a set into a list? I say neat because i'm guessing using list comprehension might turn out be slow and there might be other methods which are faster. list(a_set) Thank you for your time You're welcome. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python statements not forcing whitespace is messy?
On Sep 15, 5:11 pm, James Stroud [EMAIL PROTECTED] wrote: Steve Holden wrote: I don't know why you have a bug up your ass about it, as the Americans say. I think most Americans say wild hare up your ass. We do not, in fact, say wild hair up your ass. Many of us can testify that a hair up one's ass would be nothing terribly unusual and would go completely unnoticed under most circumstances. Also, some Americans erroneously say hair's breath, and others think they mean hare's breath (which might be tiny, but diffuses quickly to theoretically infinite volume). In reality, however, they mean hair's breadth--which is quite small indeed! For instance, a hair's breadth is far smaller than a hare's breath (even at the exact moment of respiration). James Funny... I have never heard any of those expressions. I guess I need to get out more. -- http://mail.python.org/mailman/listinfo/python-list
Re: Try this
On Sep 16, 3:46 am, GeorgeRXZ [EMAIL PROTECTED] wrote: If you have Microsoft windows 98/2000/ME/XP/2003 Operating System on your PC. Then Open the Notepad and type the following sentence, and save the file and close the notepad. Now reopen the file and you will find out that, Notepad is not able to save the following text line. Well you are speed This occurs not only with above sentence but any sentence that has 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) When type following sentence and save file then same thing occurs. This is not Maria GEOrgE Develop a website that will help people, Avoid spamming, provide quality contents on your website http://zsoftwares.googlepages.com/index.htm Didntworkiwantmymoneyback. -- http://mail.python.org/mailman/listinfo/python-list
Re: where are the .pyc files?
On Sep 16, 12:28 pm, Summercool [EMAIL PROTECTED] wrote: so i have always heard of the .pyc files but for some reason i don't see them on the Windows platform... when i have a program called try.py and after running it for ages, i still don't have a try.pyc file in my folder even if i turn the show hidden file to on. Try import try. Ummm No, you can't. Rename the file to exodomuzos.py, then import exodomuzos. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python with
On Sep 16, 3:07 pm, Ivan Voras [EMAIL PROTECTED] wrote: Hi, I'm looking for a construct that's similar to (Turbo) Pascal's with statement. I read about the Python's new with statement, but I was dissapointed to learn that it does something different (I still don't see how it's better than try..except..finally, but that's not my question). Is there something similar to what I want that's Pythonic enough? (If you're not familiar with Pascal, here's how it works: with some.big.structure.or.nested.objects.element do begin member1 := something; member2 := something; end; which exactly translates to this equivalent: some.big.structure.or.nested.objects.element.member1 := something; some.big.structure.or.nested.objects.element.member2 := something; i.e. it's a wrist-saver. I think a similar feature exists in C99, for structs. I know it can be almost always done by using a temporary variable: tmp = some.big.structure.or.nested.objects.element tmp.member1 = something tmp.member2 = something but this looks ugly to me.) signature.asc 1KDownload import this # Note item #5 -- http://mail.python.org/mailman/listinfo/python-list
Re: unexpected behavior: did i create a pointer?
On Sep 7, 3:07 am, gu [EMAIL PROTECTED] wrote: hi to all! Hi! after two days debugging my code, i've come to the point that the problem was caused by an unexpected behaviour of python. or by lack of some information about the program, of course! i've stripped down the code to reproduce the problem: code a = {} for x in range(10): for y in range(10): a[x,y] = 0 copyOfA = a def functionA(x,y): print a[x,y], copyOfA[x,y] = * print a[x,y],copyOfA[x,y] for x in range(10): for y in range(10): functionA(x,y) /code now, in the second for cycle and in functionA() i only 'touch' copyOfA (altering it). as i don't touch the variable a, i expect it not to be affected by any change, but copyOfA acts like a pointer to a and altering copyOfA's values result in altering the values of a, so the result that i expect is: 0 0 * 0 0 * 0 0 * 0 0 * [..] but i get: 0 * * 0 * * 0 * * 0 * * [..] what's going on? thanks in advance. Welcome to Python! You might want to look at the documentation: http://docs.python.org/ And the tutorials: http://docs.python.org/tut/tut.html Leaping into python from another language without looking at the above documentation is not wise, since python has both a very different structure and a somewhat different philosophy from other languages. -- http://mail.python.org/mailman/listinfo/python-list
Re: an eval()-like exec()
On Aug 27, 6:06 pm, Matt McCredie [EMAIL PROTECTED] wrote: A python interactive interpreter works by having the user type in some code, compiling and running that code, then printing the results. For printing, the results are turned into strings. I would like make an interpreter which does this, without the last part: i.e. where the results are returned as objects, instead of as strings. I.e. have I would like to see something that behaves like this: ip = MyInterpreter() # this started a new interpreter ip.run(import math) is None True ip.run(math.pi) is math.pi True Neither exec() or eval() is usable for this, as far as I see, because eval can't handle arbitrary python code (eval(import math) ), and exec() doesn't return the results. Subclassing an code.InteractiveInterpreter or code.InteractiveConsole seems like a usable idea, but I couldn't find out what to do to get the results before they are turned into strings. Using compile() and then eval() didn't seem usable either. Any ideas? Well, my first thought is that exec and eval serve two different purposes, and you should just have both of them and use the appropriate one based on the situation. However, I think it is possible to enable the behavior you want: [code] def myeval(statement, globals_=None, locals_=None): try: return eval(statement, globals_, locals_) except SyntaxError: if locals_ is None: import inspect locals_ = inspect.currentframe().f_back.f_locals exec statement in globals_, locals_ [/code] It seems to work for me. Matt Unless it's something like: raise_(SyntaxError) where raise_ is a function equivalent to the corresponding statement. -- http://mail.python.org/mailman/listinfo/python-list
Re: Let's Unite Against Jews and Mongrels!
On Aug 27, 2:13 am, Nenad Milicevic - The Aryan Serb [EMAIL PROTECTED] wrote: Let's break the chains of Jewish and black domination! A) Why? B) What chains? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to parse this line of code manually
On Aug 28, 2:59 am, A.T.Hofkamp [EMAIL PROTECTED] wrote: On 2007-08-28, Davy [EMAIL PROTECTED] wrote: On Aug 28, 11:00 am, Davy [EMAIL PROTECTED] wrote: Hi all, It is well known that Python is appreciated for its merit of concise. However, I found the over concise code is too hard to understand for me. Consider, for instance, def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) Shall I understand the code in set() as for e2 in edits1(e1) { if e2 in NWORDS { for e1 in edits1(word) { e2 } } } [SNIP] Hi all, I figured it myself. It is left to righ parse, right? So the above one is like for e1 in edits1(word) { for e2 in edits1(e1) { if e2 in NWORDS { push e2 to set } } } This is correct, although I am not sure what language you are using here, it looks like a strange mix of Python and C to me. Any suggestions are welcome! The idea is known as List comprehension (for lists, obviously), and comes from functional programming, Bird Wadler used it in their book. The notation is very close to mathematics: { e2 | e1: edits(word), e2: edits(e1) in NWORDS } or in LaTeX: $\{ e_2 | \forall e_1: \mathrm{edits}(\mathrm{words}), \forall e_2: \mathrm{edits}(e_1) \in \mathrm{NWORDS} \}$ :-) (which in words is something like: collect values e2, where e1 comes from 'edits(word)', e2 comes from 'edits(e1)', and e2 in NWORDS) For more examples: http://docs.python.org/tut/node7.html#SECTION00714 A 'list comprehension' with parentheses instead of square-brackets creates a generator instead of a list, which can be more memory- efficient and allows for lazy evaluation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Check for dict key existence, and modify it in one step.
On Aug 28, 1:13 pm, rodrigo [EMAIL PROTECTED] wrote: evan, yes, it does help. Works like it should: class CountingDictionary(dict): def increment(self, key, delta=1): self[key] = self.get(key, 0) + delta d = CountingDictionary() d.increment('cat') d.increment('dog',72) print d {'dog': 72, 'cat': 1} Thanks! You responded to the answer that made the least use of already existing recourses in python. Just letting you know. -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing keys in dict
On Aug 25, 7:41 am, Lawrence D'Oliveiro [EMAIL PROTECTED] central.gen.new_zealand wrote: In message [EMAIL PROTECTED], james_027 wrote: is there any difference between .. for key in a_dict: from for key in a_dict.keys(): I'm assuming the former is equivalent to for key in a_dict.iterkeys() : Never assume. A better approach would be to experiment: a_dict = {'name':'apple', 'color':'red', 'texture':'smooth', 'shape':'sphere'} for i in a_dict: print i color shape name texture for i in a_dict.iterkeys(): print i color shape name texture for i in a_dict.itervalues(): print i red sphere apple smooth for i in a_dict.iteritems(): print i ('color', 'red') ('shape', 'sphere') ('name', 'apple') ('texture', 'smooth') -- http://mail.python.org/mailman/listinfo/python-list
Re: How to optimise this code?
On Aug 21, 11:20 am, J. Cliff Dyer [EMAIL PROTECTED] wrote: I suspect lambda might be your friend here too for making the code less verbose, though I never really got the hang of lambdas, even though my first programming experience was a scheme class way back when Ah well. That's because it's not the same thing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Where we need to use Python ?
On Aug 20, 3:02 am, [EMAIL PROTECTED] wrote: Hi Iam new to Python I know Perl, JScript,C,C++,Java But i want to know where excatly this python come in to picture And Is it a interpreted language or a programming language It comes in which category I very keen to know this please tell Regards Ganesh P http://www.python.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Where we need to use Python ?
On Aug 20, 10:13 am, Wildemar Wildenburger [EMAIL PROTECTED] wrote: Michael Bentley wrote: On Aug 20, 2007, at 1:02 AM, [EMAIL PROTECTED] wrote: And Is it a interpreted language or a programming language It comes in which category I very keen to know this please tell [ open on suburban kitchen, Wife and Husband arguing ] Wife: New Shimmer is a floor wax! Husband: No, new Shimmer is a dessert topping! [snip 50s-style add] Spokesman: New Shimmer, for the greatest shine you ever tasted! Not the most to-the-point reply, but a very amusing one :). Ack! Worst analogy ever! But yes, amusing nonetheless. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guitar Reviews
On Aug 15, 7:32 am, [EMAIL PROTECTED] wrote: snip op.mother.speak() Congratulations! You've just given your email address to millions of people across Usenet! What do you have to say for yourself? op.respond() Awww, jeez, why'd y'all have to bring my mother into this? op.mother.speak() You're grounded for a week! op.respond() But- Ah! No buts! But- To your room, mister! Ok. # wha-? -- http://mail.python.org/mailman/listinfo/python-list
Re: A dumb question about a class
On Aug 12, 5:09 pm, Steven Bethard [EMAIL PROTECTED] wrote: def iter_primes(): # an iterator of all numbers between 2 and +infinity numbers = itertools.count(2) # generate primes forever while True: # get the first number from the iterator (always a prime) prime = numbers.next() yield prime # remove all numbers from the (infinite) iterator that are # divisible by the prime we just generated numbers = itertools.ifilter(prime.__rmod__, numbers) This is kind of OT (from the thread), but in this iter_primes function, numbers is becoming an ifilter of an ifilter of an ifilter of an ifilter of an ifilter of an ifilter of... Is that really at all efficient for larger numbers (millions or billions, or even bigger)? -- http://mail.python.org/mailman/listinfo/python-list
Re: Complexity of methods etc
On Aug 12, 7:04 pm, Nathan Harmston [EMAIL PROTECTED] wrote: Hi, I was wondering if anyone knew of any resources, where I might be able to find information about the complexity of certain python functions or little tips on how to reduce complexity. I mean like the .join(), kind of thing? I want to see if there are any improvements I can add to my coding in order to reduce time/space usage/ It's really difficult to understand what you mean. If you're looking for a reference on the functions that are available in the library, you have a long journey ahead of you at http://docs.python.org/ . -- http://mail.python.org/mailman/listinfo/python-list
Re: A dumb question about a class
On Aug 12, 7:35 pm, Dustan [EMAIL PROTECTED] wrote: On Aug 12, 5:09 pm, Steven Bethard [EMAIL PROTECTED] wrote: def iter_primes(): # an iterator of all numbers between 2 and +infinity numbers = itertools.count(2) # generate primes forever while True: # get the first number from the iterator (always a prime) prime = numbers.next() yield prime # remove all numbers from the (infinite) iterator that are # divisible by the prime we just generated numbers = itertools.ifilter(prime.__rmod__, numbers) This is kind of OT (from the thread), but in this iter_primes function, numbers is becoming an ifilter of an ifilter of an ifilter of an ifilter of an ifilter of an ifilter of... Is that really at all efficient for larger numbers (millions or billions, or even bigger)? To word my question better: How does this algorithm compare and contrast to maintaining a dictionary or set and iterating through those structures to find out if a number is divisible? All of those algorithms I've described are O(n^2), if I'm not mistaken, but as far as memory-efficiency and the likes, how do they compare/contrast? -- http://mail.python.org/mailman/listinfo/python-list
Re: Deleting objects on the fly
On Aug 10, 1:49 pm, Terry Reedy [EMAIL PROTECTED] wrote: Campbell Barton [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]| Michele Simionato wrote: | Probably not, 'del x' just decrements the reference count, Or ashttp://docs.python.org/ref/del.html puts it, Deletion of a name removes the binding of that name from the local or global namespace, | del x will remove x from memory if nothing else is refering to it, This is implementation dependent: true for CPython, not for Jython, ??? for IronPython. Wait a second; do you mean to say that in Jython, del x will never remove x from memory? How do you free up RAM? -- http://mail.python.org/mailman/listinfo/python-list
Re: Metaclass v.s. Property function.
On Aug 11, 7:33 am, Jens Thiede [EMAIL PROTECTED] wrote: I don't like the property function, usable in the new-style classes, because having to remember to manage a list of foo = property(...) assignments just plain sucks, so I wrote a metaclass that does things a little differently. Please have a look and tell me whether this is useful or impractical. The metaclass is here:http://pastebin.com/m5b06b571 and some simple testcode is here:http://pastebin.com/m382f2ae9. Notice the first line though. Are you overusing property, by any chance? In your example, bar seems to be an unneeded property; it could just be a normal attribute. -- http://mail.python.org/mailman/listinfo/python-list
Re: python 2.5 bug
On Aug 11, 12:32 am, Thorsten Kampe [EMAIL PROTECTED] wrote: 4. don't do something you don't fully understand (in this case installing Python 2.5 and uninstalling Python 2.4) If we were all limited by that rule, none of us would never have used a computer in the first place. Operating a computer is a learning experience, no matter what level you're at (although admittedly the lessons learned can sometimes be hurtful). -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about properties.
On Aug 10, 5:31 am, [EMAIL PROTECTED] wrote: On Aug 10, 12:21 pm, king kikapu [EMAIL PROTECTED] wrote: Hi, i read in a book the following code snippet that is dealing with properties: class ProtectAndHideX(object): def __init__(self, x): assert isinstance(x, int), 'x must be an integer!' self.__x = ~x def get_x(self): return ~self.__x x = property(get_x) Can anyone please help me understand what the symbol ~ does here ?? Thanks for any help! help(2) | __invert__(...) | x.__invert__() == ~x hth. Duikboot http://docs.python.org/ref/unary.html The unary ~ (invert) operator yields the bit-wise inversion of its plain or long integer argument. The bit-wise inversion of x is defined as -(x+1). It only applies to integral numbers. -- http://mail.python.org/mailman/listinfo/python-list
Re: programmatically define a new variable on the fly
On Aug 9, 5:11 pm, Lee Sander [EMAIL PROTECTED] wrote: Hi, I would like to define a new variable which is not predefined by me. For example, I want to create an array called X%s where %s is to be determined based on the data I am processing. So, for example, if I the file I'm reading has g 99 on the first line, I want to create a new variable called Xg whose length is 99. I tried eval(Xg=[0]*99) but that did not work. eval only evaluates expressions. To go about the problem that way, you would use exec, not eval. Of course, use of exec generally means you're going about the problem the wrong way; it looks to me like a better way to do what you're doing is to create a dictionary to hold your values. So, given the variables data (the dictionary), name (in your example, 'g') and *size* (in your example, 99), you can add it data as shown: data[name] = [0] data[name] *= size Note that by splitting the '[0]*size' code into two lines as shown above, you don't create an intermediate list object that gets thrown away right after creation. -- http://mail.python.org/mailman/listinfo/python-list
Re: programmatically define a new variable on the fly
On Aug 9, 5:30 pm, Dustan [EMAIL PROTECTED] wrote: given the variables data (the dictionary), name (in your example, 'g') and *size* (in your example, 99), you can add it data as shown: erm... make that: given the variables data (the dictionary), name (in your example, 'g') and size (in your example, 99), you can add it to data as shown: -- http://mail.python.org/mailman/listinfo/python-list
Re: simple string backspace question
On Jul 31, 7:17 am, John Machin [EMAIL PROTECTED] wrote: On Jul 31, 8:01 pm, [EMAIL PROTECTED] wrote: On 31 srp, 11:44, [EMAIL PROTECTED] wrote: Hello, I have one simple string, backspace character question.Here is my example: text=Hello\bworld print text HelloBSworld Should this character \b (backspace) in this text return this: Helloworld? Regards, Vedran Hi, If you mean on operating system then unfortunately Windows XP. Point (1) Works on Windows XP for me: C:\junkver Microsoft Windows XP [Version 5.1.2600] C:\junk\python25\python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. text = Hello\bworld print text Hellworld or, for mild amusement: import sys, time for x in xrange(100): ... sys.stdout.write(|/-\\[x 3] + \b) ... time.sleep(0.1) ... Now try it on IDLE. Point (2): Backspace??? YAGNI --- backspace hasn't been much use for anything (except when typing text) since the days when in order to get a bold letter (say X) on a character impact printer, one would transmit X\bX\bX ... -- http://mail.python.org/mailman/listinfo/python-list
Re: a_list.count(a_callable) ?
On Jun 16, 12:04 pm, Wildemar Wildenburger [EMAIL PROTECTED] wrote: class SmartCountingList(list): def count(self, item, func=lambda x: x): return len([item for item in self if func(item) is True]) A less bug-prone and (I would think) speedier example, although still untested: class SmartCountingList(list): def count(self, item, func=lambda x: x): return sum(1 for i in self if func(item)==item) Then, you would call it as follows: a_list.count(True, a_function) -- http://mail.python.org/mailman/listinfo/python-list
Re: a_list.count(a_callable) ?
On Jun 16, 3:37 pm, Dustan [EMAIL PROTECTED] wrote: class SmartCountingList(list): def count(self, item, func=lambda x: x): return sum(1 for i in self if func(item)==item) Then, you would call it as follows: a_list.count(True, a_function) I need to learn to think things through before hitting the send button (or test my examples); none of the mistakes I've made on this thread have been from ignorance. If a_function returns a true value other than True or the number 1 (which are technically the same), it is not 'equal' to True. Either the function would return True, or the count method could be written differently: class SmartCountingList(list): def count(self, item, is_func=False): if is_func: # item being a function: return sum(1 for i in self if item(i)) else: return super(SmartCountingList, self).count(item) And just to prove that it works: s = SmartCountingList((1,2,3)) s [1, 2, 3] s.count(1) 1 s.count(2) 1 s.count(3) 1 s.count(4) 0 s.count(lambda n: n3, True) 2 -- http://mail.python.org/mailman/listinfo/python-list
Re: a_list.count(a_callable) ?
On Jun 15, 9:15 am, Ping [EMAIL PROTECTED] wrote: sum(1 for i in a_list if a_callable(i)) -- Carsten Haesehttp://informixdb.sourceforge.net This works nicely but not very intuitive or readable to me. First of all, the generator expression makes sense only to trained eyes. Secondly, using sum(1 ...) to mean count() isn't very intuitive either. Then wrap it in a function: def count(a_list, a_function): return sum(1 for i in a_list if a_function(i)) And call the function. You can also give it a different name (although I can't think of a concise name that would express it any better). I would still prefer an expression like a_list.count(a_callable), which is short, clean, and easy to understand. :) However, it does produce ambiguities if a_list is a list of callables. Should the count() method match values or check return values of a_callable? There are several possible designs but I'm not sure which is better. Indeed, the ambiguity in that situation would be a reason *not* to introduce such behavior, especially since it would break older programs that don't recognize that behavior. Just stick with writing the function, as shown above. -- http://mail.python.org/mailman/listinfo/python-list
Re: a_list.count(a_callable) ?
On Jun 15, 12:52 pm, Ping [EMAIL PROTECTED] wrote: On 6 15 , 11 17 , Dustan [EMAIL PROTECTED] wrote: On Jun 15, 9:15 am, Ping [EMAIL PROTECTED] wrote: sum(1 for i in a_list if a_callable(i)) -- Carsten Haesehttp://informixdb.sourceforge.net This works nicely but not very intuitive or readable to me. First of all, the generator expression makes sense only to trained eyes. Secondly, using sum(1 ...) to mean count() isn't very intuitive either. Then wrap it in a function: def count(a_list, a_function): return sum(1 for i in a_list if a_function(i)) And call the function. You can also give it a different name (although I can't think of a concise name that would express it any better). Hmm... This sounds like the best idea so far. It is efficient both in memory and time while exposes an easy-to-understand name. I would name the function count_items though. n = count_items(a_list, lambda x: x 3) # very readable :) Although that particular example would be more efficient inlined, because of the additional time spent creating the lambda function in your count_items call. sum(1 for i in a_list if i 3) -- http://mail.python.org/mailman/listinfo/python-list
Re: Should: for k,v in **dictionary_instance work?
On Jun 15, 2:17 pm, [EMAIL PROTECTED] wrote: Does it make sense to provide this syntax for iterating key/value pairs from a dictionary? for k,v in **dict(): print k,v why is this not the same as: for k,v in dict().items(): print k,v for that matter, why the heck doesn't a dictionary default to returning a tuple k,v pair from its iterator? Pax, Keith Ps, I'm sure someone has thought of these things before, probably been answered before, but I'm sure I didn't find reference to them when i searched. The answer is simply for history and for clarity. -- http://mail.python.org/mailman/listinfo/python-list
Re: a_list.count(a_callable) ?
On Jun 14, 2:53 pm, Ping [EMAIL PROTECTED] wrote: Hi, I'm wondering if it is useful to extend the count() method of a list to accept a callable object? What it does should be quite intuitive: count the number of items that the callable returns True or anything logically equivalent (non-empty sequence, non-zero number, etc). This would return the same result as len(filter(a_callable, a_list)), map and filter are basically obsolete after the introduction of list comprehensions; your expression is equivalent to: len([i for i in a_list if a_callable(i)]) Which can then be converted into a generator expression (round brackets instead of square brackets) to avoid the intermediate list: len((i for i in a_list if a_callable(i))) Or syntactically equivalent (avoiding lispy brackets): len(i for i in a_list if a_callable(i)) but without constructing an intermediate list which is thrown away after len() is done. This would also be equivalent to n = 0 for i in a_list: if a_callable(i): n += 1 but with much shorter and easier-to-read code. It would also run faster. This is my first post and please bear with me if I'm not posting it in the right way. Regards, Ping -- http://mail.python.org/mailman/listinfo/python-list
Re: a_list.count(a_callable) ?
On Jun 14, 3:37 pm, Dustan [EMAIL PROTECTED] wrote: map and filter are basically obsolete after the introduction of list comprehensions It is probably worth noting that list comprehensions do not require that you write a new function; they take any expression where appropriate. For more information on list comprehensions, see: http://docs.python.org/tut/node7.html#SECTION00714 Generator expressions are the same, except syntactically they have round brackets instead of square, and they return a generator instead of a list, which allows for lazy evaluation. -- http://mail.python.org/mailman/listinfo/python-list
Re: a_list.count(a_callable) ?
On Jun 14, 3:37 pm, Dustan [EMAIL PROTECTED] wrote: Which can then be converted into a generator expression (round brackets instead of square brackets) to avoid the intermediate list: len((i for i in a_list if a_callable(i))) Sorry for the excess of posts everybody. I just realized that the generator expression would not work. I'm not sure how else could be implemented efficiently and without using up memory besides by accumulating the count as your earlier example shows. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a tuple quickly with list comprehension?
On Jun 13, 5:37 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: In [EMAIL PROTECTED], Diez B. Roggisch wrote: No need to create the intermediate list, a generator expression works just fine: a = tuple(i for i in range(10)) But `range()` creates the intermediate list anyway. ;-) I imagine that's special case. -- http://mail.python.org/mailman/listinfo/python-list
Re: get a list from a string
On Jun 7, 6:06 am, simon kagwe [EMAIL PROTECTED] wrote: exec(distances = [[1,1,1,1],[2,2,2,2]]) To be clear, exec is *not* a function; it's a statement. That means it can't be used in lambda functions, for example. Wow! So simple! but dodgy, as it'll execute any python code. Thanks a lot. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: running a random function
On Jun 7, 10:56 am, David Bear [EMAIL PROTECTED] wrote: I would like to write some code that would randomly select a function from a list of functions and call it. I was looking in the globals names space and randomly selecting items that were of type function.. Careful!!! You don't want to destroy your computer by accident. but I didn't see a way of actually running the function. What do you mean? foo is a function; here's how you run it: foo() Any pointers? Given a list of functions, it would simply be, given the list of functions bar (untested): import random random.choice(bar)() -- http://mail.python.org/mailman/listinfo/python-list
Re: running a random function
On Jun 7, 1:30 pm, Neil Cerutti [EMAIL PROTECTED] wrote: On 2007-06-07, Stebanoid [EMAIL PROTECTED] wrote: if you have a list of functions you can try this: import random import math m[int(math.floor(len(m)*random.random()))]() # seems like Lisp Or rather m[random.randint(0, len(m))]() Or rather random.choice(m)() # seems like Python -- Neil Cerutti Caution: Cape does not enable user to fly. --Kenner's Batman costume -- http://mail.python.org/mailman/listinfo/python-list
Re: function in a function accessing vars
On Jun 6, 6:40 am, Jorgen Bodde [EMAIL PROTECTED] wrote: Hi Diez, Thanks, I thought it worked similar to C++ where a higher compound could access a lower section. It can 'access a lower section'; what it can't do is *change* that 'lower section'; in your example case with an int, this matters because ints are immutable. Lists, on the other hand, are mutable. You can *access* the methods of the list that mutate it. You're always working with the same list, but it has different contents when you mutate it. But as it is not straight forward, I think it is better to embed the functionality inside a class, and make it a member variable .. now why didn't I think of that ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Determinant of Large Matrix
On Jun 6, 6:47 am, Tommy Nordgren [EMAIL PROTECTED] wrote: On 6 jun 2007, at 13.10, James Stroud wrote: Hello All, I'm using numpy to calculate determinants of matrices that look like this (13x13): [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 1. 4. 1. 9. 4. 4. 1. 1. 4. 9. 4. 9.] [ 1. 1. 0. 1. 4. 4. 9. 9. 4. 4. 1. 4. 1. 4.] [ 1. 4. 1. 0. 9. 1. 4. 4. 9. 1. 4. 1. 4. 1.] [ 1. 1. 4. 9. 0. 4. 4. 4. 1. 4. 1. 9. 4. 9.] [ 1. 9. 4. 1. 4. 0. 4. 4. 9. 4. 1. 1. 4. 1.] [ 1. 4. 9. 4. 4. 4. 0. 1. 1. 1. 9. 1. 9. 4.] [ 1. 4. 9. 4. 4. 4. 1. 0. 4. 1. 9. 4. 4. 1.] [ 1. 1. 4. 9. 1. 9. 1. 4. 0. 4. 4. 4. 4. 9.] [ 1. 1. 4. 1. 4. 4. 1. 1. 4. 0. 9. 4. 9. 4.] [ 1. 4. 1. 4. 1. 1. 9. 9. 4. 9. 0. 4. 1. 4.] [ 1. 9. 4. 1. 9. 1. 1. 4. 4. 4. 4. 0. 4. 1.] [ 1. 4. 1. 4. 4. 4. 9. 4. 4. 9. 1. 4. 0. 1.] [ 1. 9. 4. 1. 9. 1. 4. 1. 9. 4. 4. 1. 1. 0.]] For this matrix, I'm getting this with numpy: 2774532095.971 But I have a feeling I'm exceeding the capacity of floats here. Does anyone have an idea for how to treat this? Is it absurd to think I could get a determinant of this matrix? Is there a python package that could help me? Many thanks for any answers. James -- http://mail.python.org/mailman/listinfo/python-list Are you sure NumPy return float results. As far as I know, it returns doubles I don't know about NumPy, but in general, a python float is a double: http://docs.python.org/lib/typesnumeric.html Floating point numbers are implemented using double in C. All bets on their precision are off unless you happen to know the machine you are working with. (about 16 digits) -- Home is not where you are born, but where your heart finds peace - Tommy Nordgren, The dying old crone [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Pop Quiz
On Jun 1, 9:33 pm, [EMAIL PROTECTED] wrote: 1. Do you like Python? yes 2. Do you think Python is good? yes 3. Do you think Python is real good? yes 4. What is your favorite version of Python? The most recent one. 5. Because of Python, do you think it will be easier to take over the world? I don't know; I've never considered taking over the world. If so, when? If not, when? 7. How many Z80 assembly language programmers does it take to equal one Python guru? I don't know about Z80, but the word 'assembly' makes me think: .4 Essay: C++ is better than C, agree or disagree? (four word maximum) I can not say. Bonus: A rabbi walks into a bar while nursing a baby goat. He is closely followed by a priest, and a Perl hacker. Explain. I'm glad this is just bonus. What do I win? -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
On May 30, 5:37 pm, Warren Stringer [EMAIL PROTECTED] wrote: Hey many thanks for the replies! Ah, so is seems that c[:][:][:][:][:][:][:][:][:][:][:][0]() also work ... Ah well, can't have everything. Guess I was inspired by the alphabetically adjacent message Call for Ruby Champion. Would have been nice for it work - a more elegant iterator would be hard to come by. A PEP, perhaps? Maybe not; am still a bit new - am probably missing something obvious why this isn't an easy fix. Pretty cool that I can override the list class. Cheers, Do a search on python is not java (words to live by). You can also plug in another language you know (like Ruby), but you won't get as many results. -- http://mail.python.org/mailman/listinfo/python-list
Re: NEWBIE: Extending a For Statement.
On May 21, 7:22 am, Jean-Paul Calderone [EMAIL PROTECTED] wrote: On 21 May 2007 05:10:46 -0700, mosscliffe [EMAIL PROTECTED] wrote: I keep seeing examples of statements where it seems conditionals are appended to a for statement, but I do not understand them. I would like to use one in the following scenario. I have a dictionary of mydict = { 1: 500, 2:700, 3: 800, 60: 456, 62: 543, 58: 6789} for key in mydict: if key in xrange (60,69) or key == 3: print key,mydict[key] I would like to have the 'if' statement as part of the 'for' statement. I realise it is purely cosmetic, but it would help me understand python syntax a little better. Only list comprehensions and generator expressions support this extension to the loop syntax. [key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] ack! (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] File stdin, line 1 (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] ^ SyntaxError: invalid syntax Perhaps you meant that second one to be: (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3) For the statement form of 'for', there is no syntactic way to combine it with 'if' into a single statement. But there is a dumb hack to get it to happen, but I'm not going to it here, because Guido never meant for generator expressions to be used that way. To the OP: I would suggest you just live what might seem like excess indentation; it's good for your eyes. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: NEWBIE: Extending a For Statement.
On May 21, 7:22 am, Jean-Paul Calderone [EMAIL PROTECTED] wrote: On 21 May 2007 05:10:46 -0700, mosscliffe [EMAIL PROTECTED] wrote: I keep seeing examples of statements where it seems conditionals are appended to a for statement, but I do not understand them. I would like to use one in the following scenario. I have a dictionary of mydict = { 1: 500, 2:700, 3: 800, 60: 456, 62: 543, 58: 6789} for key in mydict: if key in xrange (60,69) or key == 3: print key,mydict[key] I would like to have the 'if' statement as part of the 'for' statement. I realise it is purely cosmetic, but it would help me understand python syntax a little better. Only list comprehensions and generator expressions support this extension to the loop syntax. [key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] ack! (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] File stdin, line 1 (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] ^ SyntaxError: invalid syntax Perhaps you meant that second one to be: (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3) For the statement form of 'for', there is no syntactic way to combine it with 'if' into a single statement. There is a dumb hack to get it to happen, but I'm not going to it here, because Guido never meant for generator expressions to be used that way. To the OP: I would suggest you just live what might seem like excess indentation; it's good for your eyes. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: NEWBIE: Extending a For Statement.
On May 21, 9:21 am, mosscliffe [EMAIL PROTECTED] wrote: On 21 May, 15:02, [EMAIL PROTECTED] wrote: mosscliffe: if key in xrange (60,69) or key == 3: I keep seeing again and again code like this, mostly from people not much expert of Python, but the PEP 260 shows the fast in was removed, so it's O(n). Maybe removing the fast __contains__ was bad for necomers (or just the casual Python users, that I belive is really large). Bye, bearophile Being a non-expert in python in fact just a beginner / casual user, can you expand on how 0(n) relates to if key in xrange (60,69) or key == 3: the key in xrange(60,69) part: all that does is iterate through xrange(60, 69) and when a match is met, it returns true. If it ends up iterating through the whole list without finding a match, it returns false. My mind tends to go blank at the mention of __xxx__. The above is the default behavior of the 'in' operator. That default behavior can be overridden by a class that has the __contains__ method. So XXX in YYY expands roughly to the following (as I understand it; I haven't actually looked it up): if hasattr(YYY, __contains__): return YYY.__contains__(XXX) else: for i in YYY: if XXX == YYY: return True return False R -- http://mail.python.org/mailman/listinfo/python-list
Re: converting strings to most their efficient types '1' -- 1, 'A' --- 'A', '1.2'--- 1.2
On May 18, 6:07 pm, py_genetic [EMAIL PROTECTED] wrote: Hello, I'm importing large text files of data using csv. I would like to add some more auto sensing abilities. I'm considing sampling the data file and doing some fuzzy logic scoring on the attributes (colls in a data base/ csv file, eg. height weight income etc.) to determine the most efficient 'type' to convert the attribute coll into for further processing and efficient storage... Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello there' '100,000,000,000'], [next row...] ] Aside from a missing attribute designator, we can assume that the same type of data continues through a coll. For example, a string, int8, int16, float etc. 1. What is the most efficient way in python to test weather a string can be converted into a given numeric type, or left alone if its really a string like 'A' or 'hello'? Speed is key? Any thoughts? given the string s: try: integerValue = int(s) except ValueError, e: try: floatValue = float(s) except ValueError: pass else: s = floatValue else: s = integerValue I believe it will automatically identify base 8 and base 16 integers (but not base 8/16 floats). 2. Is there anything out there already which deals with this issue? Thanks, Conor -- http://mail.python.org/mailman/listinfo/python-list
Re: try
On May 16, 4:22 pm, Robert Kern [EMAIL PROTECTED] wrote: HMS Surprise wrote: I read in the ref man that try-except-finally did not work in earlier versions, I am using jython 2.2. Does this imply that try-except without finally does not work either? I get a syntax error on the else below. Some of the functions embedded in the try section try to convert strings to ints, etc and may fail on bad data, thus try seemed like a good start for a workaround. Thanks, jh #~~ def restoreDevice(self, deviceId, closeTime = time()): self.logon() try: lst = self.getLastUpdatedDevice(deviceId) lastUpdated = lst[0] incidentId = lst[1] print 'L', lastUpdated, 'I', incidentId self.restore(incidentId, lastUpdated) except: else: print couldn't find incident The except: block still needs something in it, even if it is just pass. For sake of demonstration: def restoreDevice(self, deviceId, closeTime = time()): self.logon() try: lst = self.getLastUpdatedDevice(deviceId) lastUpdated = lst[0] incidentId = lst[1] print 'L', lastUpdated, 'I', incidentId self.restore(incidentId, lastUpdated) except: pass else: print couldn't find incident -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list