question on log as an instance method
Hi ! Here is Python 3.2.3, MacOSX-Lion Question : I may consider + as an hidden instance method , as 1+2 is equivalent to (1).__add__(2) ? I also consider __abs__ as an instance method : >>> (-2).__abs__() 2 Question 1 : could the parser cope with the mandatory space in 1 .__add__(2) ? Question 2 : After importing math, why can't I consider log as an instance method, after all ? >>> (4).__log__() AttributeError: 'float' object has no attribute '__log__' Thanks for your answers. franck -- http://mail.python.org/mailman/listinfo/python-list
getting the state of an object
Hi ! Another question. When writing a class, I have often to destructure the state of an object as in : def foo(self) : (a,b,c,d) = (self.a,self.b,self.c,self.d) ... big code with a,b,c,d ... So I use the following method : def state(self) : return (self.a,self.b,self.c,self.d) so as to write : def foo(self) : (a,b,c,d) = self.state() ... big code with a,b,c,d ... This is probably not the best Python way to code, is it ? Is there a simple way to get the *ordered* list of instance variables as given in the parameter list of __init__ ? __dict__ gives it but not in order... Thanks a lot, franck -- http://mail.python.org/mailman/listinfo/python-list
Re: question on log as an instance method
On Sun, Oct 7, 2012 at 1:33 AM, Franck Ditter wrote: > Hi ! Here is Python 3.2.3, MacOSX-Lion > > Question 0 : I may consider + as an hidden instance method , as > 1+2 is equivalent to (1).__add__(2) ? No, it's not nearly that simple. It's technically equivalent to operator.add(1, 2) [ http://docs.python.org/library/operator.html#operator.add ], which hints that there's additional logic involved. Some examples of the complexities (in the general case): * special methods are looked up on the objects' classes, ignoring per-instance attributes; see http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes * trying to add objects of incompatible types raises TypeError rather than AttributeError (which one might otherwise expect when a class doesn't define __add__() [or similar]) * such TypeErrors are often raised directly by the interpreter itself, rather than from within the body of some specific implementation of an operator special method * falling back to reflected methods (in the case of +, __radd__() [ http://docs.python.org/reference/datamodel.html#object.__radd__ ]) when the normal method fails or is not defined * returning NotImplemented triggers fallback (or if already attempting fallback, may cause the operation to fail) > Question 2 : After importing math, Why would that be relevant? Python is not generally the sort of language that would have the mere importation of a std lib module significantly affect language semantics. > why can't I consider log as > an instance method, after all ? (4).__log__() > AttributeError: 'float' object has no attribute '__log__' Because Python just simply did not choose to make "take the (natural) logarithm of" a built-in, overloadable operation (hence, in part, why you had to `import math` to even be able to access that calculation). And it further didn't happen to define math.log() in terms of a .log() or .__log__() instance method. Basically, it's somewhat arbitrary and some historical reasons are involved. Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: question on log as an instance method
On Sun, 07 Oct 2012 10:33:36 +0200, Franck Ditter wrote: > Question : I may consider + as an hidden instance method , as 1+2 is > equivalent to (1).__add__(2) ? I also consider __abs__ as an instance > method : (-2).__abs__() > 2 The short answer is, yes. The *correct* answer is, not quite. So-called "dunder" methods (Double leading and trailing UNDERscore) methods like __add__, __abs__, __len__ and many others are treated slightly differently from ordinary instance methods, but only when they are automatically invoked by Python. If you explicitly call `instance.__add__(value)`, __add__ is treated as an ordinary instance method. But when you call `instance + value`, Python automatically invokes the __add__ method, but using slightly different method resolution rules. This is done for the sake of speed. > Question 1 : could the parser cope with the mandatory space in 1 > .__add__(2) ? Why not try it and see? py> 1 .__add__(2) 3 > Question 2 : After importing math, why can't I consider log as an > instance method, after all ? (4).__log__() > AttributeError: 'float' object has no attribute '__log__' Because importing a module does not magically add new methods to classes. Floats do not have a __log__ method, because they don't need one. Importing math doesn't create such a method. Why would it? What is the purpose of __log__? math.log doesn't need it. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: getting the state of an object
On Sun, Oct 7, 2012 at 1:50 AM, Franck Ditter wrote: > Hi ! > > Another question. When writing a class, I have often to > destructure the state of an object as in : > > def foo(self) : > (a,b,c,d) = (self.a,self.b,self.c,self.d) > ... big code with a,b,c,d ... I would generally strongly frown on doing that (at least if the destructuring is actually that trivial). The "self."s are only 5 characters; that's hardly burdensome or verbose. Just write it out each time, i.e.: def foo(self): … code with self.a, self.b, self.c, self.d ... Or in the extreme case, use "s" instead of "self" (using the name "self" is just a convention; it's not a language keyword or anything). > So I use the following method : > > def state(self) : > return (self.a,self.b,self.c,self.d) > > so as to write : > > def foo(self) : > (a,b,c,d) = self.state() > ... big code with a,b,c,d ... > > This is probably not the best Python way to code, is it ? Indeed it isn't. Don't bother with the pointless destructuring. And/or refactor your method so it's less big. > Is there a simple way to get the *ordered* list of instance > variables as given in the parameter list of __init__ ? There is no guaranteed correspondence whatsoever between __init__()'s parameters and the resulting object's instance variables. At a minimum, such a hack would fail to account for instance variables that are merely derived from the parameters (e.g. self.length = len(some_list_param) ) or are initialized to constant values (e.g. self.cache = {} ). And then there's private instance variables (e.g. self._foo = foo_param ); if the parameter is named "_foo", you're doing it wrong. That said, you can obtain the names of the parameters using the `inspect` module in the std lib. > __dict__ gives it but not in order… You can actually "fix" that, not that I at all recommend doing so: http://docs.python.org/dev/reference/datamodel.html#preparing-the-class-namespace Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: question on log as an instance method
On Sun, Oct 7, 2012 at 1:33 AM, Franck Ditter wrote: > As a matter of netiquette, please don't post from a plausible-but-invalid email address, especially at a domain that doesn't seem to belong to you. (I got a mailer-daemon bounce when replying to your posts.) If you must use an invalid address, then please make use of the ".invalid" TLD (that's what it's for!). Regards, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: getting the state of an object
On Oct 7, 2012 9:57 AM, "Franck Ditter" wrote: > > Hi ! > > Another question. When writing a class, I have often to > destructure the state of an object as in : > > def foo(self) : > (a,b,c,d) = (self.a,self.b,self.c,self.d) > ... big code with a,b,c,d ... > What's wrong with the above? It seems fine to me. Alternatively, don't bother: just use self.a etc. > So I use the following method : > > def state(self) : > return (self.a,self.b,self.c,self.d) > > so as to write : > > def foo(self) : > (a,b,c,d) = self.state() > ... big code with a,b,c,d ... This just seems needlessly confusing. Someone reading your code will have to see that line, find the state function, check the order of the return values and then confirm that it matches up with the order in the original line. The first version doesn't have this problem. You can see that it's correct just by looking at it. > This is probably not the best Python way to code, is it ? > Is there a simple way to get the *ordered* list of instance > variables as given in the parameter list of __init__ ? I don't know about simple but you can get the names of the arguments from the __init__ method object using the inspect module. Then you can use getattr te recover the attribute values. I wouldn't bother though. Explicit is better than implicit. If you want to extract the instance attributes as local variables then just write the one line that does it as in your first example. Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: getting the state of an object
On Sun, Oct 7, 2012 at 7:50 PM, Franck Ditter wrote: > def foo(self) : > (a,b,c,d) = (self.a,self.b,self.c,self.d) > ... big code with a,b,c,d ... > This strikes me as ripe for bug introduction. There's no problem if you're just reading those values, and mutating them is equally fine, but suddenly you need a different syntax for modifying instance members. def foo(self) : (a,b,c,d) = (self.a,self.b,self.c,self.d) e = a+b c.append(1234) d=self.d = 57 # Oops, mustn't forget to assign both! Since Python lacks the extensive scoping rules of (say) C++, it's much simpler and safer to be explicit about scope by adorning your instance variable references with their "self." tags. There's a guarantee that you can use "self.a" in any situation where you want to manipulate that member, a guarantee that's not upheld by the local "a". In theory, I suppose you could use a C-style preprocessor to help you. class Foo(object): #define asdf self.asdf #define qwer self.qwer def __init__(self,a,q): asdf=a; qwer=q def __repr__(self): return "Foo(%s,%s)"%(asdf,qwer) This is not, however, Pythonic code. But if you made some kind of better declaration than #define, and used a preprocessor that understood Python indentation rules and flushed its token list at the end of the class definition, you could perhaps make this look not-ugly. I still wouldn't recommend it, though. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: getting the state of an object
> Is there a simple way to get the *ordered* list of instance Here's one way to do it (weather doing it is a good idea or not is debatable): from operator import attrgetter def __init__(self, a, b, c, d): self.a, self.b, self.c, self.d = a, b, c, d get = attrgetter('a', 'b', 'c', 'd') self.state = lambda: get(self) -- http://mail.python.org/mailman/listinfo/python-list
Re: getting the state of an object
In article <507170e9$0$29978$c3e8da3$54964...@news.astraweb.com>, Steven D'Aprano wrote: > I've just looked at one of my classes, picked randomly, and the largest > method is twelve lines, the second largest is eight, and the average is > three lines. I took a look at a subtree of the project I'm working on now. 116 python files, 20 kloc, 330 functions (mostly class methods). I did a quick-and-dirty "grep -n" job on them to find the line numbers of the def statements, then another quick-and-dirty python script to find the differences, and summarize. Results below (second column is length of 'def' block in lines, first column is number of blocks of that length). This is just dumb line counting; no attempt to exclude block comments, white space, docstrings, etc. There's three different authors represented here, but I'd guess 70% of the code is mine. Of the three, I'm probably the one who writes the most refactored code (i.e. smallest functions). I just went and found the longest of these (193 lines). It starts with a 95 line block comment. Of the 100-or so lines of real code, I suppose with some effort it could have been refactored some, but not hugely. 7 3 19 4 12 5 17 6 10 7 16 8 10 9 6 10 8 11 11 12 4 13 8 14 9 15 13 16 4 17 8 18 9 19 5 20 9 21 3 22 6 23 5 24 4 25 4 26 4 27 3 28 2 29 1 30 3 31 4 32 4 33 8 34 2 35 2 36 3 37 2 39 1 40 3 41 1 42 3 43 2 44 2 45 1 46 2 47 1 48 1 51 2 54 1 55 2 56 2 59 1 60 1 62 1 63 1 64 1 65 1 74 1 75 1 78 1 94 1 100 1 105 1 148 1 164 1 193 -- http://mail.python.org/mailman/listinfo/python-list
wordnet semantic similarity: how to refer to elements of a pair in a list? can we sort dictionary according to the value?
In order to solve the following question, http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html: ★ Use one of the predefined similarity measures to score the similarity of each of the following pairs of words. Rank the pairs in order of decreasing similarity. How close is your ranking to the order given here, an order that was established experimentally by (Miller & Charles, 1998): car-automobile, gem-jewel, journey-voyage, boy-lad, coast-shore, asylum-madhouse, magician-wizard, midday-noon, furnace-stove, food-fruit, bird-cock, bird-crane, tool-implement, brother-monk, lad-brother, crane-implement, journey-car, monk-oracle, cemetery-woodland, food-rooster, coast-hill, forest-graveyard, shore-woodland, monk-slave, coast-forest, lad-wizard, chord-smile, glass-magician, rooster-voyage, noon-string. (1) First, I put the word pairs in a list eg. pairs = [(car, automobile), (gem, jewel), (journey, voyage) ]. According to http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html, I need to put them in the following format so as to calculate teh semantic similarity : wn.synset('right_whale.n.01').path_similarity(wn.synset('minke_whale.n.01')). In this case, I need to use loop to iterate each element in the above pairs. How can I refer to each element in the above pairs, i.e. pairs = [(car, automobile), (gem, jewel), (journey, voyage) ]. What's the index for 'car' and for 'automobile'? Thanks for your tips. (2) Since I can't solve the above index issue. I try to use dictionary as follows: >>> import nltk >>> from nltk.corpus import wordnet as wn >>> pairs = {'car':'automobile', 'gem':'jewel', 'journey':'voyage'} >>> for key in pairs: word1 = wn.synset(str(key) + '.n.01') word2 = wn.synset(str(pairs[key])+'.n.01') similarity = word1.path_similarity(word2) print key+'-'+pairs[key],similarity car-automobile 1.0 journey-voyage 0.25 gem-jewel 0.125 Now it seems that I can calculate the semantic similarity for each groups in the above dictionary. However, I want to sort according to the similarity value in the result before print the result out. Can sort dictionary elements according to their values? This is one of the requirement in this exercise. How can we make each group of words (e.g. car-automobile, jounrney-voyage, gem-jewel) sorted according to their similarity value? Thanks for your tips. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems building Python from hg trunk on Open SUSE
Skip Montanaro於 2012年10月6日星期六UTC+8上午8時25分06秒寫道: > I haven't messed around with Python 3 recently, so decided to give it > > a whirl again. I cloned the trunk (cpython) and set about it. This > > is on an OpenSUSE 12.1 system. I configured like so: > > > > ./configure --prefix=/home/skipm/.linux-local > > > > and ran the usual "make ; make install". > > > > I'm a bit perplexed about how it is installed. Instead of installing > > shared objects in > > > > /home/skipm/.linux-local/lib/python3.4/lib-dynload > > > > they were installed in > > > > /home/skipm/.linux-local/lib64/python3.4/lib-dynload > > > > (note the "lib64" vs. "lib"). This would be fine, except sys.path > > doesn't include the "lib64" version of this path: > > > > % PYTHONPATH= PYTHONSTARTUP= ~/.linux-local/bin/python3.4 -S > > Could not find platform dependent libraries > > Consider setting $PYTHONHOME to [:] > > Python 3.4.0a0 (default:26200f535296, Oct 3 2012, 12:48:07) > > [GCC 4.4.6 [TWW]] on linux > > >>> import sys > > >>> sys.path > > ['', '', '/home/skipm/.linux-local/lib/python34.zip', > > '/home/skipm/.linux-local/lib/python3.4/', > > '/home/skipm/.linux-local/lib/python3.4/plat-linux', > > '/home/skipm/.linux-local/lib/lib-dynload'] > > > > I see the message about setting PYTHONHOME. (That happens to be bad > > advice as sys.prefix and sys.exec_prefix are identical in this case.) > > What I don't understand is why directories containing "lib64" are not > > in sys.path by default, given that that's where "make install" put > > things. > > > > GCC is as delivered by The Written Word. (This is a work computer. > > The powers that be settled on TWW awhile ago for packaging all open > > source software we use on Linux and Solaris, thus removing a headache > > from our support staff.) It is: > > > > % gcc --version > > gcc (GCC) 4.4.6 [TWW] > > Copyright (C) 2010 Free Software Foundation, Inc. > > This is free software; see the source for copying conditions. There is NO > > warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. > > > > The architecture looks like this: > > > > % uname -a > > Linux udesktop264 3.1.0-1.2-desktop #1 SMP PREEMPT Thu Nov 3 14:45:45 > > UTC 2011 (187dde0) x86_64 x86_64 x86_64 GNU/Linux > > > > I don't see anything in the output of "./configure --help" which > > relates to 64-bit install directories, though I do see some lines in > > config.log about guessing the architecture. Some cursory googling > > didn't turn up any promising web pages, and I didn't find anything in > > the various documentation files in the repo related to building > > Python. > > > > Any suggestions about how to resolve this would be appreciated. > > > > Thx, > > > > Skip I am waiting for JYTHON and IRON PYTHON to be upgraded. -- http://mail.python.org/mailman/listinfo/python-list
Re: wordnet semantic similarity: how to refer to elements of a pair in a list? can we sort dictionary according to the value?
On 07/10/2012 17:15, Token Type wrote: In order to solve the following question, http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html: ★ Use one of the predefined similarity measures to score the similarity of each of the following pairs of words. Rank the pairs in order of decreasing similarity. How close is your ranking to the order given here, an order that was established experimentally by (Miller & Charles, 1998): car-automobile, gem-jewel, journey-voyage, boy-lad, coast-shore, asylum-madhouse, magician-wizard, midday-noon, furnace-stove, food-fruit, bird-cock, bird-crane, tool-implement, brother-monk, lad-brother, crane-implement, journey-car, monk-oracle, cemetery-woodland, food-rooster, coast-hill, forest-graveyard, shore-woodland, monk-slave, coast-forest, lad-wizard, chord-smile, glass-magician, rooster-voyage, noon-string. (1) First, I put the word pairs in a list eg. pairs = [(car, automobile), (gem, jewel), (journey, voyage) ]. According to http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html, I need to put them in the following format so as to calculate teh semantic similarity : wn.synset('right_whale.n.01').path_similarity(wn.synset('minke_whale.n.01')). In this case, I need to use loop to iterate each element in the above pairs. How can I refer to each element in the above pairs, i.e. pairs = [(car, automobile), (gem, jewel), (journey, voyage) ]. What's the index for 'car' and for 'automobile'? Thanks for your tips. (2) Since I can't solve the above index issue. I try to use dictionary as follows: import nltk from nltk.corpus import wordnet as wn pairs = {'car':'automobile', 'gem':'jewel', 'journey':'voyage'} for key in pairs: word1 = wn.synset(str(key) + '.n.01') word2 = wn.synset(str(pairs[key])+'.n.01') similarity = word1.path_similarity(word2) print key+'-'+pairs[key],similarity car-automobile 1.0 journey-voyage 0.25 gem-jewel 0.125 Now it seems that I can calculate the semantic similarity for each groups in the above dictionary. However, I want to sort according to the similarity value in the result before print the result out. Can sort dictionary elements according to their values? This is one of the requirement in this exercise. How can we make each group of words (e.g. car-automobile, jounrney-voyage, gem-jewel) sorted according to their similarity value? Thanks for your tips. In your for loop save the data in a list rather than print it out and sort according to this http://wiki.python.org/moin/HowTo/Sorting#Operator_Module_Functions -- Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unpaking Tuple
On Oct 6, 3:09 am, sajuptpm wrote: > I need a way to make following code working without any ValueError . > > >>> a, b, c, d = (1,2,3,4) > >>> a, b, c, d = (1,2,3). Why is it necessary to unpack the tuple into arbitrary variables. a_tuple=(1,2,3) for v in a_tuple: print v for ctr in range(len(a_tuple)): print a_tuple[ctr] -- http://mail.python.org/mailman/listinfo/python-list
Question on Python Split
Dear Group, Suppose I have a string as, "Project Gutenberg has 36000 free ebooks for Kindle Android iPad iPhone." I am terming it as, str1= "Project Gutenberg has 36000 free ebooks for Kindle Android iPad iPhone." I am working now with a split function, str_words=str1.split() so, I would get the result as, ['Project', 'Gutenberg', 'has', '36000', 'free', 'ebooks', 'for', 'Kindle', 'Android', 'iPad', 'iPhone.'] But I am looking for, ['Project Gutenberg', 'has 36000', 'free ebooks', 'for Kindle', 'Android iPad', 'iPhone'] This can be done if we assign the string as, str1= "Project Gutenberg, has 36000, free ebooks, for Kindle, Android iPad, iPhone," and then assign the split statement as, str1_word=str1.split(",") would produce, ['Project Gutenberg', ' has 36000', ' free ebooks', ' for Kindle', ' Android iPad', ' iPhone', ''] My objective generally is achieved, but I want to convert each group here in tuple so that it can be embedded, like, [(Project Gutenberg), (has 36000), (free ebooks), (for Kindle), ( Android iPad), (iPhone), ''] as I see if I assign it as for i in str1_word: print i ti=tuple(i) print ti I am not getting the desired result. If I work again from tuple point, I get it as, >>> tup1=('Project Gutenberg') >>> tup2=('has 36000') >>> tup3=('free ebooks') >>> tup4=('for Kindle') >>> tup5=('Android iPad') >>> tup6=tup1+tup2+tup3+tup4+tup5 >>> print tup6 Project Gutenberghas 36000free ebooksfor KindleAndroid iPad Then how may I achieve it? If any one of the learned members can kindly guide me. Thanks in Advance, Regards, Subhabrata. NB: Apology for some minor errors. -- http://mail.python.org/mailman/listinfo/python-list
Convert MAC to hex howto
Dear all, I'm trying to convert '00:08:9b:ce:f5:d4' to '\x00\x08\x9b\xce\xf5\xd4' for use in magic packet construction for WakeOnLan like so: wolsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) wolsocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) wolsocket.sendto('\xff'*6 + '\x00\x08\x9b\xce\xf5\xd4'*16, (expectedlanbroadcast, 80)) This is what I came up whith, but I remain puzzled on how to preserver the leading '\h' ... thanks for any hint expectedservermac = '00:08:9b:ce:f5:d4' hexcall = str.split(expectedservermac,":") hexcall.insert(0,'') hexcall = "\\x".join(hexcall).decode('string_escape') Thanks for any pointers. Sincerely, Joh -- http://mail.python.org/mailman/listinfo/python-list
Re: wordnet semantic similarity: how to refer to elements of a pair in a list? can we sort dictionary according to the value?
On 10/7/2012 12:15 PM, Token Type wrote: In this case, I need to use loop to iterate each element in the above pairs. How can I refer to each element in the above pairs, i.e. pairs = [(car, automobile), (gem, jewel), (journey, voyage) ]. What's the index for 'car' and for 'automobile'? Thanks for your tips. >>> pairs = [('car', 'automobile'), ('gem', 'jewel')] >>> pairs[0][0] 'car' >>> pairs[1][1] 'jewel' >>> for a,b in pairs: a,b ('car', 'automobile') ('gem', 'jewel') -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert MAC to hex howto
Johannes Graumann writes: > '00:08:9b:ce:f5:d4' > ... > hexcall = "\\x".join(hexcall).decode('string_escape') I think it's best not to mess with stuff like that. Convert to integers then convert back: mac = '00:08:9b:ce:f5:d4' hexcall = ''.join(chr(int(c,16)) for c in mac.split(':')) -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on Python Split
On 2012-10-07 20:30, subhabangal...@gmail.com wrote: Dear Group, Suppose I have a string as, "Project Gutenberg has 36000 free ebooks for Kindle Android iPad iPhone." I am terming it as, str1= "Project Gutenberg has 36000 free ebooks for Kindle Android iPad iPhone." I am working now with a split function, str_words=str1.split() so, I would get the result as, ['Project', 'Gutenberg', 'has', '36000', 'free', 'ebooks', 'for', 'Kindle', 'Android', 'iPad', 'iPhone.'] But I am looking for, ['Project Gutenberg', 'has 36000', 'free ebooks', 'for Kindle', 'Android iPad', 'iPhone'] This can be done if we assign the string as, str1= "Project Gutenberg, has 36000, free ebooks, for Kindle, Android iPad, iPhone," and then assign the split statement as, str1_word=str1.split(",") would produce, ['Project Gutenberg', ' has 36000', ' free ebooks', ' for Kindle', ' Android iPad', ' iPhone', ''] It can also be done like this: >>> str1 = "Project Gutenberg has 36000 free ebooks for Kindle Android iPad iPhone." >>> # Splitting into words: >>> s = str1.split() >>> s ['Project', 'Gutenberg', 'has', '36000', 'free', 'ebooks', 'for', 'Kindle', 'Android', 'iPad', 'iPhone.'] >>> # Using slicing with a stride of 2 gives: >>> s[0 : : 2] ['Project', 'has', 'free', 'for', 'Android', 'iPhone.'] >>> # Similarly for the other words gives: >>> s[1 : : 2] ['Gutenberg', '36000', 'ebooks', 'Kindle', 'iPad'] >>> # Combining them in pairs, and adding an extra empty string in case there's an odd number of words: >>> [(x + ' ' + y).rstrip() for x, y in zip(s[0 : : 2], s[1 : : 2] + [''])] ['Project Gutenberg', 'has 36000', 'free ebooks', 'for Kindle', 'Android iPad', 'iPhone.'] My objective generally is achieved, but I want to convert each group here in tuple so that it can be embedded, like, [(Project Gutenberg), (has 36000), (free ebooks), (for Kindle), ( Android iPad), (iPhone), ''] as I see if I assign it as for i in str1_word: print i ti=tuple(i) print ti I am not getting the desired result. If I work again from tuple point, I get it as, tup1=('Project Gutenberg') tup2=('has 36000') tup3=('free ebooks') tup4=('for Kindle') tup5=('Android iPad') tup6=tup1+tup2+tup3+tup4+tup5 print tup6 Project Gutenberghas 36000free ebooksfor KindleAndroid iPad It's the comma that makes the tuple, not the parentheses, except for the empty tuple which is just empty parentheses, i.e. (). Then how may I achieve it? If any one of the learned members can kindly guide me. >>> [((x + ' ' + y).rstrip(), ) for x, y in zip(s[0 : : 2], s[1 : : 2] + [''])] [('Project Gutenberg',), ('has 36000',), ('free ebooks',), ('for Kindle',), ('Android iPad',), ('iPhone.',)] Is this what you want? If you want it to be a list of pairs of words, then: >>> [(x, y) for x, y in zip(s[0 : : 2], s[1 : : 2] + [''])] [('Project', 'Gutenberg'), ('has', '36000'), ('free', 'ebooks'), ('for', 'Kindle'), ('Android', 'iPad'), ('iPhone.', '')] -- http://mail.python.org/mailman/listinfo/python-list
Re: Unpaking Tuple
On 10/7/2012 1:58 PM, woooee wrote: On Oct 6, 3:09 am, sajuptpm wrote: I need a way to make following code working without any ValueError . a, b, c, d = (1,2,3,4) a, b, c, d = (1,2,3) You cannot 'make' buggy code work -- except by changing it. >>> a, b, c, *d = (1,2,3) >>> d [] Why is it necessary to unpack the tuple into arbitrary variables. It is not necessary. a_tuple=(1,2,3) for v in a_tuple: print v This is often the right way to access any iterable. for ctr in range(len(a_tuple)): print a_tuple[ctr] This is seldom the right way. See the example below. Unpacking is for when you have known-length iterables. For instance, enumerate produces pairs. >>> for i, v in enumerate('abc'): print('Item {} is {}.'.format(i, v)) Item 0 is a. Item 1 is b. Item 2 is c. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert MAC to hex howto
On 2012-10-07 20:44, Johannes Graumann wrote: Dear all, I'm trying to convert '00:08:9b:ce:f5:d4' to '\x00\x08\x9b\xce\xf5\xd4' for use in magic packet construction for WakeOnLan like so: wolsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) wolsocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) wolsocket.sendto('\xff'*6 + '\x00\x08\x9b\xce\xf5\xd4'*16, (expectedlanbroadcast, 80)) This is what I came up whith, but I remain puzzled on how to preserver the leading '\h' ... thanks for any hint expectedservermac = '00:08:9b:ce:f5:d4' hexcall = str.split(expectedservermac,":") hexcall.insert(0,'') hexcall = "\\x".join(hexcall).decode('string_escape') Thanks for any pointers. It looks like you're using Python 2, so: >>> s = '00:08:9b:ce:f5:d4' >>> "".join(chr(int(x, 16)) for x in s.split(":")) '\x00\x08\x9b\xce\xf5\xd4' -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on Python Split
On 10/7/2012 3:30 PM, subhabangal...@gmail.com wrote: If I work again from tuple point, I get it as, tup1=('Project Gutenberg') tup2=('has 36000') tup3=('free ebooks') tup4=('for Kindle') tup5=('Android iPad') These are strings, not tuples. Numbered names like this are a bad idea. tup6=tup1+tup2+tup3+tup4+tup5 print tup6 Project Gutenberghas 36000free ebooksfor KindleAndroid iPad tup1=('Project Gutenberg') tup2=('has 36000') tup3=('free ebooks') tup4=('for Kindle') tup5=('Android iPad') print(' '.join((tup1,tup2,tup3,tup4,tup5))) >>> Project Gutenberg has 36000 free ebooks for Kindle Android iPad -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert MAC to hex howto
MRAB wrote: > On 2012-10-07 20:44, Johannes Graumann wrote: >> Dear all, >> >> I'm trying to convert >> '00:08:9b:ce:f5:d4' >> to >> '\x00\x08\x9b\xce\xf5\xd4' >> for use in magic packet construction for WakeOnLan like so: >> wolsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) >> wolsocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) >> wolsocket.sendto('\xff'*6 + '\x00\x08\x9b\xce\xf5\xd4'*16, >> (expectedlanbroadcast, 80)) >> >> This is what I came up whith, but I remain puzzled on how to preserver >> the leading '\h' ... thanks for any hint >> >> expectedservermac = '00:08:9b:ce:f5:d4' >> hexcall = str.split(expectedservermac,":") >> hexcall.insert(0,'') >> hexcall = "\\x".join(hexcall).decode('string_escape') >> >> Thanks for any pointers. >> > It looks like you're using Python 2, so: > > >>> s = '00:08:9b:ce:f5:d4' > >>> "".join(chr(int(x, 16)) for x in s.split(":")) > '\x00\x08\x9b\xce\xf5\xd4' Many thanks! Joh -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert MAC to hex howto
Paul Rubin wrote: > Johannes Graumann writes: >> '00:08:9b:ce:f5:d4' >> ... >> hexcall = "\\x".join(hexcall).decode('string_escape') > > I think it's best not to mess with stuff like that. Convert to integers > then convert back: > > mac = '00:08:9b:ce:f5:d4' > hexcall = ''.join(chr(int(c,16)) for c in mac.split(':')) Thanks to you as well! Joh -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert MAC to hex howto
Johannes Graumann wrote: > Dear all, > > I'm trying to convert > '00:08:9b:ce:f5:d4' > to > '\x00\x08\x9b\xce\xf5\xd4' > for use in magic packet construction for WakeOnLan like so: > wolsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) >wolsocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) > wolsocket.sendto('\xff'*6 + '\x00\x08\x9b\xce\xf5\xd4'*16, > (expectedlanbroadcast, 80)) > > This is what I came up whith, but I remain puzzled on how to preserver the > leading '\h' ... thanks for any hint > > expectedservermac = '00:08:9b:ce:f5:d4' > hexcall = str.split(expectedservermac,":") > hexcall.insert(0,'') > hexcall = "\\x".join(hexcall).decode('string_escape') >>> import binascii >>> expectedservermac = '00:08:9b:ce:f5:d4' >>> binascii.unhexlify(expectedservermac.replace(":", "")) '\x00\x08\x9b\xce\xf5\xd4' -- http://mail.python.org/mailman/listinfo/python-list
Re: how to run shell command like "<
于 2012-9-29 19:53, Kushal Kumaran 写道: On Sat, Sep 29, 2012 at 6:18 AM, 叶佑群 wrote: 于 2012-9-28 16:16, Kushal Kumaran 写道: On Fri, Sep 28, 2012 at 1:15 PM, 叶佑群 wrote: Hi, all, I have the shell command like this: sfdisk -uM /dev/sdb<< EOT ,1000,83 ,,83 EOT I have tried subprocess.Popen, pexpect.spawn and os.popen, but none of these works, but when I type this shell command in shell, it is works fine. I wonder how to emulate this type of behavior in python , and if someone can figure out the reason why? The sample code of subprocess.Popen is: command = ["sfdisk", "-uM", target, "< The "< I tried this, but it is still not work. What do you mean by "not work"? Sorry for replying so late, these days are long vocation in china. If I type command in shell line by line, the command will run as expected, but when I invoke the command in python, it is always failed. Which is what I mean "not work". - If you get an exception, copy the entire traceback into an email No exception occured. - If you do not get an exception, print out the value of the "errors" variable to see why the command failed. You can also check pobj.returncode for the exit status of the subprocess. I solved this problem as below: fop = os.popen ("sfdisk -uM %s
Re: notmm is dead!
On Oct 6, 12:59 pm, Michael Torrie wrote: > I suppose a person can fail a turing test... You did, yes :) -- http://mail.python.org/mailman/listinfo/python-list
Re: notmm is dead!
On Sun, Oct 7, 2012 at 9:19 PM, alex23 wrote: > On Oct 6, 12:59 pm, Michael Torrie wrote: >> I suppose a person can fail a turing test... > > You did, yes :) > What is failed, but a timeline in this scenario, if you found the answer in the end? Failure becomes answer not given in interval required, but did anybody else, and if so...how many? -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: notmm is dead!
On Oct 8, 11:45 am, Dwight Hutto wrote: > What is failed, but a timeline in this scenario, if you found the > answer in the end? It was a _joke_ referring to Michael Torrie's email addressing the 8 Dihedral bot _as if it was a person_. > Failure becomes answer not given in interval required, but did anybody > else, and if so...how many? 23? I really have no idea what you're asking here. -- http://mail.python.org/mailman/listinfo/python-list
Re: notmm is dead!
On 10/07/2012 08:08 PM, alex23 wrote: > On Oct 8, 11:45 am, Dwight Hutto wrote: >> What is failed, but a timeline in this scenario, if you found the >> answer in the end? > > It was a _joke_ referring to Michael Torrie's email addressing the > 8 Dihedral bot _as if it was a person_. Well it would be useful to probe the bot's parameters... -- http://mail.python.org/mailman/listinfo/python-list
How to control the internet explorer?
I want to save all the URLs in current opened windows, and then close all the windows. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to control the internet explorer?
On Oct 8, 1:03 pm, yujian wrote: > I want to save all the URLs in current opened windows, and then close > all the windows. Try mechanize or Selenium. -- http://mail.python.org/mailman/listinfo/python-list
Re: notmm is dead!
>> It was a _joke_ referring to Michael Torrie's email addressing the >> 8 Dihedral bot _as if it was a person_. > > Well it would be useful to probe the bot's parameters... Five eights is a busy bot: http://www.velocityreviews.com/forums/t806110-p8-ok-lets-start-real-programming-in-c-for-problems.html http://www.edaboard.co.uk/a-cheap-or-free-version-of-system-verilog-t521889.html -- http://mail.python.org/mailman/listinfo/python-list
Re: notmm is dead!
On 10/07/2012 09:42 PM, Jason Friedman wrote: >>> It was a _joke_ referring to Michael Torrie's email addressing the >>> 8 Dihedral bot _as if it was a person_. >> >> Well it would be useful to probe the bot's parameters... > > Five eights is a busy bot: > http://www.velocityreviews.com/forums/t806110-p8-ok-lets-start-real-programming-in-c-for-problems.html > http://www.edaboard.co.uk/a-cheap-or-free-version-of-system-verilog-t521889.html Indeed and he doesn't make much more sense in any of these venues. And it does not seem to engage in conversation on any of these other forums either. -- http://mail.python.org/mailman/listinfo/python-list
Re: notmm is dead!
On Thu, Oct 4, 2012 at 2:10 PM, Etienne Robillard wrote: > Dear list, > > Due to lack of energy and resources i'm really sad to announce the removal of > notmm from pypi and bitbucket. I deleted > also my account from bitbucket as it was not really useful for me. Not 1 response? notmm will continue to be accessible from my master > site at http://gthc.org/dist/notmm until the server get down, as I cannot > find money to pay for the hosting of notmm.org, > neither anyone to encourage the project so it can grow further. Saw a niche, and announced your takeover? > > I have tried to develop a coherent extension for Django using the open source > model but I'm afraid to have been > bitten by its failure to encourage a free market over one dictated by profit > and the use of cheap tricks to compete unfairly > with perhaps too much openness. I always will also continue to love and use > free softwares but sadly it seems asking for a little > fairness is too much asked to competitors dedicated in stealing and > subverting my work for their own advantages... > Then bring in an OS project of your own, and know that's what happens. > I therefore refuse to continue any longer being mocked by competitors asking > excessive prices for having a broken Internet dictated by > a few companies and decide the content I should be visiting. > Just market penetration, not mocking. > Shall you have anything you wish saying I'll be open to discuss further on > this list. I wish also to thanks the supporters > of the project who have invested time and energy into my business and > dedication to the notmm project. It has to have an equal, or equivlilaint value to the current statistically valued features. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list