title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
calculate exponential moving average in python
488,670
14
2009-01-28T18:01:44Z
488,700
8
2009-01-28T18:12:07Z
[ "python", "signal-processing", "average", "digital-filter" ]
I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this? I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not l...
I did a bit of googling and I found the following sample code (http://osdir.com/ml/python.matplotlib.general/2005-04/msg00044.html): ``` def ema(s, n): """ returns an n period exponential moving average for the time series s s is a list ordered from oldest (index 0) to most recent (index -1) n...
calculate exponential moving average in python
488,670
14
2009-01-28T18:01:44Z
488,941
15
2009-01-28T19:15:34Z
[ "python", "signal-processing", "average", "digital-filter" ]
I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this? I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not l...
EDIT: It seems that [`mov_average_expw()`](http://www.scipy.org/scipy/scikits/browser/trunk/timeseries/scikits/timeseries/lib/moving_funcs.py) function from [scikits.timeseries.lib.moving\_funcs](http://pytseries.sourceforge.net/lib/moving_funcs.html) submodule from [SciKits](http://scikits.appspot.com/) (add-on toolki...
Given an rpm package name, query the yum database for updates
489,113
5
2009-01-28T20:12:07Z
490,314
7
2009-01-29T02:36:40Z
[ "python", "rpm", "yum" ]
I was imagining a 3-line Python script to do this but the yum Python API is impenetrable. Is this even possible? Is writing a wrapper for 'yum list package-name' the only way to do this?
<http://fpaste.org/paste/2453> and there are many examples of the yum api and some guides to getting started with it here: <http://yum.baseurl.org/#DeveloperDocumentationExamples>
Python super() raises TypeError
489,269
98
2009-01-28T20:47:10Z
489,278
121
2009-01-28T20:48:26Z
[ "python", "super" ]
In Python 2.5.2, the following code raises a TypeError: ``` >>> class X: ... def a(self): ... print "a" ... >>> class Y(X): ... def a(self): ... super(Y,self).a() ... print "b" ... >>> c = Y() >>> c.a() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, i...
The reason is that super() only operates on new-style classes, which in the 2.x series means extending from object.
Python super() raises TypeError
489,269
98
2009-01-28T20:47:10Z
500,110
13
2009-02-01T03:23:05Z
[ "python", "super" ]
In Python 2.5.2, the following code raises a TypeError: ``` >>> class X: ... def a(self): ... print "a" ... >>> class Y(X): ... def a(self): ... super(Y,self).a() ... print "b" ... >>> c = Y() >>> c.a() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, i...
In addition, don't use super() unless you have to. It's not the general-purpose "right thing" to do with new-style classes that you might suspect. There are times when you're expecting multiple inheritance and you might possibly want it, but until you know the hairy details of the MRO, best leave it alone and stick to...
Why am I getting the following error in Python "ImportError: No module named py"?
489,497
11
2009-01-28T21:37:27Z
489,503
26
2009-01-28T21:39:36Z
[ "python" ]
I'm a Python newbie, so bear with me :) I created a file called test.py with the contents as follows: ``` test.py import sys print sys.platform print 2 ** 100 ``` I then ran `import test.py` file in the interpreter to follow an example in my book. When I do this, I get the output with the import error on the end. `...
Instead of: ``` import test.py ``` simply write: ``` import test ``` This assumes test.py is in the same directory as the file that imports it.
Locking a file in Python
489,861
81
2009-01-28T23:20:03Z
490,032
9
2009-01-29T00:24:06Z
[ "python", "file-locking" ]
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
Coordinating access to a single file at the OS level is fraught with all kinds of issues that you probably don't want to solve. Your best bet is have a separate process that coordinates read/write access to that file.
Locking a file in Python
489,861
81
2009-01-28T23:20:03Z
490,102
25
2009-01-29T01:01:50Z
[ "python", "file-locking" ]
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
There is a cross-platform file locking module here: [Portalocker](https://pypi.python.org/pypi/portalocker) Although as Kevin says, writing to a file from multiple processes at once is something you want to avoid if at all possible. If you can shoehorn your problem into a database, you could use SQLite. It supports c...
Locking a file in Python
489,861
81
2009-01-28T23:20:03Z
490,919
7
2009-01-29T08:46:38Z
[ "python", "file-locking" ]
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
Locking is platform and device specific, but generally, you have a few options: 1. use flock(), or equivilent (if your os supports it). This is advisory locking, unless you check for the lock, its ignored. 2. Use a lock-copy-move-unlock methodology, where you copy the file, write the new data, then move it (move, not ...
Locking a file in Python
489,861
81
2009-01-28T23:20:03Z
498,505
65
2009-01-31T08:30:04Z
[ "python", "file-locking" ]
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
Alright, so I ended up going with the code I wrote [here, on my website](http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-python/) ([also available on GitHub](https://github.com/dmfrey/FileLock)). I can use it in the following fashion: ``` from filelock import FileLock with FileLock("myfile.t...
Locking a file in Python
489,861
81
2009-01-28T23:20:03Z
3,343,885
15
2010-07-27T13:04:47Z
[ "python", "file-locking" ]
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
I prefer **[lockfile](https://github.com/smontanaro/pylockfile)** — Platform-independent file locking
Convert list of ints to one number?
489,999
29
2009-01-29T00:16:23Z
490,020
92
2009-01-29T00:21:26Z
[ "python" ]
I have a list of integers that I would like to convert to one number like: ``` numList = [1, 2, 3] num = magic(numList) print num, type(num) >>> 123, <type 'int'> ``` What is the best way to implement the *magic* function? **EDIT** I did find [this](http://bytes.com/groups/python/722951-int-str-list-elements), b...
``` # Over-explaining a bit: def magic(numList): # [1,2,3] s = map(str, numList) # ['1','2','3'] s = ''.join(s) # '123' s = int(s) # 123 return s # How I'd probably write it: def magic(numList): s = ''.join(map(str, numList)) return int(s) # As a one-liner n...
Convert list of ints to one number?
489,999
29
2009-01-29T00:16:23Z
490,031
31
2009-01-29T00:23:42Z
[ "python" ]
I have a list of integers that I would like to convert to one number like: ``` numList = [1, 2, 3] num = magic(numList) print num, type(num) >>> 123, <type 'int'> ``` What is the best way to implement the *magic* function? **EDIT** I did find [this](http://bytes.com/groups/python/722951-int-str-list-elements), b...
Two solutions: ``` >>> nums = [1, 2, 3] >>> magic = lambda nums: int(''.join(str(i) for i in nums)) # Generator exp. >>> magic(nums) 123 >>> magic = lambda nums: sum(digit * 10 ** (len(nums) - 1 - i) # Summation ... for i, digit in enumerate(nums)) >>> magic(nums) 123 ``` The `map`-oriented solution actually come...
split a multi-page pdf file into multiple pdf files with python?
490,195
20
2009-01-29T01:35:48Z
490,203
46
2009-01-29T01:38:47Z
[ "python", "pdf" ]
I'd like to take a multi-page pdf file and create separate pdf files per page. I've downloaded [reportlab](http://www.reportlab.org/index.html) and have browsed the documentation, but it seems aimed at pdf generation, I haven't yet seen anything about processing pdf's themselves. Is there an easy way to do this in py...
pyPdf can handle this nicely (c.f. <http://pybrary.net/pyPdf/> ) ``` from pyPdf import PdfFileWriter, PdfFileReader inputpdf = PdfFileReader(open("document.pdf", "rb")) for i in xrange(inputpdf.numPages): output = PdfFileWriter() output.addPage(inputpdf.getPage(i)) with open("document-page%s.pdf" % i, "w...
What is the most pythonic way to make a bound method act like a function?
490,429
3
2009-01-29T03:55:06Z
490,437
8
2009-01-29T03:58:53Z
[ "python", "function", "methods", "closures" ]
I'm using a Python API that expects me to pass it a function. However, for various reasons, I want to pass it a method, because I want the function to behave different depending on the instance it belongs to. If I pass it a method, the API will not call it with the correct 'self' argument, so I'm wondering how to turn ...
Will passing in the method bound to a instance work? If so, you don't have to do anything special. ``` In [2]: class C(object): ...: def method(self, a, b, c): ...: print a, b, c ...: ...: In [3]: def api_function(a_func): ...: a_func("One Fish", "Two Fish", "Blue Fish") ...: ...:...
django-cart or Satchmo?
490,439
23
2009-01-29T04:00:49Z
490,534
26
2009-01-29T05:04:35Z
[ "python", "django", "e-commerce", "satchmo" ]
I'm looking to implement a very basic shopping cart. [Satchmo](http://www.satchmoproject.com/) seems to install a **lot** of applications and extra stuff that I don't need. I've heard others mention [django-cart](http://code.google.com/p/django-cart/). Has anyone tried this Django app (django-cart)? Anything to watch f...
Well if you want to use django-cart you should view it as a starting point for developing your own. The last commit (r4) for the project was November 2006. By comparison, the last commit (r1922) to Satchmo was a couple of hours ago. With Satchmo you get code that is under active development and actually used by real ...
Regex replace (in Python) - a simpler way?
490,597
42
2009-01-29T05:43:24Z
490,609
18
2009-01-29T05:51:21Z
[ "python", "regex" ]
Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like: ``` "(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)" ``` And then concatenate the `start` group with the new data for `replace` and then the `end` group. Is there a better method for this?
Look in the Python [re documentation](http://docs.python.org/library/re.html) for lookaheads `(?=...)` and lookbehinds `(?<=...)` -- I'm pretty sure they're what you want. They match strings, but do not "consume" the bits of the strings they match.
Regex replace (in Python) - a simpler way?
490,597
42
2009-01-29T05:43:24Z
490,616
105
2009-01-29T05:56:21Z
[ "python", "regex" ]
Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like: ``` "(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)" ``` And then concatenate the `start` group with the new data for `replace` and then the `end` group. Is there a better method for this?
``` >>> import re >>> s = "start foo end" >>> s = re.sub("foo", "replaced", s) >>> s 'start replaced end' >>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s) >>> s 'start can use a callable for the replaced text too end' >>> help(re.sub) Help on function sub in module r...
Regex replace (in Python) - a simpler way?
490,597
42
2009-01-29T05:43:24Z
491,966
11
2009-01-29T15:11:48Z
[ "python", "regex" ]
Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like: ``` "(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)" ``` And then concatenate the `start` group with the new data for `replace` and then the `end` group. Is there a better method for this?
The short version is that you *cannot use* variable-width patterns in lookbehinds using Python's `re` module. There is no way to change this: ``` >>> import re >>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz") 'fooquuxbaz' >>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz") Traceback (most recent call last): ...
No code completion and syntax highlighting in Pydev
491,053
12
2009-01-29T09:50:56Z
492,073
21
2009-01-29T15:32:20Z
[ "python", "ide" ]
I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it? Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. I prefer a SciTE kind of editor with similar highlighting a...
To enable code completion, go to Window > Preferences > Pydev > Editor > Code Completion, and check the 'Use Code Completion?' box, as well as the other boxes for what you want to complete on. It seems to take a second to load, the first time it has to complete something. Syntax coloring should just work by default. R...
No code completion and syntax highlighting in Pydev
491,053
12
2009-01-29T09:50:56Z
1,836,524
8
2009-12-02T23:07:53Z
[ "python", "ide" ]
I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it? Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. I prefer a SciTE kind of editor with similar highlighting a...
The typical reason that code completion doesn't work under PyDev is that the libraries aren't in the PYTHONPATH. If you go into the Project Properties, and setup PyDev PYTHONPATH preferences to include the places where the code you are trying to complete lives, it will work just fine... Project > Properties > PyDev-PY...
How can I pass a filename as a parameter into my module?
491,085
5
2009-01-29T10:04:13Z
491,189
14
2009-01-29T10:50:05Z
[ "python", "command-line", "parameters", "module" ]
I have the following code in .py file: ``` import re regex = re.compile( r"""ULLAT:\ (?P<ullat>-?[\d.]+).*? ULLON:\ (?P<ullon>-?[\d.]+).*? LRLAT:\ (?P<lrlat>-?[\d.]+)""", re.DOTALL|re.VERBOSE) ``` I have the data in .txt file as a sequence: ``` QUADNAME: rockport_colony_SD RESOLUTION: 10 ULLAT: 43.625 U...
You need to read the file in and then search the contents using the regular expression. The sys module contains a list, argv, which contains all the command line parameters. We pull out the second one (the first is the file name used to run the script), open the file, and then read in the contents. ``` import re impor...
Python: Problem with local modules shadowing global modules
491,705
9
2009-01-29T14:04:51Z
491,813
8
2009-01-29T14:33:14Z
[ "python" ]
I've got a package set up like so: ``` packagename/ __init__.py numbers.py tools.py ...other stuff ``` Now inside `tools.py`, I'm trying to import the standard library module `fractions`. However, the `fractions` module itself imports the `numbers` module, which is supposed to be the one in the standa...
[absolute and relative imports](http://www.python.org/dev/peps/pep-0328/) can be used since python2.5 (with `__future__` import) and seem to be what you're looking for.
Unicode (utf8) reading and writing to files in python
491,921
189
2009-01-29T15:01:15Z
491,967
69
2009-01-29T15:11:59Z
[ "python", "unicode", "utf-8", "io" ]
I'm having some brain failure in understanding reading and writing text to a file (Python 2.4). ``` # the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) ``` > ("u'Capit\xe1n'", "'Capit\xc3\xa1n'") ``` print ss, ss8 print >> open('f1','w'), ss8 >>> file('f1').r...
In the notation ``` u'Capit\xe1n\n' ``` the "\xe1" represents just one byte. "\x" tells you that "e1" is in hexadecimal. When you write ``` Capit\xc3\xa1n ``` into your file you have "\xc3" in it. Those are 4 bytes and in your code you read them all. You can see this when you display them: ``` >>> open('f2').read(...
Unicode (utf8) reading and writing to files in python
491,921
189
2009-01-29T15:01:15Z
493,152
12
2009-01-29T20:01:27Z
[ "python", "unicode", "utf-8", "io" ]
I'm having some brain failure in understanding reading and writing text to a file (Python 2.4). ``` # the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) ``` > ("u'Capit\xe1n'", "'Capit\xc3\xa1n'") ``` print ss, ss8 print >> open('f1','w'), ss8 >>> file('f1').r...
So, I've found a solution for what I'm looking for, which is: ``` print open('f2').read().decode('string-escape').decode("utf-8") ``` There are some unusual codecs that are useful here. This particular reading allows one to take utf-8 representations from within python, copy them into an ascii file, and have them be ...
Unicode (utf8) reading and writing to files in python
491,921
189
2009-01-29T15:01:15Z
844,443
468
2009-05-10T00:45:58Z
[ "python", "unicode", "utf-8", "io" ]
I'm having some brain failure in understanding reading and writing text to a file (Python 2.4). ``` # the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) ``` > ("u'Capit\xe1n'", "'Capit\xc3\xa1n'") ``` print ss, ss8 print >> open('f1','w'), ss8 >>> file('f1').r...
Rather than mess with the encode, decode methods I find it easier to use the open method from the codecs module. ``` >>>import codecs >>>f = codecs.open("test", "r", "utf-8") ``` Then after calling f's read() function, an encoded unicode object is returned. ``` >>>f.read() u'Capit\xe1l\n\n' ``` If you know the enco...
Unicode (utf8) reading and writing to files in python
491,921
189
2009-01-29T15:01:15Z
9,200,843
12
2012-02-08T20:24:46Z
[ "python", "unicode", "utf-8", "io" ]
I'm having some brain failure in understanding reading and writing text to a file (Python 2.4). ``` # the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) ``` > ("u'Capit\xe1n'", "'Capit\xc3\xa1n'") ``` print ss, ss8 print >> open('f1','w'), ss8 >>> file('f1').r...
``` # -*- encoding: utf-8 -*- # converting a unknown formatting file in utf-8 import codecs import commands file_location = "jumper.sub" file_encoding = commands.getoutput('file -b --mime-encoding %s' % file_location) file_stream = codecs.open(file_location, 'r', file_encoding) file_output = codecs.open(file_locati...
Unicode (utf8) reading and writing to files in python
491,921
189
2009-01-29T15:01:15Z
25,378,530
11
2014-08-19T08:09:28Z
[ "python", "unicode", "utf-8", "io" ]
I'm having some brain failure in understanding reading and writing text to a file (Python 2.4). ``` # the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) ``` > ("u'Capit\xe1n'", "'Capit\xc3\xa1n'") ``` print ss, ss8 print >> open('f1','w'), ss8 >>> file('f1').r...
Actually this is worked for me for reading a file with utf-8 encodeing in Py 3.2 ``` import codecs f = codecs.open('file_name.txt', 'r', 'UTF-8') for line in f: print(line) ```
How do I use ctypes to set a library's extern function pointer to a Python callback function?
492,377
3
2009-01-29T16:31:41Z
492,640
9
2009-01-29T17:39:14Z
[ "python", "ctypes" ]
Some C libraries export function pointers such that the user of the library sets that function pointer to the address of their own function to implement a hook or callback. In this example library `liblibrary.so`, how do I set library\_hook to a Python function using ctypes? library.h: ``` typedef int exported_funct...
This is tricky in ctypes because ctypes function pointers do not implement the `.value` property used to set other pointers. Instead, cast your callback function and the extern function pointer to `void *` with the `c_void_p` function. After setting the function pointer as `void *` as shown, C can call your Python func...
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
492,399
282
2009-01-29T16:37:18Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
EDIT: Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search&replace to replace all tabs with a few spaces. Try this: ``` import sys def Factorial(n): # return factorial result = 1 for i in range (1,n): result = result * i print "factorial is ",resu...
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
492,419
26
2009-01-29T16:41:15Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
Are you sure you are not mixing tabs and spaces in your indentation white space? (That will cause that error.) Note, it is recommended that you don't use tabs in Python code. See the [style guide](http://www.python.org/dev/peps/pep-0008/). You should configure Notepad++ to insert spaces for tabs.
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
492,437
12
2009-01-29T16:45:19Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
Whenever I've encountered this error, it's because I've somehow mixed up tabs and spaces in my editor.
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
513,524
97
2009-02-04T21:50:28Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
To easily check for problems with tabs/spaces you can actually do this: ``` python -m tabnanny yourfile.py ``` or you can just set up your editor correctly of course :-)
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
17,091,012
7
2013-06-13T15:26:00Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
If you use Python's IDLE editor you can do as it suggests in one of similar error messages: 1) select all, e.g. Ctrl + A 2) Go to Format -> Untabify Region 3) Double check your indenting is still correct, save and rerun your program. I'm using Python 2.5.4
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
23,540,812
86
2014-05-08T11:44:49Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
**IMPORTANT**: ***Spaces are the preferred method*** - see PEP008 [Indentation](https://www.python.org/dev/peps/pep-0008/#indentation) and [Tabs or Spaces?](https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces). (Thanks to @Siha for this.) For `Sublime Text` users: Set `Sublime Text` to use tabs for indentation: ...
Setting the correct encoding when piping stdout in Python
492,483
224
2009-01-29T16:57:59Z
492,711
120
2009-01-29T18:03:18Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this: ``` # -*- coding: utf-8 -*- print u"åäö" ``` will work fine when run normally, but fail with: > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in p...
Your code works when run in an script because Python encodes the output to whatever encoding your terminal application is using. If you are piping you must encode it yourself. A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send. ``` # -*- coding: utf-8 -*- print u"åä...
Setting the correct encoding when piping stdout in Python
492,483
224
2009-01-29T16:57:59Z
1,169,209
129
2009-07-23T02:05:58Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this: ``` # -*- coding: utf-8 -*- print u"åäö" ``` will work fine when run normally, but fail with: > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in p...
First, regarding this solution: ``` # -*- coding: utf-8 -*- print u"åäö".encode('utf-8') ``` It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone. A better solution is to change **`sys.stdout`** at the start of your program, to encode with a selected en...
Setting the correct encoding when piping stdout in Python
492,483
224
2009-01-29T16:57:59Z
4,027,726
81
2010-10-26T20:30:35Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this: ``` # -*- coding: utf-8 -*- print u"åäö" ``` will work fine when run normally, but fail with: > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in p...
You may want to try changing the environment variable "PYTHONIOENCODING" to "utf\_8." I have written a [page on my ordeal with this problem](http://daveagp.wordpress.com/2010/10/26/what-a-character/). Tl;dr of the blog post: ``` import sys, locale, os print(sys.stdout.encoding) print(sys.stdout.isatty()) print(locale...
Setting the correct encoding when piping stdout in Python
492,483
224
2009-01-29T16:57:59Z
6,362,647
38
2011-06-15T18:40:18Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this: ``` # -*- coding: utf-8 -*- print u"åäö" ``` will work fine when run normally, but fail with: > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in p...
``` export PYTHONIOENCODING=utf-8 ``` do the job, but can't set it on python itself ... what we can do is verify if isn't setting and tell the user to set it before call script with : ``` if __name__ == '__main__': if (sys.stdout.encoding is None): print >> sys.stderr, "please set python env PYTHONIOENCO...
Timeout on a function call
492,519
95
2009-01-29T17:08:29Z
494,273
92
2009-01-30T02:14:04Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
I'm calling a function in Python which I know may stall and force me to restart the script. How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
You may use the [signal](http://docs.python.org/library/signal.html) package if you are running on UNIX: ``` In [1]: import signal # Register an handler for the timeout In [2]: def handler(signum, frame): ...: print "Forever is over!" ...: raise Exception("end of time") ...: # This function *may* r...
Timeout on a function call
492,519
95
2009-01-29T17:08:29Z
13,821,695
26
2012-12-11T13:41:31Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
I'm calling a function in Python which I know may stall and force me to restart the script. How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
I have a different proposal which is a pure function (with the same API as the threading suggestion) and seems to work fine (based on suggestions on this thread) ``` def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None): import signal class TimeoutError(Exception): pass def hand...
Timeout on a function call
492,519
95
2009-01-29T17:08:29Z
14,924,210
58
2013-02-17T18:00:10Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
I'm calling a function in Python which I know may stall and force me to restart the script. How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
You can use `multiprocessing.Process` to do exactly that. **Code** ``` import multiprocessing import time # bar def bar(): for i in range(100): print "Tick" time.sleep(1) if __name__ == '__main__': # Start bar as a process p = multiprocessing.Process(target=bar) p.start() # Wait...
Timeout on a function call
492,519
95
2009-01-29T17:08:29Z
31,667,005
10
2015-07-28T03:43:52Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
I'm calling a function in Python which I know may stall and force me to restart the script. How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
> # How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it? I posted a [gist](https://gist.github.com/aaronchall/6331661fe0185c30a0b4) that solves this question/problem with a decorator and a `threading.Timer`. Here it is with a breakdown. ## Imports and set...
Timeout on a function call
492,519
95
2009-01-29T17:08:29Z
35,139,284
14
2016-02-01T20:02:32Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
I'm calling a function in Python which I know may stall and force me to restart the script. How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
I ran across this thread when searching for a timeout call on unit tests. I didn't find anything simple in the answers or 3rd party packages so I wrote the decorator below you can drop right into code: ``` import multiprocessing.pool import functools def timeout(max_timeout): """Timeout decorator, parameter in se...
Reversing a regular expression in Python
492,716
33
2009-01-29T18:05:22Z
496,603
10
2009-01-30T18:27:24Z
[ "python", "regex" ]
I want to reverse a regular expression. I.e. given a regular expression, I want to produce *any* string that will match that regex. I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :) I'm usi...
I don't know of any module to do this. If you don't find anything like this in the Cookbook or PyPI, you could try rolling your own, using the (undocumented) re.sre\_parse module. This might help getting you started: ``` In [1]: import re In [2]: a = re.sre_parse.parse("[abc]+[def]*\d?z") In [3]: a Out[3]: [('max_re...
Reversing a regular expression in Python
492,716
33
2009-01-29T18:05:22Z
502,074
15
2009-02-02T02:59:15Z
[ "python", "regex" ]
I want to reverse a regular expression. I.e. given a regular expression, I want to produce *any* string that will match that regex. I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :) I'm usi...
Although I don't see much sense in this, here goes: ``` import re import string def traverse(tree): retval = '' for node in tree: if node[0] == 'any': retval += 'x' elif node[0] == 'at': pass elif node[0] in ['min_repeat', 'max_repeat']: retval += tr...
Reversing a regular expression in Python
492,716
33
2009-01-29T18:05:22Z
9,118,086
16
2012-02-02T18:45:41Z
[ "python", "regex" ]
I want to reverse a regular expression. I.e. given a regular expression, I want to produce *any* string that will match that regex. I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :) I'm usi...
Somebody else had a similar (duplicate?) question [here](http://stackoverflow.com/questions/4627464/generate-a-string-that-matches-a-regex-in-python), and I'd like to offer a little helper library for [generating random strings with Python](https://bitbucket.org/leapfrogdevelopment/rstr/) that I've been working on. It...
python: restarting a loop
492,860
9
2009-01-29T18:37:51Z
492,864
9
2009-01-29T18:38:57Z
[ "python", "loops" ]
i have: ``` for i in range(2,n): if(something): do something else: do something else i = 2 **restart the loop ``` But that doesn't seem to work. Is there a way to restart that loop? Thanks
Changing the index variable `i` from within the loop is unlikely to do what you expect. You may need to use a `while` loop instead, and control the incrementing of the loop variable yourself. Each time around the `for` loop, `i` is reassigned with the next value from `range()`. So something like: ``` i = 2 while i < n...
python: restarting a loop
492,860
9
2009-01-29T18:37:51Z
492,877
17
2009-01-29T18:42:22Z
[ "python", "loops" ]
i have: ``` for i in range(2,n): if(something): do something else: do something else i = 2 **restart the loop ``` But that doesn't seem to work. Is there a way to restart that loop? Thanks
You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer. perhaps a: ``` i=2 while i < n: if something: do something i += 1 else: do something else i = 2 #restart the loop ```
I don't understand slicing with negative bounds in Python. How is this supposed to work?
493,046
6
2009-01-29T19:31:48Z
493,057
18
2009-01-29T19:34:38Z
[ "python", "slice" ]
I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter: ``` >>> s = 'spam' >>> s[:-1] 'spa' ``` Why does slicing with no beginning bound and a `'-1'` return every element except the last one? Is calling `s[0:-1]` logical...
Yes, calling `s[0:-1]` is exactly the same as calling `s[:-1]`. Using a negative number as an index in python returns the nth element from the right-hand side of the list (as opposed to the usual left-hand side). so if you have a list as so: ``` myList = ['a', 'b', 'c', 'd', 'e'] print myList[-1] # prints 'e' ``` t...
Is there a way to convert number words to Integers?
493,174
24
2009-01-29T20:07:43Z
493,788
56
2009-01-29T22:32:54Z
[ "python", "string", "text", "integer", "numbers" ]
I need to convert `one` into `1`, `two` into `2` and so on. Is there a way to do this with a library or a class or anything?
The majority of this code is to set up the numwords dict, which is only done on the first call. ``` def text2int(textnum, numwords={}): if not numwords: units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",...
In Django, how do you retrieve data from extra fields on many-to-many relationships without an explicit query for it?
493,304
15
2009-01-29T20:38:21Z
493,454
9
2009-01-29T21:13:53Z
[ "python", "django", "manytomanyfield" ]
Given a situation in Django 1.0 where you have [extra data on a Many-to-Many relationship](http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany): ``` class Player(models.Model): name = models.CharField(max_length=80) class Team(models.Model): name = models.CharField(max_length=40) play...
So, 15 minutes after asking the question, and I found my own answer. Using `dir(Team)`, I can see another generated attribute named `teamplayer_set` (it also exists on Player). ``` t = Team.objects.get(pk=168) for x in t.teamplayer_set.all(): if x.captain: print "%s (Captain)" % (x.player.name) else: prin...
Python: For each list element apply a function across the list
493,367
23
2009-01-29T20:53:15Z
493,423
40
2009-01-29T21:07:47Z
[ "python", "algorithm", "list", "list-comprehension" ]
Given `[1,2,3,4,5]`, how can I do something like ``` 1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 ``` I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return `(1,5)`. So basic...
You can do this using [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) and [min()](http://docs.python.org/library/functions.html) (Python 3.0 code): ``` >>> nums = [1,2,3,4,5] >>> [(x,y) for x in nums for y in nums] [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), ...
Python: For each list element apply a function across the list
493,367
23
2009-01-29T20:53:15Z
493,473
9
2009-01-29T21:17:20Z
[ "python", "algorithm", "list", "list-comprehension" ]
Given `[1,2,3,4,5]`, how can I do something like ``` 1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 ``` I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return `(1,5)`. So basic...
If I'm correct in thinking that you want to find the minimum value of a function for all possible pairs of 2 elements from a list... ``` l = [1,2,3,4,5] def f(i,j): return i+j # Prints min value of f(i,j) along with i and j print min( (f(i,j),i,j) for i in l for j in l) ```
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
493,399
1,118
2009-01-29T21:01:43Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ```...
## General way ``` import sys sys.stdout.write('.') ``` You may also need to call ``` sys.stdout.flush() ``` to ensure `stdout` is flushed immediately. ## Python 2.6+ From Python 2.6 you can import the `print` function from Python 3: ``` from __future__ import print_function ``` This allows you to use the Pytho...
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
493,422
14
2009-01-29T21:07:36Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ```...
The new (as of Python 3.0) print function has an optional end parameter that let's you modify the ending character. There's also sep for separator.
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
493,500
148
2009-01-29T21:24:58Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ```...
*Note: The title of this question used to be something like "How to printf in python?"* Since people may come here looking for it based on the title, Python also supports printf-style substitution: ``` >>> strings = [ "one", "two", "three" ] >>> >>> for i in xrange(3): ... print "Item %d: %s" % (i, strings[i]) .....
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
4,348,063
31
2010-12-03T17:16:00Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ```...
This is not the answer to the question in the title, but it's the answer on how to print on the same line: ``` import sys for i in xrange(0,10): sys.stdout.write(".") sys.stdout.flush() ```
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
5,071,123
67
2011-02-21T20:50:30Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ```...
Use the python3-style print function for python2.6+ *(will also break any existing keyworded print statements in the same file.)* ``` # for python2 to use the print() function, removing the print keyword from __future__ import print_function for x in xrange(10): print('.', end='') ``` To not ruin all your python2...
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
11,685,717
166
2012-07-27T10:09:57Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ```...
It should be as simple as described at this link by Guido Van Rossum: Re: How does one print without a c/r ? <http://www.python.org/search/hypermail/python-1992/0115.html> > Is it possible to print something but not automatically have a > carriage return appended to it ? Yes, append a comma after the last argument ...
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
24,685,004
13
2014-07-10T19:45:40Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ```...
You can just add `,` in the end of `print` function so it won't print on new line.
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
30,881,087
7
2015-06-17T01:55:02Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ```...
Using functools.partial to create a new function called printf ``` >>> import functools >>> printf = functools.partial(print, end="") >>> printf("Hello world\n") Hello world ``` Easy way to wrap a function with default parameters.
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
493,831
170
2009-01-29T22:48:38Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
Because the `join()` method is in the string class, instead of the list class? I agree it looks funny. See <http://www.faqs.org/docs/diveintopython/odbchelper_join.html>: > **Historical note.** When I first learned > Python, I expected join to be a method > of a list, which would take the > delimiter as an argument....
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
493,842
672
2009-01-29T22:51:18Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
It's because any iterable can be joined, not just lists, but the result and the "joiner" are always strings. E.G: ``` import urllib2 print '\n############\n'.join( urllib2.urlopen('http://data.stackexchange.com/users/7095')) ```
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
493,843
10
2009-01-29T22:51:45Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
Primarily because the result of a `someString.join()` is a string. The sequence (list or tuple or whatever) doesn't appear in the result, just a string. Because the result is a string, it makes sense as a method of a string.
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
493,884
40
2009-01-29T23:03:45Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
I agree that it's counterintuitive at first, but there's a good reason. Join can't be a method of a list because: * it must work for different iterables too (tuples, generators, etc.) * it must have different behavior between different types of strings. There are actually two join methods (Python 3.0): ``` >>> b"".j...
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
494,320
15
2009-01-30T02:43:51Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
Think of it as the natural orthogonal operation to split. I understand why it is applicable to anything iterable and so can't easily be implemented *just* on list. For readability, I'd like to see it in the language but I don't think that is actually feasible - if iterability were an interface then it could be added ...
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
12,662,361
117
2012-09-30T15:21:16Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
This was discussed in the [String methods... finally](http://mail.python.org/pipermail/python-dev/1999-June/095366.html) thread in the Python-Dev achive, and was accepted by Guido. This thread began in Jun 1999, and `str.join` was included in Python 1.6 (which supported Unicode) was released in Sep 2000. Python 2.0 (su...
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
29,617,379
14
2015-04-14T00:45:18Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
> # Why is it `string.join(list)` instead of `list.join(string)`? This is because `join` is a "string" method! It creates a string from any iterable. If we stuck the method on lists, what about when we have iterables that aren't lists? What if you have a tuple of strings? If this were a `list` method, you would have ...
Uses for Dynamic Languages
493,973
8
2009-01-29T23:42:47Z
494,055
15
2009-01-30T00:23:01Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compil...
In theory, there's nothing that dynamic languages can do and static languages can't. Smart people put a lot of work into making *very good* dynamic languages, leading to a perception at the moment that dynamic languages are ahead while static ones need to catch up. In time, this will swing the other way. Already vario...
How can I disable quoting in the Python 2.4 CSV reader?
494,054
10
2009-01-30T00:22:40Z
494,126
12
2009-01-30T01:05:04Z
[ "python", "csv" ]
I am writing a Python utility that needs to parse a large, regularly-updated CSV file I don't control. The utility must run on a server with only Python 2.4 available. The CSV file does not quote field values at all, but the [Python 2.4 version of the csv library](http://www.python.org/doc/2.4.3/lib/csv-fmt-params.html...
I don't know if python would like/allow it but could you use a non-printable ascii code such as BEL or BS (backspace) These I would think to be extremely rare.
How to write the Fibonacci Sequence in Python
494,594
68
2009-01-30T05:49:13Z
494,636
16
2009-01-30T06:15:45Z
[ "python", "fibonacci", "sequences" ]
I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibona...
The idea behind the Fibonacci sequence is shown in the following Python code: ``` def fib(n): if n == 1: return 1 elif n == 0: return 0 else: return fib(n-1) + fib(n-2) ``` This means that fib is a function that can do one of three things. It defines fib...
How to write the Fibonacci Sequence in Python
494,594
68
2009-01-30T05:49:13Z
499,245
153
2009-01-31T18:01:14Z
[ "python", "fibonacci", "sequences" ]
I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibona...
There is lots of information about the Fibonacci Sequence on [wikipedia](http://en.wikipedia.org/wiki/Fibonacci_number) and on [wolfram](http://mathworld.wolfram.com/FibonacciNumber.html). A lot more than you may need. Anyway it is a good thing to learn how to use these resources to find (quickly if possible) what you ...
How to write the Fibonacci Sequence in Python
494,594
68
2009-01-30T05:49:13Z
24,846,766
24
2014-07-20T02:24:24Z
[ "python", "fibonacci", "sequences" ]
I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibona...
# Efficient Pythonic generator of the Fibonacci sequence I found this question while trying to get the shortest Pythonic generation of this sequence (later realizing I had seen a similar one in a [Python Enhancement Proposal](https://www.python.org/dev/peps/pep-0255/)), and I haven't noticed anyone else coming up with...
How to write the Fibonacci Sequence in Python
494,594
68
2009-01-30T05:49:13Z
26,118,289
7
2014-09-30T10:14:59Z
[ "python", "fibonacci", "sequences" ]
I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibona...
**Time complexity :** The caching feature reduces the normal way of calculating Fibonacci series from **O(2^n)** to **O(n)** by eliminating the repeats in the recursive tree of Fibonacci series : ![enter image description here](http://i.stack.imgur.com/59Rpw.png) **Code :** ``` import sys table = [0]*1000 def Fas...
refactor this dictionary-to-xml converter in python
494,881
3
2009-01-30T08:33:12Z
494,905
9
2009-01-30T08:52:10Z
[ "python", "xml", "dry" ]
It's a small thing, really: I have this function that converts dict objects to xml. Here's the function: ``` def dictToXml(d): from xml.sax.saxutils import escape def unicodify(o): if o is None: return u''; return unicode(o) lines = [] def addDict(node, offset): f...
``` >>> from pyfo import pyfo >>> d = ('site', { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } ) >>> result = pyfo(d, pretty=True, prolog=True, encoding='ascii') >>> print result.encode('ascii', 'xmlcharrefreplace') <?xml version="1.0" encoding="ascii"?> <site> <blogger> Jeff Joel </blogger> <n...
Refactor this Python code to iterate over a container
495,294
3
2009-01-30T12:02:34Z
495,343
19
2009-01-30T12:22:05Z
[ "python", "django", "refactoring", "iterator" ]
Surely there is a better way to do this? ``` results = [] if not queryset is None: for obj in queryset: results.append((getattr(obj,field.attname),obj.pk)) ``` The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I just want result to be set...
``` results = [(getattr(obj, field.attname), obj.pk) for obj in queryset or []] ```
Refactor this Python code to iterate over a container
495,294
3
2009-01-30T12:02:34Z
495,400
8
2009-01-30T12:44:35Z
[ "python", "django", "refactoring", "iterator" ]
Surely there is a better way to do this? ``` results = [] if not queryset is None: for obj in queryset: results.append((getattr(obj,field.attname),obj.pk)) ``` The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I just want result to be set...
How about ``` for obj in (queryset or []): # Do your stuff ``` It is the same as J.F Sebastians suggestion, only not implemented as a list comprehension.
Confusion about global variables in python
495,422
11
2009-01-30T12:56:57Z
495,570
15
2009-01-30T14:01:27Z
[ "python", "global-variables", "python-import" ]
I'm new to python, so please excuse what is probably a pretty dumb question. Basically, I have a single global variable, called \_debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses it. I hav...
There are more problems than just the leading underscore I'm afraid. When you call `my_function()`, it still won't have your `debug` variable in its namespace, unless you import it from `two.py`. Of course, doing that means you'll end up with cyclic dependencies (`one.py -> two.py -> one.py`), and you'll get `NameErr...
Python's version of PHP's time() function
495,595
2
2009-01-30T14:09:29Z
495,610
19
2009-01-30T14:13:19Z
[ "python", "time" ]
I've looked at the [Python Time module](http://docs.python.org/library/time.html) and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time(). Am I simply missing something here or is there a common way to do this that's simply not listed there?
``` import time print int(time.time()) ```
Is there any case where len(someObj) does not call someObj's __len__ function?
496,009
5
2009-01-30T15:58:58Z
496,038
7
2009-01-30T16:07:33Z
[ "python" ]
Is there any case where len(someObj) does not call someObj's `__len__` function? I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where len(someObj) is not the same as someObj.`__len__`().
What kind of speedup did you see? I cannot imagine it was noticeable was it? From <http://mail.python.org/pipermail/python-list/2002-May/147079.html> > in certain situations there is no > difference, but using len() is > preferred for a couple reasons. > > first, it's not recommended to go > calling the `__methods__`...
What's a good way to keep track of class instance variables in Python?
496,582
8
2009-01-30T18:21:13Z
496,656
7
2009-01-30T18:39:58Z
[ "python", "variables" ]
I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a `.h` file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do...
First of all: class attributes, or instance attributes? Or both? =) *Usually* you just add instance attributes in `__init__`, and class attributes in the class definition, often before method definitions... which should probably cover 90% of use cases. If code adds attributes on the fly, it probably (hopefully :-) ha...
What's a good way to keep track of class instance variables in Python?
496,582
8
2009-01-30T18:21:13Z
498,284
9
2009-01-31T04:45:58Z
[ "python", "variables" ]
I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a `.h` file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do...
I would say, the standard practice to avoid this is to *not write classes where you can be 1000 lines away from anything!* Seriously, that's way too much for just about any useful class, especially in a language that is as expressive as Python. Using more of what the Standard Library offers and abstracting away code i...
Progress bar not updating during operation
496,814
7
2009-01-30T19:17:39Z
497,313
12
2009-01-30T21:26:52Z
[ "python", "user-interface", "gtk", "progress-bar", "pygtk" ]
in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests...my...
I'm going to quote the [PyGTK FAQ](http://faq.pygtk.org/index.py?req=show&file=faq23.020.htp): > You have created a progress bar inside a window, then you start running a loop that does some work: ``` while work_left: ...do something... progressbar.set_fraction(...) ``` > You will notice that the window does...
Is there a Python equivalent of Perl's x operator?
497,114
11
2009-01-30T20:27:49Z
497,119
31
2009-01-30T20:29:15Z
[ "python", "perl" ]
In Perl, I can replicate strings with the 'x' operator: ``` $str = "x" x 5; ``` Can I do something similar in Python?
``` >>> "blah" * 5 'blahblahblahblahblah' ```
Python's os.path choking on Hebrew filenames
497,233
13
2009-01-30T21:03:24Z
497,356
14
2009-01-30T21:40:06Z
[ "python", "internationalization", "hebrew" ]
I'm writing a script that has to move some file around, but unfortunately it doesn't seem `os.path` plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory: ![alt text](http://eli.thegreenplace.net/files/temp/hebfilenameshot.p...
Hmm, after [some digging](http://www.amk.ca/python/howto/unicode) it appears that when supplying os.listdir a unicode string, this kinda works: ``` files = os.listdir(u'test_source') for f in files: pf = os.path.join(u'test_source', f) print pf.encode('ascii', 'replace'), os.path.exists(pf) ``` ===> ``` te...
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
497,434
65
2009-01-30T22:02:26Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm ...
If you're deleting multiple non-adjacent items, then what you describe is the best way (and yes, be sure to start from the highest index). If your items are adjacent, you can use the slice assignment syntax: ``` a[2:10] = [] ```
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
497,439
45
2009-01-30T22:05:01Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm ...
Probably not the best solution for this problem: ``` indices = 0, 2 somelist = [i for j, i in enumerate(somelist) if j not in indices] ```
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
497,451
13
2009-01-30T22:09:38Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm ...
As a function: ``` def multi_delete(list_, *args): indexes = sorted(list(args), reverse=True) for index in indexes: del list_[index] return list_ ``` Runs in **n log(n)** time, which should make it the fastest correct solution yet.
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
498,074
9
2009-01-31T02:23:39Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm ...
So, you essentially want to delete multiple elements in one pass? In that case, the position of the next element to delete will be offset by however many were deleted previously. Our goal is to delete all the vowels, which are precomputed to be indices 1, 4, and 7. Note that its important the to\_delete indices are in...
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
500,076
14
2009-02-01T02:55:32Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm ...
As a specialisation of Greg's answer, you can even use extended slice syntax. eg. If you wanted to delete items 0 and 2: ``` >>> a= [0, 1, 2, 3, 4] >>> del a[0:3:2] >>> a [1, 3, 4] ``` This doesn't cover any arbitrary selection, of course, but it can certainly work for deleting any two items.
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
28,697,246
30
2015-02-24T13:36:44Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm ...
For some reason I don't like any of the answers here. Yes, they work, but strictly speaking most of them aren't deleting elements in a list, are they? (But making a copy and then replacing the original one with the edited copy). Why not just delete the higher index first? Is there a reason for this? I would just do: ...
Django workflow when modifying models frequently?
497,654
24
2009-01-30T23:18:54Z
497,687
21
2009-01-30T23:29:45Z
[ "python", "django", "django-models", "workflow", "django-syncdb" ]
as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. 1. Modify the...
Steps 2 & 3 can be done in one step: ``` manage.py reset appname ``` Step 4 is most easily managed, from my understanding, by using [fixtures](http://www.djangoproject.com/documentation/models/fixtures/)
Django workflow when modifying models frequently?
497,654
24
2009-01-30T23:18:54Z
497,696
14
2009-01-30T23:32:02Z
[ "python", "django", "django-models", "workflow", "django-syncdb" ]
as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. 1. Modify the...
This is a job for Django's fixtures. They are convenient because they are database independent and the test harness (and manage.py) have built-in support for them. To use them: 1. Set up your data in your app (call it "foo") using the admin tool 2. Create a fixtures directory in your "foo" app directory 3. Type...
Django workflow when modifying models frequently?
497,654
24
2009-01-30T23:18:54Z
498,092
12
2009-01-31T02:39:00Z
[ "python", "django", "django-models", "workflow", "django-syncdb" ]
as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. 1. Modify the...
Here's what we do. 1. Apps are named with a Schema version number. `appa_2`, `appb_1`, etc. 2. Minor changes don't change the number. 3. Major changes increment the number. Syncdb works. And a "data migration" script can be written. ``` def migrate_appa_2_to_3(): for a in appa_2.SomeThing.objects.all(): ...
Django workflow when modifying models frequently?
497,654
24
2009-01-30T23:18:54Z
636,949
10
2009-03-12T00:33:46Z
[ "python", "django", "django-models", "workflow", "django-syncdb" ]
as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. 1. Modify the...
South is the coolest. Though good ol' reset works best when data doesn't matter. <http://south.aeracode.org/>
IronPython vs. C# for small-scale projects
497,747
8
2009-01-30T23:59:34Z
497,938
11
2009-01-31T01:15:04Z
[ "c#", ".net", "python", "ironpython" ]
I currently use Python for most of my programming projects (mainly rapid development of small programs and prototypes). I'd like to invest time in learning a language that gives me the flexibility to use various Microsoft tools and APIs whenever the opportunity arises. I'm trying to decide between IronPython and C#. Si...
I've built a large-scale application in IronPython bound with C#. It's almost completely seamless. The only things missing in IronPython from the true "python" feel are the C-based libraries (gotta use .NET for those) and IDLE. The language interacts with other .NET languages like a dream... Specifically if you embed...
Python string.join(list) on object array rather than string array
497,765
134
2009-01-31T00:06:07Z
497,773
207
2009-01-31T00:10:58Z
[ "python", "list" ]
In Python, I can do: ``` >>> list = ['a', 'b', 'c'] >>> ', '.join(list) 'a, b, c' ``` Is there any easy way to do the same when I have a list of objects? ``` >>> class Obj: ... def __str__(self): ... return 'name' ... >>> list = [Obj(), Obj(), Obj()] >>> ', '.join(list) Traceback (most recent call last):...
You could use a list comprehension or a generator expression instead: ``` ', '.join([str(x) for x in list]) # list comprehension ', '.join(str(x) for x in list) # generator expression ```
Python string.join(list) on object array rather than string array
497,765
134
2009-01-31T00:06:07Z
497,787
49
2009-01-31T00:16:03Z
[ "python", "list" ]
In Python, I can do: ``` >>> list = ['a', 'b', 'c'] >>> ', '.join(list) 'a, b, c' ``` Is there any easy way to do the same when I have a list of objects? ``` >>> class Obj: ... def __str__(self): ... return 'name' ... >>> list = [Obj(), Obj(), Obj()] >>> ', '.join(list) Traceback (most recent call last):...
The built-in string constructor will automatically call `obj.__str__`: ``` ''.join(map(str,list)) ```
Python element-wise tuple operations like sum
497,885
52
2009-01-31T00:51:48Z
497,894
72
2009-01-31T00:55:01Z
[ "python", "tuples" ]
Is there anyway to get tuple operations in Python to work like this: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (4,4,4) ``` instead of: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (1,2,3,3,2,1) ``` I know it works like that because the `__add__` and `__mul__` methods are defined to work like that. So the only ...
``` import operator tuple(map(operator.add, a, b)) ```