[issue26977] Unnecessary line in statistics.pvariance
New submission from Ian Foote: In statistics.pvariance, the sum of squares helper function (_ss) is called twice and the first return value is unused: https://github.com/python/cpython/blob/9043c80b0daaddb5bff1e37432d503910506727f/Lib/statistics.py#L596 -- components: Library (Lib) messages: 265131 nosy: Ian Foote priority: normal severity: normal status: open title: Unnecessary line in statistics.pvariance versions: Python 3.6 ___ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue26977> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)
On 22/03/16 11:05, BartC wrote: On 22/03/2016 01:01, Steven D'Aprano wrote: Pythonic code probably uses a lot of iterables: for value in something: ... in preference to Pascal code written in Python: for index in range(len(something)): value = something[index] (Suppose you need both the value and its index in the loop? Then the one-line for above won't work. For example, 'something' is [10,20,30] and you want to print: 0: 10 1: 20 2: 30 ) The builtin enumerate function is the idiomatic way: for index, item in enumerate(something): ... Regards, Ian F -- https://mail.python.org/mailman/listinfo/python-list
Re: try..except with empty exceptions
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On 11/04/15 08:11, Steven D'Aprano wrote: But with try...except, an empty exception list means to catch *everything*, not nothing: try: ... except a,b,c: # catches a, b, c try: ... except a,b: # catches a, b This example is incorrect. In python3 it is a SyntaxError: Python 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] on linux Type help, copyright, credits or license for more information. try: ... 1/0 ... except ValueError, ZeroDivisionError: File stdin, line 3 except ValueError, ZeroDivisionError: ^ SyntaxError: invalid syntax In python2 it aliases ValueError as ZeroDivisionError: Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type help, copyright, credits or license for more information. try: ... 1/0 ... except ValueError, ZeroDivisionError: ... pass ... Traceback (most recent call last): File stdin, line 2, in module ZeroDivisionError: integer division or modulo by zero To get the behaviour you expect, you must use parentheses: try: ... 1/0 ... except (ValueError, ZeroDivisionError): ... pass ... Regards, Ian F -BEGIN PGP SIGNATURE- Version: GnuPG v1 iQEcBAEBAgAGBQJVKS2dAAoJEODsV4MF7PWznkAH/jidWhoJ//gsvBr0ByOOOEgc A+k8HqrkALfzrh3aEjJB3sq19oLfLcepQeFVUh77mJKOMCQdEeyJtqIz6tLc4RUa L/nXytHygXVTb5HIARGVkPD26gqAleSb9eZUfPeSEvRHy9UbFS7SMmOdkApheDX3 Vq8TOa8EchaYd+S89y9eepZAhGC7n2TNwrNgp36sbHoz/hYUxFNnugP0ow9FM0Wk MGKGh04c3Lao+6w7a0scz4YKKb8wTdYkyYwlJhEdg3q74+PwYJpkjcGucna745AZ XlAKlDCJ9LhPgMufuGdRNskJa4TF709ec5hG9itHu1lFKrjH1iJCEU9ntX6hInU= =zi4K -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
Re: Idiomatic backtracking in Python
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hi, I think a very idiomatic way to implement backtracking is using a recursive generator (python 3): def backtrack_solver(data=None): if data is None: yield from backtrack_solver(data=initial_data) if cannot_be_valid(data): return if matches_condition(data): yield data return for new_data in process(data): yield from backtrack_solver(new_data) This generator will yield valid solutions to a suitably defined problem. `initial_data`, `cannot_be_valid`, `matches_condition` and `process` should be replaced with appropriate implementation for your problem. For example, a sudoku solver could be fit to this by accepting a partially solved grid as the `data` parameter. `cannot_be_valid` would now detect grids that have, say, two `1`s in a row or any other invalid grid state and exit. `matches_condition` would detect a fully solved grid. `process` would produce new grids with more cells filled in than the current grid. `initial_data` wouldn't be strictly necessary here, but you could use it for an example grid. It could also be an empty grid, and the solver would then yield all valid grids. Regards, Ian F On 25/01/15 20:15, Johannes Bauer wrote: Hi folks, I have a problem at hand that needs code for backtracking as a solution. And I have no problem coding it, but I can't get rid of the feeling that I'm always solving backtracking problems in a non-Pythonic (non-idiomatic) way. So, I would like to ask if you have a Pythonic approach to backtracking problems? If so, I'd love to hear your solutions! Cheers, Johannes -BEGIN PGP SIGNATURE- Version: GnuPG v1 iQEcBAEBAgAGBQJUxVc3AAoJEODsV4MF7PWzO+sH/jaz0Dc7Hs9LkbB8g6//A7pK bxBeFSVtmvaHynASg2PRAzSAC4dty5R52myPoXB3Hdf+otTjBUjOyA7k5j+HCDum TeJJSUFwOFQxr3yRtXcYoct+xYGBAGRqjT0oiGJMFYp5dLPXmHsAv10KIr3HcOo4 TgqQ9XtyMw60Tmx1ZJ/pj0xOPtrr5PUxe0bwRC5bRycDS943s+UJ/o42DhnBtkZp h6kkqsZsAL27i0hZrqBEfWMaIHbY9DZNzA9PYyYEl/pzvtB0tpN6ENrxTQFbBNeE SZoEz9AdcUr9D0ej3HaTgmbT/ivl0op4xQdnpp75uRnGpaH5LlssEGbWQsmRwsY= =Jpwv -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python 3?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On 20/04/14 03:34, Michael Torrie wrote: On 04/18/2014 10:49 PM, Andrew Berg wrote: Python 3 is not the future; it is the present. If you're developing an application, just use Python 3.4 and don't look back unless you absolutely positively *need* one of the big libraries that doesn't fully support Python 3 yet. Depends on what OS you want to be running on. I don't know of any currently-supported Enterprise distributions (long-term support) that ship with Python 3.4. I don't know if you'd count it as an Enterprise distribution, but ubuntu 14.04 (LTS) ships with python 3.4 (and 2.7). Regards, Ian F -BEGIN PGP SIGNATURE- Version: GnuPG v1 Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iQEcBAEBAgAGBQJTU4mGAAoJEODsV4MF7PWzR2sIAL4P0DhzWr5b7T4tfxSFWvlM A31VEwh1MiL8qQKi+ukzm1lumnqF0VZG5a8VYOrq9F/AgbPmkmdaJ3vwlNSZYYrq X6E0zdszTbnK6ec3zNHsqhWd7id/vzyJG5OQkDgg7K9dHY2r2lYfneIUhKvGy01q 6kaqWWXs77UIeWam2amjhtAMsUZtte/828CoIugHBdZgUhmbbNA8PK6/38w6BSgw 3NzT2kCz0298jqPUUZw++pap0Bb/9tQ+Ceps6KKeCE3QJ12Qn7Viv7TnrpQQnkeT Wt56VWoS9VGodB8h7ozHFGeA11VePN9YdLeM+CuUqNsOxXhuean7ysMiazMU30s= =mv5B -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python 3?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On 19/04/14 05:49, Andrew Berg wrote: On 2014.04.18 22:28, Anthony Papillion wrote: What is the general feel of /this/ community? I'm about to start a large scale Python project. Should it be done in 2 or 3? What are the benefits, aside from the 'it's the future' argument? Python 3 is not the future; it is the present. If you're developing an application, just use Python 3.4 and don't look back unless you absolutely positively *need* one of the big libraries that doesn't fully support Python 3 yet. The smaller ones either support it or have been replaced, and the few remaining (e.g., Twisted, Django) are getting there. Django has been there since 1.5. My company has been using python3 in production since 1.6 was released. There have been a few other third party libraries we've wanted to use but can't, but we've been able to work around that. Regards, Ian F -BEGIN PGP SIGNATURE- Version: GnuPG v1 Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iQEcBAEBAgAGBQJTUnMOAAoJEODsV4MF7PWzhEsH/infLqjUcGh+vSTaMNEvjuRn /vqaxiok5/9opocoDtBbK707rpJz55V+NP1ajhso0llhLlQ1T7XyAK2QQthfvcTd FIyn7uw7ud5nofivXUkkO3g9FoHRASZnAc9mXZGGV7O1RKjA3YvEccOakJKpq/jC UYzBYLOfkUzLYV9yQPaE5Dxt/rRmO1NLNzdBMXXTBOy4s6hd+B+TSCCgAgGy05ZJ yNePgO98N2wq7W/iG4EAw409rxXYxR0cAHNSID7+m1omSTPls4PV+jyIfmoS+eBl 6nWkqjVw3yw2cF0gBs1k/sjxPZ/aXOjD1FxpIhBOvh+upNieFSP0AT2X5R3NRnw= =wW3W -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
Re: Python GUI?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On 11/09/13 21:55, eamonn...@gmail.com wrote: There are a few known GUI toolkits out there, and the main ones from what I can tell are: Tkinter -- Simple to use, but limited PyQT -- You have a GUI designer, so I'm not going to count that PyGTK -- Gnome officially back this I think wxPython -- Very nice, very professional, approved by Python creator, but alas hard to get started with So, what are your personal preferences and why? Why use X over Y? I, personally, really like wxPython, but I also really like Tkinter. I've messed with PyGTK, but I'd choose wxPython over it. Have you got anything to say on what one I should be using(excluding PyQT because it has a DD designer :( )? Is Tkinter really dead? Should I stick with wxPython? It's might be similar to the What language to use argument, or the What background to code on argument(I prefer darker backgrounds xD Please don't argue about this though!), in the sense that there is *no* answer, just preference. Also, with wxPython, it has kind of a flow layout like JFrame, whereas it will adjust it's layout to look like a native Mac App, Windows app or Linux App, correct? It'll look almost identical, right? Not that it matters, I'm just curious! :D Thanks! Another GUI toolkit is kivy (kivy.org). It has a focus on supporting a wide range of platforms, including Android and IOs, and various input devices (mouse, keyboard, touchscreen, etc). Kivy is in active development and I think is well worth a look. Regards, Ian F -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.12 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iQEcBAEBAgAGBQJSMiFNAAoJEODsV4MF7PWzOsAH/3hidUN4pNxDG5ox2hNmfFkz g8D+hhXz/zKC+MpEh2iEm9G9NhaxoSTLQkcsUs5bxL9MvIQ0TYy68/vbQddRA52I GN0ofz8+E5h7MX57wegE/uxv0N9+CjdpWfwOfESoR5TXGUD8tr9ONEKAENLvod3W JUgU0KvN410J8+2yxI+LKpqezW3hNr43VoUO4zEmRgCm6KEK6wdKdooI5j45tb9r HW7vZgd12RCzE4XMVSBRl20xcYB9isi9erP7UnTCep8FUQKV0XxdnXY00rEBPQEm 7hgh66dIX5c2SC3fPgiYHFA7fSv7x4hrCJcokr+z5LEfdzRInra01tqnQLxnA+Q= =uPwE -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
Re: Kivy for Python 3.3
On 11/07/13 10:09, fronag...@gmail.com wrote: Hello, first time poster here, and general newbie to Python. I'm looking to write a program in Python, (and have in fact written most of it by now,) and am trying to put together a GUI for it. Kivy looks very nice, particularly with the fact that it's supposed to be compatible with most platforms (including Android, which I would like to be able to use my program on in addition to running it on my desktop) with minimal hassle. However, its current iteration is Python 2.7 only, and I've only learned Python 3.3. I suppose I could learn Python 2.7, but I don't really want to. (Nor rewrite my program.) I could wait for the next release of Kivy, but who knows when that will be? In any case, it's apparently possible to pull and compile the development version of Kivy for 3.3: https://groups.google.com/forum/#!topic/kivy-dev/pRp_02jaJww/discussion, however, I haven't succeeded in getting it to work. I'm on a Windows machine, and after a good deal of wrangling, I'm getting: C:\Users\[SNIP]\Desktop\kivy-py3python setup.py build_ext --inplace --compiler=mi ngw32 [INFO ] Kivy v1.8.0-dev Windows platform detected, force GLEW usage. running build_ext Build configuration is: * use_mesagl = False * use_x11 = False * use_rpi = False * use_opengl_es2 = True * use_opengl_debug = False * use_sdl = False * use_ios = False * use_glew = True Generate config.h Generate config.pxi cythoning kivy\properties.pyx to kivy\properties.c building 'kivy.properties' extension C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python33\include -IC:\Pytho n33\include -c kivy\properties.c -o build\temp.win32-3.3\Release\kivy\properties .o writing build\temp.win32-3.3\Release\kivy\properties.def C:\MinGW\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-3.3\Release\kivy\pr operties.o build\temp.win32-3.3\Release\kivy\properties.def -LC:\Python33\libs - LC:\Python33\PCbuild -lm -lpython33 -lmsvcr100 -o C:\Users\Lung\Desktop\kivy-py3 \kivy\properties.pyd C:\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot fin d -lmsvcr100 collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 I also tried to compile it with an Ubuntu virtual machine, but I failed hard on that since I'm not a native Linux user. Would anyone be able to help, either by suggesting how I can fix the above error, or, perhaps, by helping me compile Kivy? (I did post this on the Kivy group, but I've not gotten any response there... The group's a bit dead.) Hi Have you tried asking on the kivy irc channel? (#kivy on freenode, or http://webchat.freenode.net/?nick=kvuser.channels=kivyuio=d4) The channel is fairly active, though you might have to wait a bit for a response. I'm not a Windows user myself, so unfortunately I can't help with the issue directly. Regards, Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: [SPOILERS] Python easter eggs
On 03/07/13 14:29, Steven D'Aprano wrote: Most people are familiar with: import this and sometimes even with: from __future__ import braces But I'm aware of at least three more. Anyone care to give them? import antigravity Regards, Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Game Development?
On 07/06/13 16:53, letsplaysf...@gmail.com wrote: I was planning on making a small 2D game in Python. Are there any libraries for this? I know of: • Pygame - As far as I know it's dead and has been for almost a year • PyOgre - Linux and Windows only(I do have those, but I want multi-platform) • Cocos2D - Won't install and cant find any support • PyCap - Can't find any documentation • Panda3D - Dead since 2011 + overkill for what I need • PyOpenGL - Overkill Any help on what to do with this would be appreciated. I am making games mainly in Lua but I'd like to make one in Python for fun. I also understand that Python isn't exactly the *BEST* choice programming a game, but I have heard it is possible. Tell me if it's true. Thanks! You might also wish to consider Kivy (kivy.org). Regards, Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: Future standard GUI library
On 26/05/13 20:41, Michael Torrie wrote: On 05/26/2013 11:43 AM, Wolfgang Keller wrote: snip Maybe it would have been faster to develop, but ultimately less useful and require more development time in the long run. suppose I now want the app natively on my phone (because that's all the rage). It's an iPhone. Oh. Apple doesn't support Python. Okay, rewrite the works, including business logic, in Objective C. Now I want it on my android phone. Oops rewrite the stack again in Java. Kivy (http://kivy.org) is a python library that can be used to write python apps for Linux, Windows, MaxOSX, Android and IOS. Regards, Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie to python. Very newbie question
On 07/04/13 20:09, Dennis Lee Bieber wrote: On Sun, 7 Apr 2013 04:16:27 -0700 (PDT), ReviewBoard User lalitha.viswan...@gmail.com declaimed the following in gmane.comp.python.general: Hi I am a newbie to python and am trying to write a program that does a sum of squares of numbers whose squares are odd. For example, for x from 1 to 100, it generates 165 as an output (sum of 1,9,25,49,81) Here is the code I have print reduce(lambda x, y: x+y, filter(lambda x: x%2, map(lambda x: x*x, xrange (10**6 = sum(x*x for x in xrange(1, 10**6, 2)) I am getting a syntax error. Can you let me know what the error is? I can't even read that mess... three nested lambda? Not the most efficient version but... sum( x*x for x in range(100/2) if (x*x % 2) and (x*x 100) ) 165 The range(100/2) is a simple reduction to avoid invoking a sqrt function... the more economical is import math sum( x*x for x in range(int(math.sqrt(100))) if x*x % 2) 165 I'm surprised no one has suggested: import math sum( x*x for x in range(1, int(math.sqrt(100)), 2)) Regards, Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: JIT compilers for Python, what is the latest news?
On 05/04/13 03:29, John Ladasky wrote: I'm revisiting a project that I haven't touched in over a year. It was written in Python 2.6, and executed on 32-bit Ubuntu 10.10. I experienced a 20% performance increase when I used Psyco, because I had a computationally-intensive routine which occupied most of my CPU cycles, and always received the same data type. (Multiprocessing also helped, and I was using that too.) I have now migrated to a 64-bit Ubuntu 12.10.1, and Python 3.3. I would rather not revert to my older configuration. That being said, it would appear from my initial reading that 1) Psyco is considered obsolete and is no longer maintained, 2) Psyco is being superseded by PyPy, 3) PyPy doesn't support Python 3.x, or 64-bit optimizations. Do I understand all that correctly? I guess I can live with the 20% slower execution, but sometimes my code would run for three solid days... Pypy is working on porting to python 3. They are accepting donations: http://pypy.org/py3donate.html Regards, Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: flaming vs accuracy [was Re: Performance of int/long in Python 3]
On 28/03/13 09:03, jmfauth wrote: The problem is elsewhere. Nobody understand the examples I gave on this list, because nobody understand Unicode. These examples are not random examples, they are well thought. If you were understanding the coding of the characters, Unicode and what this flexible representation does, it would not be a problem for you to create analog examples. So, we are turning into circles. This flexible representation succeeds to cumulate in one shoot all the design mistakes it is possible to do, when one wishes to implements Unicode. Example of a good Unicode understanding. If you wish 1) to preserve memory, 2) to cover the whole range of Unicode, 3) to keep maximum performance while preserving the good work Unicode.org as done (normalization, sorting), there is only one solution: utf-8. For this you have to understand, what is really a unicode transformation format. Why all the actors, active in the text field, like MicroSoft, Apple, Adobe, the unicode compliant TeX engines, the foundries, the organisation in charge of the OpenType font specifications, are able to handle all this stuff correctly (understanding + implementation) and Python not?, I should say this is going beyond my understanding. Python has certainly and definitvely not revolutionize Unicode. jmf You're confusing python's choice of internal string representation with the programmer's choice of encoding for communicating with other programs. I think most people agree that utf-8 is usually the best encoding to use for interoperating with other unicode aware software, but as a variable-length encoding it has disadvantages that make it unsuitable for use as an internal representation. Specifically, indexing a variable-length encoding like utf-8 is not as efficient as indexing a fixed-length encoding. Regards, Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: monty python
On 20/03/13 13:38, Jan Oelze wrote: Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior. This isn't true in python 3: Python 3.2.3 (default, Oct 19 2012, 19:53:57) [GCC 4.7.2] on linux2 Type help, copyright, credits or license for more information. b'bytes' 'unicode' Traceback (most recent call last): File stdin, line 1, in module TypeError: unorderable types: bytes() str() Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Tutorials
On 18/01/13 14:47, Rik wrote: Hi, I've developed a website for beginners to Python. I'd appreciate any comments or criticism. It's still under development, and should be finished in the next few months. Oh, and it's free to use. www.usingpython.com Is there a particular reason you disable right-click with javascript? Regards, Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Tutorials
On 18/01/13 14:47, Rik wrote: Hi, I've developed a website for beginners to Python. I'd appreciate any comments or criticism. It's still under development, and should be finished in the next few months. Oh, and it's free to use. www.usingpython.com Your example code on http://usingpython.com/variables/ is missing a space: #Whatever the user enters is stored in a variable called ‘name’. name = input(What is your name? ) # Remember how we can use + to ‘add’ strings together? print(Hello + name + !) Here's my output: name = input(What is your name? ) What is your name? Ian print(Hello + name + !) HelloIan! Your final print should be: print(Hello + name + !) Regards, Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: Dependency management in Python?
On 11/01/13 22:34, Rodrick Brown wrote: On Fri, Jan 11, 2013 at 5:23 PM, Adelbert Chang adelbe...@gmail.com mailto:adelbe...@gmail.com wrote: Hi all, I've been using Python for a while now but one of my concerns is if it is possible to have some sort of dependency management (not sure if right term) for Python? In the Scala language there is the Simple Build Tool that lets me specify on a project-by-project basis which libraries I want to use (provided they are in a central repository somewhere) and it will download them for me. Better yet, when a new version comes out I need only change the SBT configuration file for that project and it will download it for me. Is there something like this for Python. I am typically wary of downloading Python modules I use like NumPy, SciPy, NetworkX, etc because I want to be able to upgrade at any time and doing so seems to be a hassle - in fact, I am not entirely sure how to upgrade. Checkout PIP/setuptools and virtualenv Thank you and regards, -Adelbert -- http://mail.python.org/mailman/listinfo/python-list pip and virtualenv is a great combination. I also like to use virtualenvwrapper for convenience, but it isn't necessary. Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: get each pair from a string.
On 22/10/12 09:03, Emile van Sebille wrote: So, as OP's a self confessed newbie asking about slicing, why provide an example requiring knowledge of tee, enumerate, next and izip? Because not only the newbie will read the thread? I for one was interested to see all the different possible approaches, and their upsides and downsides. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any difference between print 3 and print '3' in Python ?
On 09/09/12 14:23, iMath wrote: 在 2012年3月26日星期一UTC+8下午7时45分26秒,iMath写道: I know the print statement produces the same result when both of these two instructions are executed ,I just want to know Is there any difference between print 3 and print '3' in Python ? thx everyone The difference is that 3 is an integer whereas '3' is a string. The print statement (function in python 3) converts any object to a string before displaying it on the screen, so print 3 and print '3' both display the same result. Ian F -- http://mail.python.org/mailman/listinfo/python-list
Re: Function for examine content of directory
On 06/09/12 15:56, Tigerstyle wrote: Hi guys, I'm trying to write a module containing a function to examine the contents of the current working directory and print out a count of how many files have each extension (.txt, .doc, etc.) This is the code so far: -- import os path = v:\\workspace\\Python2_Homework03\\src\\ dirs = os.listdir( path ) filenames = {this.txt, that.txt, the_other.txt,this.doc,that.doc,this.pdf,first.txt,that.pdf} extensions = [] Try using a set here instead of a list: extensions = set() for filename in filenames: f = open(filename, w) f.write(Some text\n) f.close() name , ext = os.path.splitext(f.name) extensions.append(ext) and use: extensions.add(ext) This should take care of duplicates for you. Regards, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: asking
On 22/08/12 03:57, mingqiang hu wrote: can I use just one statement to figure out if substring “a” ,b c are in string adfbdfc ? not use the statement like (a in adfbdfc) or ( b in adfbdfc) or (c in adfbdfc ) ,because if I have lots of substring, this could sucks This might not be the most efficient way, but: set(abc) = set(adfbdfc) True set(abce) = set(adfbdfc) False If you want to check for substrings longer than one character, this won't work. A solution then is to define a custom function: def all_in(string, substrings): for substring in substrings: if substring not in string: return False return True Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: asking
Oops, hopefully this with indent correctly: def all_in(string, substrings): for substring in substrings: if substring not in string: return False return True -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for a neat solution to a nested loop problem
The function range can be called with more than one argument. For example: for i in range(N, N + 10): for j in range(M, M + 100): do_something(i, j) You can also call range with 3 arguments, if want a step size different to 1: for k in range(2, 11, 3): print(k) 2 5 8 Hope this is clear, Ian On 06/08/12 16:52, Tom P wrote: consider a nested loop algorithm - for i in range(100): for j in range(100): do_something(i,j) Now, suppose I don't want to use i = 0 and j = 0 as initial values, but some other values i = N and j = M, and I want to iterate through all 10,000 values in sequence - is there a neat python-like way to this? I realize I can do things like use a variable for k in range(1): and then derive values for i and j from k, but I'm wondering if there's something less clunky. -- http://mail.python.org/mailman/listinfo/python-list
Re: My first ever Python program, comments welcome
On 21/07/12 20:08, Lipska the Kat wrote: Greetings Pythoners A short while back I posted a message that described a task I had set myself. I wanted to implement the following bash shell script in Python Here's the script sort -nr $1 | head -${2:-10} this script takes a filename and an optional number of lines to display and sorts the lines in numerical order, printing them to standard out. if no optional number of lines are input the script prints 10 lines Here's the file. 50Parrots 12Storage Jars 6Lemon Currys 2Pythons 14Spam Fritters 23Flying Circuses 1Meaning Of Life 123Holy Grails 76Secret Policemans Balls 8Something Completely Differents 12Lives of Brian 49Spatulas ... and here's my very first attempt at a Python program I'd be interested to know what you think, you can't hurt my feelings just be brutal (but fair). There is very little error checking as you can see and I'm sure you can crash the program easily. 'Better' implementations most welcome #! /usr/bin/env python3.2 import fileinput from sys import argv from operator import itemgetter l=[] t = tuple What is this line supposed to do? If you're trying to make an empty tuple, you can write: t = () But I don't think this is needed at all. filename=argv[1] lineCount=10 with fileinput.input(files=(filename)) as f: for line in f: t=(line.split('\t')) t[0]=int(t[0]) l.append(t) l=sorted(l, key=itemgetter(0)) try: inCount = int(argv[2]) lineCount = inCount I don't think you need to split this into two lines here. try: lineCount = int(argv[2]) should work. except IndexError: #just catch the error and continue None I would use pass instead of None here - I want to do nothing rather than create a None object. for c in range(lineCount): t=l[c] print(t[0], t[1], sep='\t', end='') Thanks Lipska My only other point is that you might find it helpful to use slightly more verbose names than l or t - its not immediately obvious to the reader what these are intended to represent. Regards, Ian -- http://mail.python.org/mailman/listinfo/python-list