title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Python library for converting files to MP3 and setting their quality | 1,246,131 | <p>I'm trying to find a Python library that would take an audio file (e.g. .ogg, .wav) and convert it into mp3 for playback on a webpage. </p>
<p>Also, any thoughts on setting its quality for playback would be great.</p>
<p>Thank you.</p>
| 8 | 2009-08-07T17:51:39Z | 12,391,523 | <p>I wrote <a href="http://pydub.com" rel="nofollow">a library</a> designed to do that =D </p>
<pre><code>from pydub import AudioSegment
AudioSegment.from_file("/input/file").export("/output/file", format="mp3")
</code></pre>
<p>Easy!</p>
<p>to specify a bitrate, just use the <code>bitrate</code> kwargâ¦</p>
<pre><code>from pydub import AudioSegment
sound = AudioSegment.from_file("/input/file")
sound.export("/output/file", format="mp3", bitrate="128k")
</code></pre>
| 12 | 2012-09-12T15:23:23Z | [
"python",
"audio",
"compression"
] |
Python/mySQL on an Embedded ARM9 Device? | 1,246,235 | <p>I have an application where a small embedded ARM9 device (running Linux) must gather information from sensors and then connect to a remote mySQL database and INSERT the data. I have Python 2.5 running on the ARM9 device fine. I have developed a prototype application in Python 2.5 running on x86 Windows and it connects with mySQL and INSERTS just fine. My confusion in this issue come from working with "mySQL Connect/C" which would have to be cross compiled for the ARM processor before being used. </p>
<ul>
<li>What is the best way to port or move this DB app onto the ARM device?</li>
<li>Are there underlying x86 binaries in supporting libraries that must be cross compiled?</li>
<li>Or, is MySQLdb simply portable across platforms?</li>
</ul>
| 0 | 2009-08-07T18:12:49Z | 1,246,261 | <p>It should compile on ARM just fine, but first you should check that your platform's Linux distribution doesn't simply have packages for MySQL (if it has packages, it probably has those). If there are no packages it should be no big deal to compile it yourself. How's your cross compiler? Or is the platform big enough to host its own?</p>
<p>Maybe you are looking for <a href="http://dev.mysql.com/doc/mysql-sourcebuild-excerpt/5.1/en/installing-source.html" rel="nofollow">http://dev.mysql.com/doc/mysql-sourcebuild-excerpt/5.1/en/installing-source.html</a></p>
| 1 | 2009-08-07T18:18:50Z | [
"python",
"arm",
"embedded"
] |
Python/mySQL on an Embedded ARM9 Device? | 1,246,235 | <p>I have an application where a small embedded ARM9 device (running Linux) must gather information from sensors and then connect to a remote mySQL database and INSERT the data. I have Python 2.5 running on the ARM9 device fine. I have developed a prototype application in Python 2.5 running on x86 Windows and it connects with mySQL and INSERTS just fine. My confusion in this issue come from working with "mySQL Connect/C" which would have to be cross compiled for the ARM processor before being used. </p>
<ul>
<li>What is the best way to port or move this DB app onto the ARM device?</li>
<li>Are there underlying x86 binaries in supporting libraries that must be cross compiled?</li>
<li>Or, is MySQLdb simply portable across platforms?</li>
</ul>
| 0 | 2009-08-07T18:12:49Z | 4,729,963 | <p>I suggest using SQLite. I have an application running Python+SQLite for telemetry purposes and it works like a charm. It's much easier than MySQL.</p>
| 0 | 2011-01-18T22:49:17Z | [
"python",
"arm",
"embedded"
] |
convert string to dict using list comprehension in python | 1,246,444 | <p>I have came across this problem a few times and can't seem to figure out a simple solution.
Say I have a string</p>
<pre><code> string = "a=0 b=1 c=3"
</code></pre>
<p>I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:</p>
<pre><code> list = string.split()
dic = {}
for entry in list:
key, val = entry.split('=')
dic[key] = int(val)
</code></pre>
<p>But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the <code>val</code> can be a string. </p>
<pre><code> dic = dict([entry.split('=') for entry in list])
</code></pre>
<p>However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect.</p>
<pre><code> dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list])
</code></pre>
<p>So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?</p>
| 15 | 2009-08-07T19:00:32Z | 1,246,470 | <p>Do you mean this?</p>
<pre><code>>>> dict( (n,int(v)) for n,v in (a.split('=') for a in string.split() ) )
{'a': 0, 'c': 3, 'b': 1}
</code></pre>
| 27 | 2009-08-07T19:07:15Z | [
"python",
"string",
"dictionary",
"list-comprehension",
"generator-expression"
] |
convert string to dict using list comprehension in python | 1,246,444 | <p>I have came across this problem a few times and can't seem to figure out a simple solution.
Say I have a string</p>
<pre><code> string = "a=0 b=1 c=3"
</code></pre>
<p>I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:</p>
<pre><code> list = string.split()
dic = {}
for entry in list:
key, val = entry.split('=')
dic[key] = int(val)
</code></pre>
<p>But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the <code>val</code> can be a string. </p>
<pre><code> dic = dict([entry.split('=') for entry in list])
</code></pre>
<p>However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect.</p>
<pre><code> dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list])
</code></pre>
<p>So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?</p>
| 15 | 2009-08-07T19:00:32Z | 1,246,585 | <pre><code>from cgi import parse_qsl
text = "a=0 b=1 c=3"
dic = dict((k, int(v)) for k, v in parse_qsl(text.replace(' ', '&')))
print dic
</code></pre>
<p>prints</p>
<pre><code>{'a': 0, 'c': 3, 'b': 1}
</code></pre>
| 1 | 2009-08-07T19:32:29Z | [
"python",
"string",
"dictionary",
"list-comprehension",
"generator-expression"
] |
convert string to dict using list comprehension in python | 1,246,444 | <p>I have came across this problem a few times and can't seem to figure out a simple solution.
Say I have a string</p>
<pre><code> string = "a=0 b=1 c=3"
</code></pre>
<p>I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:</p>
<pre><code> list = string.split()
dic = {}
for entry in list:
key, val = entry.split('=')
dic[key] = int(val)
</code></pre>
<p>But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the <code>val</code> can be a string. </p>
<pre><code> dic = dict([entry.split('=') for entry in list])
</code></pre>
<p>However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect.</p>
<pre><code> dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list])
</code></pre>
<p>So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?</p>
| 15 | 2009-08-07T19:00:32Z | 1,247,057 | <p>I like S.Lott's solution, but I came up with another possibility.<br />
Since you already have a string resembling somehow the way you'd write that, you can just adapt it to python syntax and then eval() it :)</p>
<pre><code>import re
string = "a=0 b=1 c=3"
string2 = "{"+ re.sub('( |^)(?P<id>\w+)=(?P<val>\d+)', ' "\g<id>":\g<val>,', string) +"}"
dict = eval(string2)
print type(string), type(string2), type(dict)
print string, string2, dict
</code></pre>
<p>The regex here is pretty raw and won't catch all the possible python identifiers, but I wanted to keep it simple for simplicity's sake.
Of course if you have control over how the input string is generated, just generate it according to python syntax and eval it away.
BUT of course you should perform additional sanity checks to make sure that no code is injected there!</p>
| -3 | 2009-08-07T21:16:37Z | [
"python",
"string",
"dictionary",
"list-comprehension",
"generator-expression"
] |
convert string to dict using list comprehension in python | 1,246,444 | <p>I have came across this problem a few times and can't seem to figure out a simple solution.
Say I have a string</p>
<pre><code> string = "a=0 b=1 c=3"
</code></pre>
<p>I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:</p>
<pre><code> list = string.split()
dic = {}
for entry in list:
key, val = entry.split('=')
dic[key] = int(val)
</code></pre>
<p>But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the <code>val</code> can be a string. </p>
<pre><code> dic = dict([entry.split('=') for entry in list])
</code></pre>
<p>However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect.</p>
<pre><code> dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list])
</code></pre>
<p>So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?</p>
| 15 | 2009-08-07T19:00:32Z | 1,247,741 | <p>How about a one-liner without list comprehension?</p>
<pre><code> foo="a=0 b=1 c=3"
ans=eval( 'dict(%s)'%foo.replace(' ',',')) )
print ans
{'a': 0, 'c': 3, 'b': 1}
</code></pre>
| 3 | 2009-08-08T01:50:16Z | [
"python",
"string",
"dictionary",
"list-comprehension",
"generator-expression"
] |
convert string to dict using list comprehension in python | 1,246,444 | <p>I have came across this problem a few times and can't seem to figure out a simple solution.
Say I have a string</p>
<pre><code> string = "a=0 b=1 c=3"
</code></pre>
<p>I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:</p>
<pre><code> list = string.split()
dic = {}
for entry in list:
key, val = entry.split('=')
dic[key] = int(val)
</code></pre>
<p>But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the <code>val</code> can be a string. </p>
<pre><code> dic = dict([entry.split('=') for entry in list])
</code></pre>
<p>However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect.</p>
<pre><code> dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list])
</code></pre>
<p>So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?</p>
| 15 | 2009-08-07T19:00:32Z | 1,248,990 | <p>Try the next:</p>
<pre><code>dict([x.split('=') for x in s.split()])
</code></pre>
| 3 | 2009-08-08T14:17:31Z | [
"python",
"string",
"dictionary",
"list-comprehension",
"generator-expression"
] |
convert string to dict using list comprehension in python | 1,246,444 | <p>I have came across this problem a few times and can't seem to figure out a simple solution.
Say I have a string</p>
<pre><code> string = "a=0 b=1 c=3"
</code></pre>
<p>I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:</p>
<pre><code> list = string.split()
dic = {}
for entry in list:
key, val = entry.split('=')
dic[key] = int(val)
</code></pre>
<p>But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the <code>val</code> can be a string. </p>
<pre><code> dic = dict([entry.split('=') for entry in list])
</code></pre>
<p>However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect.</p>
<pre><code> dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list])
</code></pre>
<p>So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?</p>
| 15 | 2009-08-07T19:00:32Z | 1,249,077 | <p>I sometimes like this approach, especially when the logic for making keys and values is more complicated:</p>
<pre><code>s = "a=0 b=1 c=3"
def get_key_val(x):
a,b = x.split('=')
return a,int(b)
ans = dict(map(get_key_val,s.split()))
</code></pre>
| 2 | 2009-08-08T14:50:23Z | [
"python",
"string",
"dictionary",
"list-comprehension",
"generator-expression"
] |
convert string to dict using list comprehension in python | 1,246,444 | <p>I have came across this problem a few times and can't seem to figure out a simple solution.
Say I have a string</p>
<pre><code> string = "a=0 b=1 c=3"
</code></pre>
<p>I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:</p>
<pre><code> list = string.split()
dic = {}
for entry in list:
key, val = entry.split('=')
dic[key] = int(val)
</code></pre>
<p>But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the <code>val</code> can be a string. </p>
<pre><code> dic = dict([entry.split('=') for entry in list])
</code></pre>
<p>However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect.</p>
<pre><code> dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list])
</code></pre>
<p>So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?</p>
| 15 | 2009-08-07T19:00:32Z | 3,030,359 | <p>I would do this:</p>
<pre><code>def kv(e): return (e[0], int(e[1]))
d = dict([kv(e.split("=")) for e in string.split(" ")])
</code></pre>
| 0 | 2010-06-12T22:37:04Z | [
"python",
"string",
"dictionary",
"list-comprehension",
"generator-expression"
] |
convert string to dict using list comprehension in python | 1,246,444 | <p>I have came across this problem a few times and can't seem to figure out a simple solution.
Say I have a string</p>
<pre><code> string = "a=0 b=1 c=3"
</code></pre>
<p>I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:</p>
<pre><code> list = string.split()
dic = {}
for entry in list:
key, val = entry.split('=')
dic[key] = int(val)
</code></pre>
<p>But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the <code>val</code> can be a string. </p>
<pre><code> dic = dict([entry.split('=') for entry in list])
</code></pre>
<p>However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect.</p>
<pre><code> dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list])
</code></pre>
<p>So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?</p>
| 15 | 2009-08-07T19:00:32Z | 27,033,812 | <p>Nowadays you should probably use a dictionary comprehension, introduced in 2.7:</p>
<pre><code>mydict = {key: int(value) for key, value in (a.split('=') for a in mystring.split())}
</code></pre>
<p>The dictionary comprehension is faster and shinier (and, in my opinion, more readable).</p>
<pre><code>from timeit import timeit
setup = """mystring = "a=0 b=1 c=3\""""
code1 = """mydict = dict((n,int(v)) for n,v in (a.split('=') for a in mystring.split()))""" # S.Lott's code
code2 = """mydict = {key: int(value) for key, value in (a.split('=') for a in mystring.split())}"""
print timeit(code1, setup=setup, number=10000) # 0.115524053574
print timeit(code2, setup=setup, number=10000) # 0.105328798294
</code></pre>
| 1 | 2014-11-20T07:13:58Z | [
"python",
"string",
"dictionary",
"list-comprehension",
"generator-expression"
] |
Getting the position of the gtk.StatusIcon on Windows | 1,246,552 | <p>I am assisting with Windows support for a PyGTK app that appears as a system tray applet, but am not so strong on the GTK+ gooey stuff...</p>
<p>We have it so when you left-click the systray icon, the window appears right by your tray icon no matter where your system tray is--and on Linux this works great, using the results of <code>gtk.StatusIcon.get_geometry()</code> to calculate the size and position. </p>
<p>Of course, the docs for gtk.StatusIcon.get_geometry() point out that "some platforms do not provide this information"--and this includes MS Windows, as I get NoneType as the result.</p>
<p>I can make a guess and position the window in the bottom-right corner of the screen, 30 pixels up from the bottom--as this will catch the majority of Windows users who haven't moved the taskbar. But for those that have, it looks all wrong.</p>
<p>So is there a Windows-friendly way to get the position of the systray icon so I can place my window there?</p>
<p><hr></p>
<p>Please note: I am already using <code>gtk_menu_popup()</code> with <code>gtk_status_icon_position_menu</code> for a pop-up menu which works correctly.</p>
<p>But what I am trying to position is a separate gtk.Window, which will not accept gtk_status_icon_position_menu (because it's not a menu).</p>
<p>Any other ideas would be appreciated...</p>
| 4 | 2009-08-07T19:27:36Z | 1,247,303 | <p>Gtk provides function gtk_status_icon_position_menu that can be passed into gtk_menu_popup as a GtkPositionFunc.
This seems to provide the requested functionality.</p>
| 1 | 2009-08-07T22:33:14Z | [
"python",
"windows",
"gtk",
"pygtk"
] |
Getting the position of the gtk.StatusIcon on Windows | 1,246,552 | <p>I am assisting with Windows support for a PyGTK app that appears as a system tray applet, but am not so strong on the GTK+ gooey stuff...</p>
<p>We have it so when you left-click the systray icon, the window appears right by your tray icon no matter where your system tray is--and on Linux this works great, using the results of <code>gtk.StatusIcon.get_geometry()</code> to calculate the size and position. </p>
<p>Of course, the docs for gtk.StatusIcon.get_geometry() point out that "some platforms do not provide this information"--and this includes MS Windows, as I get NoneType as the result.</p>
<p>I can make a guess and position the window in the bottom-right corner of the screen, 30 pixels up from the bottom--as this will catch the majority of Windows users who haven't moved the taskbar. But for those that have, it looks all wrong.</p>
<p>So is there a Windows-friendly way to get the position of the systray icon so I can place my window there?</p>
<p><hr></p>
<p>Please note: I am already using <code>gtk_menu_popup()</code> with <code>gtk_status_icon_position_menu</code> for a pop-up menu which works correctly.</p>
<p>But what I am trying to position is a separate gtk.Window, which will not accept gtk_status_icon_position_menu (because it's not a menu).</p>
<p>Any other ideas would be appreciated...</p>
| 4 | 2009-08-07T19:27:36Z | 1,874,016 | <p>The behavior i experienced in windows with gtk_status_icon_position_menu was that it spawns the window at the location the user clicked in the statusicon</p>
| 0 | 2009-12-09T13:48:27Z | [
"python",
"windows",
"gtk",
"pygtk"
] |
Getting the position of the gtk.StatusIcon on Windows | 1,246,552 | <p>I am assisting with Windows support for a PyGTK app that appears as a system tray applet, but am not so strong on the GTK+ gooey stuff...</p>
<p>We have it so when you left-click the systray icon, the window appears right by your tray icon no matter where your system tray is--and on Linux this works great, using the results of <code>gtk.StatusIcon.get_geometry()</code> to calculate the size and position. </p>
<p>Of course, the docs for gtk.StatusIcon.get_geometry() point out that "some platforms do not provide this information"--and this includes MS Windows, as I get NoneType as the result.</p>
<p>I can make a guess and position the window in the bottom-right corner of the screen, 30 pixels up from the bottom--as this will catch the majority of Windows users who haven't moved the taskbar. But for those that have, it looks all wrong.</p>
<p>So is there a Windows-friendly way to get the position of the systray icon so I can place my window there?</p>
<p><hr></p>
<p>Please note: I am already using <code>gtk_menu_popup()</code> with <code>gtk_status_icon_position_menu</code> for a pop-up menu which works correctly.</p>
<p>But what I am trying to position is a separate gtk.Window, which will not accept gtk_status_icon_position_menu (because it's not a menu).</p>
<p>Any other ideas would be appreciated...</p>
| 4 | 2009-08-07T19:27:36Z | 3,262,115 | <p>I am also looking for an answer to this but have found something that might help.</p>
<p>It seems to me that GTK figures out where to bring up the PopupMenu from the mouse position. Somehow it figures out that the mouse button was clicked over the StatusIcon. Presumably either from mouse events sent by the windowing system or from some sort of knowledge of where the StatusIcon is.</p>
<p>What I am getting at is that GTK must either 1) know the actual location of the StatusIcon or 2) get events from the windowing system when the mouse is clicked on the StatusIcon. So it must know the information.</p>
<p>I also have a popup window I want to raise near the StatusIcon and I also have a PopupMenu that is working fine. So I tried this, in pygtk:</p>
<pre><code>x, y, push = gtk.status_icon_position_menu(popup_menu, status_icon)
</code></pre>
<p>I passed in the PopupMenu to try to find the StatusIcon even though I'm not trying to popup the menu. This does get a position near the StatusIcon but the weird thing is that it only works after the PopupMenu has been popped up once.</p>
<p>Anyway, that got me a little closer and might help you or someone else find a complete solution.</p>
| 0 | 2010-07-16T05:16:48Z | [
"python",
"windows",
"gtk",
"pygtk"
] |
How can I process this text file and parse what I need? | 1,246,752 | <p>I'm trying to parse ouput from the Python doctest module and store it in an HTML file.</p>
<p>I've got output similar to this:</p>
<pre><code>**********************************************************************
File "example.py", line 16, in __main__.factorial
Failed example:
[factorial(n) for n in range(6)]
Expected:
[0, 1, 2, 6, 24, 120]
Got:
[1, 1, 2, 6, 24, 120]
**********************************************************************
File "example.py", line 20, in __main__.factorial
Failed example:
factorial(30)
Expected:
25252859812191058636308480000000L
Got:
265252859812191058636308480000000L
**********************************************************************
1 items had failures:
2 of 8 in __main__.factorial
***Test Failed*** 2 failures.
</code></pre>
<p>Each failure is preceded by a line of asterisks, which delimit each test failure from each other.</p>
<p>What I'd like to do is strip out the filename and method that failed, as well as the expected and actual results. Then I'd like to create an HTML document using this (or store it in a text file and then do a second round of parsing).</p>
<p>How can I do this using just Python or some combination of UNIX shell utilities?</p>
<p>EDIT: I formulated the following shell script which matches each block how I'd like,but I'm unsure how to redirect each sed match to its own file.</p>
<pre><code>python example.py | sed -n '/.*/,/^\**$/p' > `mktemp error.XXX`
</code></pre>
| 2 | 2009-08-07T20:06:29Z | 1,247,033 | <p>You can write a Python program to pick this apart, but maybe a better thing to do would be to look into modifying doctest to output the report you want in the first place. From the docs for doctest.DocTestRunner:</p>
<pre><code> ... the display output
can be also customized by subclassing DocTestRunner, and
overriding the methods `report_start`, `report_success`,
`report_unexpected_exception`, and `report_failure`.
</code></pre>
| 4 | 2009-08-07T21:10:35Z | [
"python",
"parsing",
"shell",
"doctest"
] |
How can I process this text file and parse what I need? | 1,246,752 | <p>I'm trying to parse ouput from the Python doctest module and store it in an HTML file.</p>
<p>I've got output similar to this:</p>
<pre><code>**********************************************************************
File "example.py", line 16, in __main__.factorial
Failed example:
[factorial(n) for n in range(6)]
Expected:
[0, 1, 2, 6, 24, 120]
Got:
[1, 1, 2, 6, 24, 120]
**********************************************************************
File "example.py", line 20, in __main__.factorial
Failed example:
factorial(30)
Expected:
25252859812191058636308480000000L
Got:
265252859812191058636308480000000L
**********************************************************************
1 items had failures:
2 of 8 in __main__.factorial
***Test Failed*** 2 failures.
</code></pre>
<p>Each failure is preceded by a line of asterisks, which delimit each test failure from each other.</p>
<p>What I'd like to do is strip out the filename and method that failed, as well as the expected and actual results. Then I'd like to create an HTML document using this (or store it in a text file and then do a second round of parsing).</p>
<p>How can I do this using just Python or some combination of UNIX shell utilities?</p>
<p>EDIT: I formulated the following shell script which matches each block how I'd like,but I'm unsure how to redirect each sed match to its own file.</p>
<pre><code>python example.py | sed -n '/.*/,/^\**$/p' > `mktemp error.XXX`
</code></pre>
| 2 | 2009-08-07T20:06:29Z | 1,247,039 | <p>This is a quick and dirty script that parses the output into tuples with the relevant information:</p>
<pre><code>import sys
import re
stars_re = re.compile('^[*]+$', re.MULTILINE)
file_line_re = re.compile(r'^File "(.*?)", line (\d*), in (.*)$')
doctest_output = sys.stdin.read()
chunks = stars_re.split(doctest_output)[1:-1]
for chunk in chunks:
chunk_lines = chunk.strip().splitlines()
m = file_line_re.match(chunk_lines[0])
file, line, module = m.groups()
failed_example = chunk_lines[2].strip()
expected = chunk_lines[4].strip()
got = chunk_lines[6].strip()
print (file, line, module, failed_example, expected, got)
</code></pre>
| 1 | 2009-08-07T21:11:11Z | [
"python",
"parsing",
"shell",
"doctest"
] |
How can I process this text file and parse what I need? | 1,246,752 | <p>I'm trying to parse ouput from the Python doctest module and store it in an HTML file.</p>
<p>I've got output similar to this:</p>
<pre><code>**********************************************************************
File "example.py", line 16, in __main__.factorial
Failed example:
[factorial(n) for n in range(6)]
Expected:
[0, 1, 2, 6, 24, 120]
Got:
[1, 1, 2, 6, 24, 120]
**********************************************************************
File "example.py", line 20, in __main__.factorial
Failed example:
factorial(30)
Expected:
25252859812191058636308480000000L
Got:
265252859812191058636308480000000L
**********************************************************************
1 items had failures:
2 of 8 in __main__.factorial
***Test Failed*** 2 failures.
</code></pre>
<p>Each failure is preceded by a line of asterisks, which delimit each test failure from each other.</p>
<p>What I'd like to do is strip out the filename and method that failed, as well as the expected and actual results. Then I'd like to create an HTML document using this (or store it in a text file and then do a second round of parsing).</p>
<p>How can I do this using just Python or some combination of UNIX shell utilities?</p>
<p>EDIT: I formulated the following shell script which matches each block how I'd like,but I'm unsure how to redirect each sed match to its own file.</p>
<pre><code>python example.py | sed -n '/.*/,/^\**$/p' > `mktemp error.XXX`
</code></pre>
| 2 | 2009-08-07T20:06:29Z | 1,247,149 | <p>I wrote a quick parser in pyparsing to do it.</p>
<pre><code>from pyparsing import *
str = """
**********************************************************************
File "example.py", line 16, in __main__.factorial
Failed example:
[factorial(n) for n in range(6)]
Expected:
[0, 1, 2, 6, 24, 120]
Got:
[1, 1, 2, 6, 24, 120]
**********************************************************************
File "example.py", line 20, in __main__.factorial
Failed example:
factorial(30)
Expected:
25252859812191058636308480000000L
Got:
265252859812191058636308480000000L
**********************************************************************
"""
quote = Literal('"').suppress()
comma = Literal(',').suppress()
in_ = Keyword('in').suppress()
block = OneOrMore("**").suppress() + \
Keyword("File").suppress() + \
quote + Word(alphanums + ".") + quote + \
comma + Keyword("line").suppress() + Word(nums) + comma + \
in_ + Word(alphanums + "._") + \
LineStart() + restOfLine.suppress() + \
LineStart() + restOfLine + \
LineStart() + restOfLine.suppress() + \
LineStart() + restOfLine + \
LineStart() + restOfLine.suppress() + \
LineStart() + restOfLine
all = OneOrMore(Group(block))
result = all.parseString(str)
for section in result:
print section
</code></pre>
<p>gives</p>
<pre><code>['example.py', '16', '__main__.factorial', ' [factorial(n) for n in range(6)]', ' [0, 1, 2, 6, 24, 120]', ' [1, 1, 2, 6, 24, 120]']
['example.py', '20', '__main__.factorial', ' factorial(30)', ' 25252859812191058636308480000000L', ' 265252859812191058636308480000000L']
</code></pre>
| 1 | 2009-08-07T21:43:23Z | [
"python",
"parsing",
"shell",
"doctest"
] |
How can I process this text file and parse what I need? | 1,246,752 | <p>I'm trying to parse ouput from the Python doctest module and store it in an HTML file.</p>
<p>I've got output similar to this:</p>
<pre><code>**********************************************************************
File "example.py", line 16, in __main__.factorial
Failed example:
[factorial(n) for n in range(6)]
Expected:
[0, 1, 2, 6, 24, 120]
Got:
[1, 1, 2, 6, 24, 120]
**********************************************************************
File "example.py", line 20, in __main__.factorial
Failed example:
factorial(30)
Expected:
25252859812191058636308480000000L
Got:
265252859812191058636308480000000L
**********************************************************************
1 items had failures:
2 of 8 in __main__.factorial
***Test Failed*** 2 failures.
</code></pre>
<p>Each failure is preceded by a line of asterisks, which delimit each test failure from each other.</p>
<p>What I'd like to do is strip out the filename and method that failed, as well as the expected and actual results. Then I'd like to create an HTML document using this (or store it in a text file and then do a second round of parsing).</p>
<p>How can I do this using just Python or some combination of UNIX shell utilities?</p>
<p>EDIT: I formulated the following shell script which matches each block how I'd like,but I'm unsure how to redirect each sed match to its own file.</p>
<pre><code>python example.py | sed -n '/.*/,/^\**$/p' > `mktemp error.XXX`
</code></pre>
| 2 | 2009-08-07T20:06:29Z | 1,247,291 | <p>This is probably one of the least elegant python scripts I've ever written, but it should have the framework to do what you want without resorting to UNIX utilities and separate scripts to create the html. It's untested, but it should only need minor tweaking to work.</p>
<pre><code>import os
import sys
#create a list of all files in directory
dirList = os.listdir('')
#Ignore anything that isn't a .txt file.
#
#Read in text, then split it into a list.
for thisFile in dirList:
if thisFile.endswith(".txt"):
infile = open(thisFile,'r')
rawText = infile.read()
yourList = rawText.split('\n')
#Strings
compiledText = ''
htmlText = ''
for i in yourList:
#clunky way of seeing whether or not current line
#should be included in compiledText
if i.startswith("*****"):
compiledText += "\n\n--- New Report ---\n"
if i.startswith("File"):
compiledText += i + '\n'
if i.startswith("Fail"):
compiledText += i + '\n'
if i.startswith("Expe"):
compiledText += i + '\n'
if i.startswith("Got"):
compiledText += i + '\n'
if i.startswith(" "):
compiledText += i + '\n'
#insert your HTML template below
htmlText = '<html>...\n <body> \n '+htmlText+'</body>... </html>'
#write out to file
outfile = open('processed/'+thisFile+'.html','w')
outfile.write(htmlText)
outfile.close()
</code></pre>
| 0 | 2009-08-07T22:28:11Z | [
"python",
"parsing",
"shell",
"doctest"
] |
Can I use more than a single filter on a variable in template? | 1,246,968 | <p>For example:</p>
<pre><code>{{test|linebreaksbr|safe}}
</code></pre>
| 1 | 2009-08-07T20:57:01Z | 1,246,978 | <p>Yes you can, this is common practice to string together many filters consecutively.</p>
<p>Could you turn debugging on and see what the error is and update the question?</p>
<p>Make sure this is set in your settings.py</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
</code></pre>
| 2 | 2009-08-07T20:57:55Z | [
"python",
"django",
"templates",
"filter"
] |
Can I use more than a single filter on a variable in template? | 1,246,968 | <p>For example:</p>
<pre><code>{{test|linebreaksbr|safe}}
</code></pre>
| 1 | 2009-08-07T20:57:01Z | 1,246,987 | <p>Yes, have you tried it? Did something go wrong?</p>
| 2 | 2009-08-07T20:59:06Z | [
"python",
"django",
"templates",
"filter"
] |
Recursive? looping to n levels in Python | 1,247,133 | <p>Working in python I want to extract a dataset with the following structure:</p>
<p>Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the potential to go on for infinity, in reality a depth of 10 levels is unusual, as is having more than 10 siblings at each level.</p>
<p>For each item in the dataset I want to show show all items for which this item is their parent... and so on until it reaches the bottom of the dataset.</p>
<p>Doing the first two levels is easy, but I'm unsure how to make it efficiently recurs down through the levels.</p>
<p>Any pointers very much appreciated.</p>
| 1 | 2009-08-07T21:38:22Z | 1,247,157 | <p>Are you saying that each item only maintains a reference to its parents? If so, then how about</p>
<pre><code>def getChildren(item) :
children = []
for possibleChild in allItems :
if (possibleChild.parent == item) :
children.extend(getChildren(possibleChild))
return children
</code></pre>
<p>This returns a list that contains all items who are in some way descended from item.</p>
| 1 | 2009-08-07T21:45:59Z | [
"python",
"recursion"
] |
Recursive? looping to n levels in Python | 1,247,133 | <p>Working in python I want to extract a dataset with the following structure:</p>
<p>Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the potential to go on for infinity, in reality a depth of 10 levels is unusual, as is having more than 10 siblings at each level.</p>
<p>For each item in the dataset I want to show show all items for which this item is their parent... and so on until it reaches the bottom of the dataset.</p>
<p>Doing the first two levels is easy, but I'm unsure how to make it efficiently recurs down through the levels.</p>
<p>Any pointers very much appreciated.</p>
| 1 | 2009-08-07T21:38:22Z | 1,247,268 | <p>If you want to keep the structure of your dataset, this will produce a list of the format [id, [children of id], id2, [children of id2]]</p>
<pre><code>def children(id):
return [id]+[children(x.id) for x in filter(lambda x:x.parent == id, items)]
</code></pre>
| 1 | 2009-08-07T22:19:50Z | [
"python",
"recursion"
] |
Recursive? looping to n levels in Python | 1,247,133 | <p>Working in python I want to extract a dataset with the following structure:</p>
<p>Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the potential to go on for infinity, in reality a depth of 10 levels is unusual, as is having more than 10 siblings at each level.</p>
<p>For each item in the dataset I want to show show all items for which this item is their parent... and so on until it reaches the bottom of the dataset.</p>
<p>Doing the first two levels is easy, but I'm unsure how to make it efficiently recurs down through the levels.</p>
<p>Any pointers very much appreciated.</p>
| 1 | 2009-08-07T21:38:22Z | 1,247,290 | <p>you should probably use a defaultdictionary for this:</p>
<pre><code>from collections import defaultdict
itemdict = defaultdict(list)
for id, parent_id in itemlist:
itemdict[parent_id].append(id)
</code></pre>
<p>then you can recursively print it (with indentation) like</p>
<pre><code>def printitem(id, depth=0):
print ' '*depth, id
for child in itemdict[id]:
printitem(child, depth+1)
</code></pre>
| 1 | 2009-08-07T22:27:11Z | [
"python",
"recursion"
] |
Recursive? looping to n levels in Python | 1,247,133 | <p>Working in python I want to extract a dataset with the following structure:</p>
<p>Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the potential to go on for infinity, in reality a depth of 10 levels is unusual, as is having more than 10 siblings at each level.</p>
<p>For each item in the dataset I want to show show all items for which this item is their parent... and so on until it reaches the bottom of the dataset.</p>
<p>Doing the first two levels is easy, but I'm unsure how to make it efficiently recurs down through the levels.</p>
<p>Any pointers very much appreciated.</p>
| 1 | 2009-08-07T21:38:22Z | 1,249,176 | <p>How about something like this,</p>
<pre><code>
#!/usr/bin/python
tree = { 0:(None, [1,2,3]),
1:(0, [4]),
2:(0, []),
3:(0, [5,6]),
4:(1, [7]),
5:(3, []),
6:(3, []),
7:(4, []),
}
def find_children( tree, id ):
print "node:", id, tree[id]
for child in tree[id][1]:
find_children( tree, child )
if __name__=="__main__":
import sys
find_children( tree, int(sys.argv[1]) )
$ ./tree.py 3
node: 3 (0, [5, 6])
node: 5 (3, [])
node: 6 (3, [])
</code></pre>
<p>It's also worth noting that python has a pretty low default recursion limit, 1000 I think.</p>
<p>In the event that your tree actually gets pretty deep you'll hit this very quickly.
You can crank this up with, </p>
<pre><code>
sys.setrecursionlimit(100000)
</code></pre>
<p>and check it with,</p>
<pre><code>
sys.getrecursionlimit()
</code></pre>
| 0 | 2009-08-08T15:44:28Z | [
"python",
"recursion"
] |
how to include % sign in docutils html template | 1,247,284 | <p>I want to generate HTML pages with rst2html, using my own templates. these templates include many % signs, like in</p>
<pre><code><TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
</code></pre>
<p>now, when I call rst2html using the command</p>
<pre><code>rst2html --template=layout2.tpl rst/index.rst > index.html
</code></pre>
<p>i get the error</p>
<blockquote>
<p>ValueError: unsupported format character '"' (0x22) at index 827</p>
</blockquote>
<p>i found out the problem is that rst2html thinks that the %" is a placeholder.</p>
<p>i already tried escaping the % in the template, like</p>
<pre><code><TABLE border="0" cellpadding="0" cellspacing="0" width="100\%">
</code></pre>
<p>but this is not working, the error is the same.</p>
<p>so my question is how i can solve this issue. any help is greatly appreciated!</p>
| 1 | 2009-08-07T22:25:12Z | 1,247,287 | <p>Have you tried obvious things: escaping the '%' with '%'? </p>
<p>Here is normal string formatting to display a percent sign in the result:</p>
<pre><code>>>> print "%d%%" % 100
100%
</code></pre>
<p>Maybe rst2html is the same? (I haven't tried this in rst2html -- I don't have it installed.)</p>
<p>Okay, now I've installed docutils. This works for me:</p>
<p>layout2.tpl:</p>
<pre><code><TABLE border="0" cellpadding="0" cellspacing="0" width="100%%">
</code></pre>
<p>Command line:</p>
<pre><code>C:\Python26\Lib\site-packages>python C:\Python26\Lib\site-packages\docutils-0.5-
py2.6.egg\EGG-INFO\scripts\rst2html.py --template=c:\temp\layout2.tpl
^Z
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
</code></pre>
<p>So the result is as desired, I believe.</p>
| 7 | 2009-08-07T22:26:32Z | [
"python"
] |
how to include % sign in docutils html template | 1,247,284 | <p>I want to generate HTML pages with rst2html, using my own templates. these templates include many % signs, like in</p>
<pre><code><TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
</code></pre>
<p>now, when I call rst2html using the command</p>
<pre><code>rst2html --template=layout2.tpl rst/index.rst > index.html
</code></pre>
<p>i get the error</p>
<blockquote>
<p>ValueError: unsupported format character '"' (0x22) at index 827</p>
</blockquote>
<p>i found out the problem is that rst2html thinks that the %" is a placeholder.</p>
<p>i already tried escaping the % in the template, like</p>
<pre><code><TABLE border="0" cellpadding="0" cellspacing="0" width="100\%">
</code></pre>
<p>but this is not working, the error is the same.</p>
<p>so my question is how i can solve this issue. any help is greatly appreciated!</p>
| 1 | 2009-08-07T22:25:12Z | 1,247,305 | <p>Doubt it, but maybe the XML command CDATA works.</p>
<pre><code><![CDATA[
...
]]>
</code></pre>
<p>I use it for storing paypal buttons in an XML document and inserting them with PHP.</p>
| 0 | 2009-08-07T22:33:52Z | [
"python"
] |
Elixir Entity with a list of tuples in it. ex. Cooking Recipe with list of (ingrediant, quantity) tuple | 1,247,343 | <p>I'm trying to build an elixir model in which I have a class with a list(of variable size) of tuples.</p>
<p>One example would be a recipe</p>
<p>while I can do something like this:</p>
<pre><code>class Recipe(Entity):
ingrediants = OneToMany('IngrediantList')
cooking_time = Field(Integer)
...
class IngrediantList(Entity):
ingrediant = ManyToOne('Ingrediant')
quantity = Field(Number(3,2))
class Ingrediant(Entity):
name = Field(String(30))
...
</code></pre>
<p>It has a number of short comings. For one, I don't like creating an entity for ingrediant list which I don't have any meaning for wrt the domain; takes fun out of abstraction.</p>
<p>Another is that a query like which items can I prepare with this ingredient would get really messy and probably inefficient without adding more relations and or fields to the model making it messy in turn.</p>
<p>One more example would be a bank deposit slip with list of denominations and quantity.</p>
<p>What is the best way to design such a model?</p>
| 0 | 2009-08-07T22:46:05Z | 1,253,951 | <p>This is the correct way to model composite objects. The only thing I'd change is the name of the IngredientList class. Something like RecipeEntry or IngredientQuantity would be more appropriate. Calling it a tuple is just trying to avoid the need to name the fact that a recipe needs some quantity of some ingredient.</p>
<p>If for most of the code you don't want to consider the details of the association you can use sqlalchemy associationproxy extension to create a proxy attribute to hide the details.</p>
| 0 | 2009-08-10T09:38:20Z | [
"python",
"sqlalchemy",
"python-elixir"
] |
Elixir Entity with a list of tuples in it. ex. Cooking Recipe with list of (ingrediant, quantity) tuple | 1,247,343 | <p>I'm trying to build an elixir model in which I have a class with a list(of variable size) of tuples.</p>
<p>One example would be a recipe</p>
<p>while I can do something like this:</p>
<pre><code>class Recipe(Entity):
ingrediants = OneToMany('IngrediantList')
cooking_time = Field(Integer)
...
class IngrediantList(Entity):
ingrediant = ManyToOne('Ingrediant')
quantity = Field(Number(3,2))
class Ingrediant(Entity):
name = Field(String(30))
...
</code></pre>
<p>It has a number of short comings. For one, I don't like creating an entity for ingrediant list which I don't have any meaning for wrt the domain; takes fun out of abstraction.</p>
<p>Another is that a query like which items can I prepare with this ingredient would get really messy and probably inefficient without adding more relations and or fields to the model making it messy in turn.</p>
<p>One more example would be a bank deposit slip with list of denominations and quantity.</p>
<p>What is the best way to design such a model?</p>
| 0 | 2009-08-07T22:46:05Z | 1,258,142 | <p><a href="http://www.sqlalchemy.org/docs/05/reference/ext/associationproxy.html#building-complex-views" rel="nofollow">solution using sqlalchemy associationproxy</a>
This is from the sqlalchemy docs.</p>
| 0 | 2009-08-11T02:03:18Z | [
"python",
"sqlalchemy",
"python-elixir"
] |
Python List Comprehension Vs. Map | 1,247,486 | <p>Is there a reason to prefer using <code>map()</code> over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other?</p>
| 376 | 2009-08-07T23:43:31Z | 1,247,490 | <p><code>map</code> may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.</p>
<p>An example of the tiny speed advantage of map when using exactly the same function:</p>
<pre><code>$ python -mtimeit -s'xs=range(10)' 'map(hex, xs)'
100000 loops, best of 3: 4.86 usec per loop
$ python -mtimeit -s'xs=range(10)' '[hex(x) for x in xs]'
100000 loops, best of 3: 5.58 usec per loop
</code></pre>
<p>An example of how performance comparison gets completely reversed when map needs a lambda:</p>
<pre><code>$ python -mtimeit -s'xs=range(10)' 'map(lambda x: x+2, xs)'
100000 loops, best of 3: 4.24 usec per loop
$ python -mtimeit -s'xs=range(10)' '[x+2 for x in xs]'
100000 loops, best of 3: 2.32 usec per loop
</code></pre>
| 360 | 2009-08-07T23:45:23Z | [
"python",
"list-comprehension",
"map-function"
] |
Python List Comprehension Vs. Map | 1,247,486 | <p>Is there a reason to prefer using <code>map()</code> over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other?</p>
| 376 | 2009-08-07T23:43:31Z | 1,247,531 | <p>I find list comprehensions are generally more expressive of what I'm trying to do than <code>map</code> - they both get it done, but the former saves the mental load of trying to understand what could be a complex <code>lambda</code> expression.</p>
<p>There's also an interview out there somewhere (I can't find it offhand) where Guido lists <code>lambda</code>s and the functional functions as the thing he most regrets about accepting into Python, so you could make the argument that they're un-Pythonic by virtue of that.</p>
| 14 | 2009-08-07T23:59:05Z | [
"python",
"list-comprehension",
"map-function"
] |
Python List Comprehension Vs. Map | 1,247,486 | <p>Is there a reason to prefer using <code>map()</code> over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other?</p>
| 376 | 2009-08-07T23:43:31Z | 1,660,062 | <p>Here is one possible case:</p>
<pre><code>map(lambda op1,op2: op1*op2, list1, list2)
</code></pre>
<p>versus:</p>
<pre><code>[op1*op2 for op1,op2 in zip(list1,list2)]
</code></pre>
<p>I am guessing the zip() is an unfortunate and unnecessary overhead you need to indulge in if you insist on using list comprehensions instead of the map. Would be great if someone clarifies this whether affirmatively or negatively.</p>
| 8 | 2009-11-02T08:42:48Z | [
"python",
"list-comprehension",
"map-function"
] |
Python List Comprehension Vs. Map | 1,247,486 | <p>Is there a reason to prefer using <code>map()</code> over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other?</p>
| 376 | 2009-08-07T23:43:31Z | 2,307,517 | <p>Another reason to use list comprehension over map() and filter() is that Psyco can't compile these functions. </p>
<p>See <a href="http://psyco.sourceforge.net/" rel="nofollow">http://psyco.sourceforge.net/</a></p>
| 6 | 2010-02-21T21:27:28Z | [
"python",
"list-comprehension",
"map-function"
] |
Python List Comprehension Vs. Map | 1,247,486 | <p>Is there a reason to prefer using <code>map()</code> over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other?</p>
| 376 | 2009-08-07T23:43:31Z | 6,407,222 | <p><strong>Cases</strong></p>
<ul>
<li><strong>Common case</strong>: Almost always, you will want to use a list comprehension in <em>python</em> because it will be more obvious what you're doing to novice programmers reading your code. (This does not apply to other languages, where other idioms may apply.) It will even be more obvious what you're doing to python programmers, since list comprehensions are the de-facto standard in python for iteration; they are <em>expected</em>.</li>
<li><strong>Less-common case</strong>: However if you <em>already have a function defined</em>, it is often reasonable to use <code>map</code>, though it is considered 'unpythonic'. For example, <code>map(sum, myLists)</code> is more elegant/terse than <code>[sum(x) for x in myLists]</code>. You gain the elegance of not having to make up a dummy variable (e.g. <code>sum(x) for x...</code> or <code>sum(_) for _...</code> or <code>sum(readableName) for readableName...</code>) which you have to type twice, just to iterate. The same argument holds for <code>filter</code> and <code>reduce</code> and anything from the <code>itertools</code> module: if you already have a function handy, you could go ahead and do some functional programming. This gains readability in some situations, and loses it in others (e.g. novice programmers, multiple arguments)... but the readability of your code highly depends on your comments anyway.</li>
<li><strong>Almost never</strong>: You may want to use the <code>map</code> function as a pure abstract function while doing functional programming, where you're mapping <code>map</code>, or currying <code>map</code>, or otherwise benefit from talking about <code>map</code> as a function. In Haskell for example, a functor interface called <code>fmap</code> generalizes mapping over any data structure. This is very uncommon in python because the python grammar compels you to use generator-style to talk about iteration; you can't generalize it easily. (This is sometimes good and sometimes bad.) You can probably come up with rare python examples where <code>map(f, *lists)</code> is a reasonable thing to do. The closest example I can come up with would be <code>sumEach = partial(map,sum)</code>, which is a one-liner that is very roughly equivalent to:</li>
</ul>
<p></p>
<pre><code>def sumEach(myLists):
return [sum(_) for _ in myLists]
</code></pre>
<p><strong>"Pythonism"</strong></p>
<p>I dislike the word "pythonic" because I don't find that pythonic is always elegant in my eyes. Nevertheless, <code>map</code> and <code>filter</code> and similar functions (like the very useful <code>itertools</code> module) are probably considered unpythonic in terms of style.</p>
<p><strong>Laziness</strong></p>
<p>In terms of efficiency, like most functional programming constructs, <strong>MAP CAN BE LAZY</strong>, and in fact is lazy in python. That means you can do this (in <em>python3</em>) and your computer will not run out of memory and lose all your unsaved data:</p>
<pre><code>>>> map(str, range(10**100))
<map object at 0x2201d50>
</code></pre>
<p>Try doing that with a list comprehension:</p>
<pre><code>>>> [str(n) for n in range(10**100)]
# DO NOT TRY THIS AT HOME OR YOU WILL BE SAD #
</code></pre>
<p>Do note that list comprehensions are also inherently lazy, but <em>python has chosen to implement them as non-lazy</em>. Nevertheless, python does support lazy list comprehensions in the form of generator expressions, as follows:</p>
<pre><code>>>> (str(n) for n in range(10**100))
<generator object <genexpr> at 0xacbdef>
</code></pre>
<p>You can basically think of the <code>[...]</code> syntax as passing in a generator expression to the list constructor, like <code>list(x for x in range(5))</code>.</p>
<p><strong>Brief contrived example</strong></p>
<pre><code>from operator import neg
print({x:x**2 for x in map(neg,range(5))})
print({x:x**2 for x in [-y for y in range(5)]})
print({x:x**2 for x in (-y for y in range(5))})
</code></pre>
<p>List comprehensions are non-lazy, so may require more memory (unless you use generator comprehensions). The square brackets <code>[...]</code> often make things obvious, especially when in a mess of parentheses. On the other hand, sometimes you end up being verbose like typing <code>[x for x in...</code>. As long as you keep your iterator variables short, list comprehensions are usually clearer if you don't indent your code. But you could always indent your code.</p>
<pre><code>print(
{x:x**2 for x in (-y for y in range(5))}
)
</code></pre>
<p>or break things up:</p>
<pre><code>rangeNeg5 = (-y for y in range(5))
print(
{x:x**2 for x in rangeNeg5}
)
</code></pre>
<p><strong>Efficiency comparison for python3</strong></p>
<p><code>map</code> is now lazy:</p>
<pre><code>% python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=map(f,xs)'
1000000 loops, best of 3: 0.336 usec per loop ^^^^^^^^^
</code></pre>
<p><em>Therefore if you will not be using all your data, or do not know ahead of time how much data you need, <code>map</code> in python3 (and generator expressions in python2 or python3) will avoid calculating their values until the last moment necessary. Usually this will usually outweigh any overhead from using <code>map</code>. The downside is that this is very limited in python as opposed to most functional languages: you only get this benefit if you access your data left-to-right "in order", because python generator expressions can only be evaluated the order <code>x[0], x[1], x[2], ...</code>.</em></p>
<p>However let's say that we have a pre-made function <code>f</code> we'd like to <code>map</code>, and we ignore the laziness of <code>map</code> by immediately forcing evaluation with <code>list(...)</code>. We get some very interesting results:</p>
<pre><code>% python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=list(map(f,xs))'
10000 loops, best of 3: 165/124/135 usec per loop ^^^^^^^^^^^^^^^
for list(<map object>)
% python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=[f(x) for x in xs]'
10000 loops, best of 3: 181/118/123 usec per loop ^^^^^^^^^^^^^^^^^^
for list(<generator>), probably optimized
% python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=list(f(x) for x in xs)'
1000 loops, best of 3: 215/150/150 usec per loop ^^^^^^^^^^^^^^^^^^^^^^
for list(<generator>)
</code></pre>
<p>In results are in the form AAA/BBB/CCC where A was performed with on a circa-2010 Intel workstation with python 3.?.?, and B and C were performed with a circa-2013 AMD workstation with python 3.2.1, with extremely different hardware. The result seems to be that map and list comprehensions are comparable in performance, which is most strongly affected by other random factors. The only thing we can tell seems to be that, oddly, while we expect list comprehensions <code>[...]</code> to perform better than generator expressions <code>(...)</code>, <code>map</code> is ALSO more efficient that generator expressions (again assuming that all values are evaluated/used).</p>
<p>It is important to realize that these tests assume a very simple function (the identity function); however this is fine because if the function were complicated, then performance overhead would be negligible compared to other factors in the program. (It may still be interesting to test with other simple things like <code>f=lambda x:x+x</code>)</p>
<p>If you're skilled at reading python assembly, you can use the <code>dis</code> module to see if that's actually what's going on behind the scenes:</p>
<pre><code>>>> listComp = compile('[f(x) for x in xs]', 'listComp', 'eval')
>>> dis.dis(listComp)
1 0 LOAD_CONST 0 (<code object <listcomp> at 0x2511a48, file "listComp", line 1>)
3 MAKE_FUNCTION 0
6 LOAD_NAME 0 (xs)
9 GET_ITER
10 CALL_FUNCTION 1
13 RETURN_VALUE
>>> listComp.co_consts
(<code object <listcomp> at 0x2511a48, file "listComp", line 1>,)
>>> dis.dis(listComp.co_consts[0])
1 0 BUILD_LIST 0
3 LOAD_FAST 0 (.0)
>> 6 FOR_ITER 18 (to 27)
9 STORE_FAST 1 (x)
12 LOAD_GLOBAL 0 (f)
15 LOAD_FAST 1 (x)
18 CALL_FUNCTION 1
21 LIST_APPEND 2
24 JUMP_ABSOLUTE 6
>> 27 RETURN_VALUE
</code></pre>
<p> </p>
<pre><code>>>> listComp2 = compile('list(f(x) for x in xs)', 'listComp2', 'eval')
>>> dis.dis(listComp2)
1 0 LOAD_NAME 0 (list)
3 LOAD_CONST 0 (<code object <genexpr> at 0x255bc68, file "listComp2", line 1>)
6 MAKE_FUNCTION 0
9 LOAD_NAME 1 (xs)
12 GET_ITER
13 CALL_FUNCTION 1
16 CALL_FUNCTION 1
19 RETURN_VALUE
>>> listComp2.co_consts
(<code object <genexpr> at 0x255bc68, file "listComp2", line 1>,)
>>> dis.dis(listComp2.co_consts[0])
1 0 LOAD_FAST 0 (.0)
>> 3 FOR_ITER 17 (to 23)
6 STORE_FAST 1 (x)
9 LOAD_GLOBAL 0 (f)
12 LOAD_FAST 1 (x)
15 CALL_FUNCTION 1
18 YIELD_VALUE
19 POP_TOP
20 JUMP_ABSOLUTE 3
>> 23 LOAD_CONST 0 (None)
26 RETURN_VALUE
</code></pre>
<p> </p>
<pre><code>>>> evalledMap = compile('list(map(f,xs))', 'evalledMap', 'eval')
>>> dis.dis(evalledMap)
1 0 LOAD_NAME 0 (list)
3 LOAD_NAME 1 (map)
6 LOAD_NAME 2 (f)
9 LOAD_NAME 3 (xs)
12 CALL_FUNCTION 2
15 CALL_FUNCTION 1
18 RETURN_VALUE
</code></pre>
<p>It seems it is better to use <code>[...]</code> syntax than <code>list(...)</code>. Sadly the <code>map</code> class is a bit opaque to disassembly, but we can make due with our speed test.</p>
| 244 | 2011-06-20T05:41:27Z | [
"python",
"list-comprehension",
"map-function"
] |
Python List Comprehension Vs. Map | 1,247,486 | <p>Is there a reason to prefer using <code>map()</code> over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other?</p>
| 376 | 2009-08-07T23:43:31Z | 13,483,314 | <h2>You should use <code>map</code> and <code>filter</code> instead of list comprehensions.</h2>
<p>An <strong>objective</strong> reason why you should prefer them even though they're not "Pythonic" is this:<br>
They require functions/lambdas as arguments, which <strong>introduce a new scope</strong>.</p>
<p>I've gotten bitten by this more than once:</p>
<pre><code>for x, y in somePoints:
# (several lines of code here)
squared = [x ** 2 for x in numbers]
# Oops, x was silently overwritten!
</code></pre>
<p>but if instead I had said:</p>
<pre><code>for x, y in somePoints:
# (several lines of code here)
squared = map(lambda x: x ** 2, numbers)
</code></pre>
<p>then everything would've been fine.</p>
<p>You could say I was being silly for using the same variable name in the same scope.</p>
<p>I wasn't. The code was fine originally -- the two <code>x</code>s weren't in the same scope.<br>
It was only after I <strong>moved</strong> the inner block to a different section of the code that the problem came up (read: problem during maintenance, not development), and I didn't expect it.</p>
<p>Yes, <em>if you never make this mistake</em> then list comprehensions are more elegant.<br>
But from personal experience (and from seeing others make the same mistake) I've seen it happen enough times that I think it's not worth the pain you have to go through when these bugs creep into your code.</p>
<h3>Conclusion:</h3>
<p>Use <code>map</code> and <code>filter</code>. They prevent subtle hard-to-diagnose scope-related bugs.</p>
<h3>Side note:</h3>
<p>Don't forget to consider using <code>imap</code> and <code>ifilter</code> (in <code>itertools</code>) if they are appropriate for your situation!</p>
| 46 | 2012-11-20T22:28:55Z | [
"python",
"list-comprehension",
"map-function"
] |
Python List Comprehension Vs. Map | 1,247,486 | <p>Is there a reason to prefer using <code>map()</code> over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other?</p>
| 376 | 2009-08-07T23:43:31Z | 19,117,067 | <p>Actually, <code>map</code> and list comprehensions behave quite differently in the Python 3 language. Take a look at the following Python 3 program:</p>
<pre><code>def square(x):
return x*x
squares = map(square, [1, 2, 3])
print(list(squares))
print(list(squares))
</code></pre>
<p>You might expect it to print the line "[1, 4, 9]" twice, but instead it prints "[1, 4, 9]" followed by "[]". The first time you look at <code>squares</code> it seems to behave as a sequence of three elements, but the second time as an empty one.</p>
<p>In the Python 2 language <code>map</code> returns a plain old list, just like list comprehensions do in both languages. The crux is that the return value of <code>map</code> in Python 3 (and <code>imap</code> in Python 2) is not a list - it's an iterator!</p>
<p>The elements are consumed when you iterate over an iterator unlike when you iterate over a list. This is why <code>squares</code> looks empty in the last <code>print(list(squares))</code> line.</p>
<p>To summarize:</p>
<ul>
<li><strong>When dealing with iterators you have to remember that they are stateful and that they mutate as you traverse them.</strong></li>
<li>Lists are more predictable since they only change when you explicitly mutate them; they are <em>containers</em>.</li>
<li>And a bonus: numbers, strings, and tuples are even more predictable since they cannot change at all; they are <em>values</em>.</li>
</ul>
| 23 | 2013-10-01T13:09:13Z | [
"python",
"list-comprehension",
"map-function"
] |
Python List Comprehension Vs. Map | 1,247,486 | <p>Is there a reason to prefer using <code>map()</code> over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other?</p>
| 376 | 2009-08-07T23:43:31Z | 24,108,573 | <p>If you plan on writing any asynchronous, parallel, or distributed code, you will probably prefer <code>map</code> over a list comprehension -- as most asynchronous, parallel, or distributed packages provide a <code>map</code> function to overload python's <code>map</code>. Then by passing the appropriate <code>map</code> function to the rest of your code, you may not have to modify your original serial code to have it run in parallel (etc).</p>
| 8 | 2014-06-08T17:03:13Z | [
"python",
"list-comprehension",
"map-function"
] |
django extreme slowness | 1,247,501 | <p>I have a slowness problem with Django and I can't find the source .. I'm not sure what I'm doing wrong, but at least twice while working on projects Django became really slow.</p>
<p>Requests takes age to complete (~15 seconds) and Validating model when starting the development server is also very slow (12+ seconds on a quad core..)</p>
<p>I've tried many solution found on the net for similar problem, but they don't seem related to me.</p>
<p>The problem doesn't seem to come from Django's development server since the request are also very slow on the production server with apache and mod_python.</p>
<p>Then I thought it might be a DNS issue, but the site loads instantly when served with Apache2.</p>
<p>I tried to strace the development server, but I didn't find anything interesting.</p>
<p>Even commenting all the apps (except django apps) didn't change anything.. models still take age to validate.</p>
<p>I really don't know where I should be looking now ..</p>
<p>Anybody has an idea ?</p>
| 2 | 2009-08-07T23:47:54Z | 1,247,506 | <blockquote>
<p>Then I thought it might be a DNS
issue, but the site loads instantly
when served with Apache2.</p>
</blockquote>
<p>How are you serving your Django site? I presume you're running mod_python on Apache2? </p>
<p>You may want to start by running an Apache2 locally on you computer (use MAMP or WAMP and install mod_python there) and seeing if it's still slow. Then you can tell whether it's a django/python issue or an Apache/mod_python issue</p>
| 0 | 2009-08-07T23:51:12Z | [
"python",
"django"
] |
django extreme slowness | 1,247,501 | <p>I have a slowness problem with Django and I can't find the source .. I'm not sure what I'm doing wrong, but at least twice while working on projects Django became really slow.</p>
<p>Requests takes age to complete (~15 seconds) and Validating model when starting the development server is also very slow (12+ seconds on a quad core..)</p>
<p>I've tried many solution found on the net for similar problem, but they don't seem related to me.</p>
<p>The problem doesn't seem to come from Django's development server since the request are also very slow on the production server with apache and mod_python.</p>
<p>Then I thought it might be a DNS issue, but the site loads instantly when served with Apache2.</p>
<p>I tried to strace the development server, but I didn't find anything interesting.</p>
<p>Even commenting all the apps (except django apps) didn't change anything.. models still take age to validate.</p>
<p>I really don't know where I should be looking now ..</p>
<p>Anybody has an idea ?</p>
| 2 | 2009-08-07T23:47:54Z | 1,247,516 | <p>I've posted <a href="http://serverfault.com/questions/47112/django-site-performance-problem">this question</a> on serverfault maybe it will help you. </p>
<p>If you are serving big static files - those will slow down response.</p>
<p>This will be the case in any mode if your mod_python or development server process big static files like images, client scripts, etc.</p>
<p>You want to configure the production server to handle those files directly - i.e. bypassing the modules.</p>
<p>btw, mod_wsgi is nowadays the preferred way to run django in the production environment.</p>
<p>If you have issues with system services or hardware then you might get some clues from <a href="http://www.cyberciti.biz/faq/linux-log-files-location-and-how-do-i-view-logs-files/" rel="nofollow">log messages</a>. </p>
| 6 | 2009-08-07T23:54:41Z | [
"python",
"django"
] |
django extreme slowness | 1,247,501 | <p>I have a slowness problem with Django and I can't find the source .. I'm not sure what I'm doing wrong, but at least twice while working on projects Django became really slow.</p>
<p>Requests takes age to complete (~15 seconds) and Validating model when starting the development server is also very slow (12+ seconds on a quad core..)</p>
<p>I've tried many solution found on the net for similar problem, but they don't seem related to me.</p>
<p>The problem doesn't seem to come from Django's development server since the request are also very slow on the production server with apache and mod_python.</p>
<p>Then I thought it might be a DNS issue, but the site loads instantly when served with Apache2.</p>
<p>I tried to strace the development server, but I didn't find anything interesting.</p>
<p>Even commenting all the apps (except django apps) didn't change anything.. models still take age to validate.</p>
<p>I really don't know where I should be looking now ..</p>
<p>Anybody has an idea ?</p>
| 2 | 2009-08-07T23:47:54Z | 1,247,774 | <p>I've once used remote edit to develop my Django site. The validating process seem to be very slow too. But, everything else is fine not like yours. </p>
<p>It's come from the webserver can't add/change .pyc in that directory.</p>
| 0 | 2009-08-08T02:16:33Z | [
"python",
"django"
] |
django extreme slowness | 1,247,501 | <p>I have a slowness problem with Django and I can't find the source .. I'm not sure what I'm doing wrong, but at least twice while working on projects Django became really slow.</p>
<p>Requests takes age to complete (~15 seconds) and Validating model when starting the development server is also very slow (12+ seconds on a quad core..)</p>
<p>I've tried many solution found on the net for similar problem, but they don't seem related to me.</p>
<p>The problem doesn't seem to come from Django's development server since the request are also very slow on the production server with apache and mod_python.</p>
<p>Then I thought it might be a DNS issue, but the site loads instantly when served with Apache2.</p>
<p>I tried to strace the development server, but I didn't find anything interesting.</p>
<p>Even commenting all the apps (except django apps) didn't change anything.. models still take age to validate.</p>
<p>I really don't know where I should be looking now ..</p>
<p>Anybody has an idea ?</p>
| 2 | 2009-08-07T23:47:54Z | 1,248,504 | <p>If the validating models takes forever don't search for anything else. On a dual core some of my largest enterprise applications (+30 models) take less then a second to validate.</p>
<p>The problem must lie somewhere with your models but without source code it's hard to tell what the problem is.</p>
<p>Kind regards,
Michael</p>
<p>Open Source Consultant</p>
| 0 | 2009-08-08T10:16:52Z | [
"python",
"django"
] |
Finding the domain name of a site that is hotlinking in Google app engine using web2py | 1,247,593 | <p>Let's say we have an image in the Google App Engine and sites are hotlinking it.
How can I find the domain names of the sites?</p>
<p>My first thought was:</p>
<blockquote>
<p>request.client</p>
</blockquote>
<p>and then do a reverse lookup but that it's not possible in GAE and would take a lot of time.
I am pretty sure that there is a property that allows me to get the url of the site that is requesting the file
(somewhere in request?). GAE has a <a href="http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html" rel="nofollow">Request class</a> but I couldn't make it work inside web2py.</p>
<p>Any ideas?</p>
| 2 | 2009-08-08T00:26:46Z | 1,247,600 | <p>You can easily get the referrer from the request headers. This referrer can be spoofed, but most people do not spoof it and it is already resolved.</p>
<p>There is no automatic way to resolve the DNS other than manually resolving it. Like you said, a DNS resolution takes extra time and it makes no sense for Web2Py or any other framework to do it.</p>
| 2 | 2009-08-08T00:31:28Z | [
"python",
"google-app-engine",
"web2py",
"reverse-lookup"
] |
Finding the domain name of a site that is hotlinking in Google app engine using web2py | 1,247,593 | <p>Let's say we have an image in the Google App Engine and sites are hotlinking it.
How can I find the domain names of the sites?</p>
<p>My first thought was:</p>
<blockquote>
<p>request.client</p>
</blockquote>
<p>and then do a reverse lookup but that it's not possible in GAE and would take a lot of time.
I am pretty sure that there is a property that allows me to get the url of the site that is requesting the file
(somewhere in request?). GAE has a <a href="http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html" rel="nofollow">Request class</a> but I couldn't make it work inside web2py.</p>
<p>Any ideas?</p>
| 2 | 2009-08-08T00:26:46Z | 1,247,766 | <p>If you're just looking to find out the domain names (not to block the requests by running a script when the image URL is requested), then they'll be in the request logs. In the admin thingy go to "Logs", select "Requests only" from the drop-down. If you expand "Options" you can filter on the relevant filename.</p>
<p>Then expand each request log entry, and the referer is either a hyphen, or the string in quotes immediately following the 200 (or whatever) status code and the size transferred. Chances are very high that not all of the clients have blocked or spoofed the header, so you'll see the URLs linked from.</p>
<p>You can also download the logs using the SDK, and search/process them locally:</p>
<pre><code>appcfg.py --email=whatever request_logs some_filename
</code></pre>
| 1 | 2009-08-08T02:08:47Z | [
"python",
"google-app-engine",
"web2py",
"reverse-lookup"
] |
Web Service require Python List as argument. Need to invoke from C# | 1,247,638 | <p>I need to consume a webservice over XML-RPC. The webservice is written in Python, and one of the arguments is a Python list.</p>
<p>I'm using <a href="http://xml-rpc.net/" rel="nofollow">XML-RPC.NET</a> to invoke all the methods and it works fine, except for those that require a Python list argument.</p>
<p>What would be the corresponding structure in C# which, if I pass as the argument, would be construed by the web service as a Python list? I've tried Python-style code in a string. I've also tried string arrays. </p>
<p>Any example would be really helpful.</p>
<p>Thanks,
V</p>
| 1 | 2009-08-08T00:50:28Z | 1,247,642 | <p>What you need to obtain in the underlying XML is an <code><array></code> tag, e.g.</p>
<pre><code><array>
<data>
<value><i4>12</i4></value>
<value><string>Egypt</string></value>
<value><boolean>0</boolean></value>
<value><i4>-31</i4></value>
</data>
</array>
</code></pre>
<p>for Python list</p>
<pre><code>[12, 'Egypt', False, -31]
</code></pre>
<p>How you get XML-RPC.NET to emit an <code><array></code> tag with a heterogenous "array", I'm not sure. Do you have a way to visualize the XML that's getting emitted for certain C# input constructs/data structures...?</p>
| 1 | 2009-08-08T00:55:33Z | [
"c#",
"python",
"xml-rpc"
] |
Web Service require Python List as argument. Need to invoke from C# | 1,247,638 | <p>I need to consume a webservice over XML-RPC. The webservice is written in Python, and one of the arguments is a Python list.</p>
<p>I'm using <a href="http://xml-rpc.net/" rel="nofollow">XML-RPC.NET</a> to invoke all the methods and it works fine, except for those that require a Python list argument.</p>
<p>What would be the corresponding structure in C# which, if I pass as the argument, would be construed by the web service as a Python list? I've tried Python-style code in a string. I've also tried string arrays. </p>
<p>Any example would be really helpful.</p>
<p>Thanks,
V</p>
| 1 | 2009-08-08T00:50:28Z | 1,247,655 | <p>You need to use arrays of System.Object[]. See <a href="http://www.xml-rpc.net/faq/xmlrpcnetfaq.html#1.12" rel="nofollow">http://www.xml-rpc.net/faq/xmlrpcnetfaq.html#1.12</a> These are generally equivalent to Python lists.</p>
| 2 | 2009-08-08T01:04:13Z | [
"c#",
"python",
"xml-rpc"
] |
Python - printing out all references to a specific instance | 1,247,697 | <p>I am investigating garbage collection issues in a Python app. What would be the best readable option to print out all variables referencing a specific instance?</p>
| 4 | 2009-08-08T01:24:23Z | 1,248,024 | <p>Use the inspect module. This script helps if you just want to track down reference leaks:</p>
<p><a href="http://mg.pov.lt/objgraph.py" rel="nofollow">http://mg.pov.lt/objgraph.py</a> <a href="http://mg.pov.lt/blog/hunting-python-memleaks" rel="nofollow">http://mg.pov.lt/blog/hunting-python-memleaks</a> <a href="http://mg.pov.lt/blog/python-object-graphs.html" rel="nofollow">http://mg.pov.lt/blog/python-object-graphs.html</a></p>
| 3 | 2009-08-08T05:04:25Z | [
"python",
"oop",
"garbage-collection"
] |
Python - printing out all references to a specific instance | 1,247,697 | <p>I am investigating garbage collection issues in a Python app. What would be the best readable option to print out all variables referencing a specific instance?</p>
| 4 | 2009-08-08T01:24:23Z | 1,248,398 | <p>Try <a href="http://pythonic.pocoo.org/2009/5/30/finding-objects-names" rel="nofollow">Finding objects' names</a>, it prints all names that reference a given object.</p>
| 2 | 2009-08-08T09:06:38Z | [
"python",
"oop",
"garbage-collection"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 1,247,869 | <p>Monty never opens the door with the car - that's the whole point of the show (he isn't your friend an has knowledge of what is behind each door)</p>
| 0 | 2009-08-08T03:17:27Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 1,247,875 | <p>You mentioned that all the choices are hardcoded in. But if you look closer, you'll notice that what you think are 'choices' are actually not choices at all. Monty's decision is without loss of generality since he always chooses the door with the goat behind it. Your swapping is always determined by what Monty chooses, and since Monty's "choice" was actually not a choice, neither is yours. Your simulation gives the correct results.. </p>
| 1 | 2009-08-08T03:20:44Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 1,247,888 | <p>Your solution is fine, but if you want a stricter simulation of the problem as posed (and somewhat higher-quality Python;-), try:</p>
<pre><code>import random
iterations = 100000
doors = ["goat"] * 2 + ["car"]
change_wins = 0
change_loses = 0
for i in xrange(iterations):
random.shuffle(doors)
# you pick door n:
n = random.randrange(3)
# monty picks door k, k!=n and doors[k]!="car"
sequence = range(3)
random.shuffle(sequence)
for k in sequence:
if k == n or doors[k] == "car":
continue
# now if you change, you lose iff doors[n]=="car"
if doors[n] == "car":
change_loses += 1
else:
change_wins += 1
print "Changing has %s wins and %s losses" % (change_wins, change_loses)
perc = (100.0 * change_wins) / (change_wins + change_loses)
print "IOW, by changing you win %.1f%% of the time" % perc
</code></pre>
<p>a typical output is:</p>
<pre><code>Changing has 66721 wins and 33279 losses
IOW, by changing you win 66.7% of the time
</code></pre>
| 32 | 2009-08-08T03:28:15Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 1,249,100 | <p>I like something like this.</p>
<pre><code>
#!/usr/bin/python
import random
CAR = 1
GOAT = 0
def one_trial( doors, switch=False ):
"""One trial of the Monty Hall contest."""
random.shuffle( doors )
first_choice = doors.pop( )
if switch==False:
return first_choice
elif doors.__contains__(CAR):
return CAR
else:
return GOAT
def n_trials( switch=False, n=10 ):
"""Play the game N times and return some stats."""
wins = 0
for n in xrange(n):
doors = [CAR, GOAT, GOAT]
wins += one_trial( doors, switch=switch )
print "won:", wins, "lost:", (n-wins), "avg:", (float(wins)/float(n))
if __name__=="__main__":
import sys
n_trials( switch=eval(sys.argv[1]), n=int(sys.argv[2]) )
$ ./montyhall.py True 10000
won: 6744 lost: 3255 avg: 0.674467446745
</code></pre>
| 1 | 2009-08-08T15:00:23Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 3,617,844 | <p>Here is an interactive version:</p>
<pre><code>from random import shuffle, choice
cars,goats,iters= 0, 0, 100
for i in range(iters):
doors = ['goat A', 'goat B', 'car']
shuffle(doors)
moderator_door = 'car'
#Turn 1:
selected_door = choice(doors)
print selected_door
doors.remove(selected_door)
print 'You have selected a door with an unknown object'
#Turn 2:
while moderator_door == 'car':
moderator_door = choice(doors)
doors.remove(moderator_door)
print 'Moderator has opened a door with ', moderator_door
#Turn 3:
decision=raw_input('Wanna change your door? [yn]')
if decision=='y':
prise = doors[0]
print 'You have a door with ', prise
elif decision=='n':
prise = selected_door
print 'You have a door with ', prise
else:
prise = 'ERROR'
iters += 1
print 'ERROR:unknown command'
if prise == 'car':
cars += 1
elif prise != 'ERROR':
goats += 1
print '==============================='
print ' RESULTS '
print '==============================='
print 'Goats:', goats
print 'Cars :', cars
</code></pre>
| 0 | 2010-09-01T12:13:41Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 3,671,645 | <p>I hadn't heard of the Monty Hall Problem before I stumbled across this question. I thought it was interesting, so I read about it and created a c# simulation. It's kind of goofy since it simulates the game-show and not just the problem.</p>
<p>I published the source and release on codeplex:</p>
<p><a href="http://montyhall.codeplex.com" rel="nofollow">http://montyhall.codeplex.com</a></p>
| 1 | 2010-09-08T20:32:35Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 8,225,497 | <p>Another code sample is available at: <a href="http://standardwisdom.com/softwarejournal/code-samples/monty-hall-python/" rel="nofollow">http://standardwisdom.com/softwarejournal/code-samples/monty-hall-python/</a></p>
<p>The code is a bit longer and may not use some of Python's cool features, but I hope it is nicely readable. Used Python precisely because I didn't have any experience in it, so feedback is appreciated.</p>
| 0 | 2011-11-22T10:43:53Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 11,833,365 | <p>My solution with list comprehension to simulate the problem</p>
<pre><code>from random import randint
N = 1000
def simulate(N):
car_gate=[randint(1,3) for x in range(N)]
gate_sel=[randint(1,3) for x in range(N)]
score = sum([True if car_gate[i] == gate_sel[i] or ([posible_gate for posible_gate in [1,2,3] if posible_gate != gate_sel[i]][randint(0,1)] == car_gate[i]) else False for i in range(N)])
return 'you win %s of the time when you change your selection.' % (float(score) / float(N))
</code></pre>
<p>print simulate(N)</p>
| 0 | 2012-08-06T17:52:48Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 15,328,086 | <p>Here is different variant I find most intuitive. Hope this helps!</p>
<pre><code>import random
class MontyHall():
"""A Monty Hall game simulator."""
def __init__(self):
self.doors = ['Door #1', 'Door #2', 'Door #3']
self.prize_door = random.choice(self.doors)
self.contestant_choice = ""
self.monty_show = ""
self.contestant_switch = ""
self.contestant_final_choice = ""
self.outcome = ""
def Contestant_Chooses(self):
self.contestant_choice = random.choice(self.doors)
def Monty_Shows(self):
monty_choices = [door for door in self.doors if door not in [self.contestant_choice, self.prize_door]]
self.monty_show = random.choice(monty_choices)
def Contestant_Revises(self):
self.contestant_switch = random.choice([True, False])
if self.contestant_switch == True:
self.contestant_final_choice = [door for door in self.doors if door not in [self.contestant_choice, self.monty_show]][0]
else:
self.contestant_final_choice = self.contestant_choice
def Score(self):
if self.contestant_final_choice == self.prize_door:
self.outcome = "Win"
else:
self.outcome = "Lose"
def _ShowState(self):
print "-" * 50
print "Doors %s" % self.doors
print "Prize Door %s" % self.prize_door
print "Contestant Choice %s" % self.contestant_choice
print "Monty Show %s" % self.monty_show
print "Contestant Switch %s" % self.contestant_switch
print "Contestant Final Choice %s" % self.contestant_final_choice
print "Outcome %s" % self.outcome
print "-" * 50
Switch_Wins = 0
NoSwitch_Wins = 0
Switch_Lose = 0
NoSwitch_Lose = 0
for x in range(100000):
game = MontyHall()
game.Contestant_Chooses()
game.Monty_Shows()
game.Contestant_Revises()
game.Score()
# Tally Up the Scores
if game.contestant_switch and game.outcome == "Win": Switch_Wins = Switch_Wins + 1
if not(game.contestant_switch) and game.outcome == "Win": NoSwitch_Wins = NoSwitch_Wins + 1
if game.contestant_switch and game.outcome == "Lose": Switch_Lose = Switch_Lose + 1
if not(game.contestant_switch) and game.outcome == "Lose": NoSwitch_Lose = NoSwitch_Lose + 1
print Switch_Wins * 1.0 / (Switch_Wins + Switch_Lose)
print NoSwitch_Wins * 1.0 / (NoSwitch_Wins + NoSwitch_Lose)
</code></pre>
<p>The learning is still the same, that switching increases your chances of winning, 0.665025416127 vs 0.33554730611 from the above run.</p>
| 0 | 2013-03-10T21:48:45Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 18,693,512 | <p>Not mine sample</p>
<pre><code># -*- coding: utf-8 -*-
#!/usr/bin/python -Ou
# Written by kocmuk.ru, 2008
import random
num = 10000 # number of games to play
win = 0 # init win count if donot change our first choice
for i in range(1, num): # play "num" games
if random.randint(1,3) == random.randint(1,3): # if win at first choice
win +=1 # increasing win count
print "I donot change first choice and win:", win, " games"
print "I change initial choice and win:", num-win, " games" # looses of "not_change_first_choice are wins if changing
</code></pre>
| 0 | 2013-09-09T07:38:04Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 20,641,764 | <p>Here's one I made earlier:</p>
<pre><code>import random
def game():
"""
Set up three doors, one randomly with a car behind and two with
goats behind. Choose a door randomly, then the presenter takes away
one of the goats. Return the outcome based on whether you stuck with
your original choice or switched to the other remaining closed door.
"""
# Neither stick or switch has won yet, so set them both to False
stick = switch = False
# Set all of the doors to goats (zeroes)
doors = [ 0, 0, 0 ]
# Randomly change one of the goats for a car (one)
doors[random.randint(0, 2)] = 1
# Randomly choose one of the doors out of the three
choice = doors[random.randint(0, 2)]
# If our choice was a car (a one)
if choice == 1:
# Then stick wins
stick = True
else:
# Otherwise, because the presenter would take away the other
# goat, switching would always win.
switch = True
return (stick, switch)
</code></pre>
<p>I also had code to run the game many times, and stored this and the sample output <a href="https://bitbucket.org/flyte/monty-hall-problem" rel="nofollow">in this repostory</a>.</p>
| 0 | 2013-12-17T18:18:54Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 24,590,519 | <p>Here is my solution to the MontyHall problem implemented in python.</p>
<p>This solution makes use of numpy for speed, it also allows you to change the number of doors.</p>
<pre><code>def montyhall(Trials:"Number of trials",Doors:"Amount of doors",P:"Output debug"):
N = Trials # the amount of trial
DoorSize = Doors+1
Answer = (nprand.randint(1,DoorSize,N))
OtherDoor = (nprand.randint(1,DoorSize,N))
UserDoorChoice = (nprand.randint(1,DoorSize,N))
# this will generate a second door that is not the user's selected door
C = np.where( (UserDoorChoice==OtherDoor)>0 )[0]
while (len(C)>0):
OtherDoor[C] = nprand.randint(1,DoorSize,len(C))
C = np.where( (UserDoorChoice==OtherDoor)>0 )[0]
# place the car as the other choice for when the user got it wrong
D = np.where( (UserDoorChoice!=Answer)>0 )[0]
OtherDoor[D] = Answer[D]
'''
IfUserStays = 0
IfUserChanges = 0
for n in range(0,N):
IfUserStays += 1 if Answer[n]==UserDoorChoice[n] else 0
IfUserChanges += 1 if Answer[n]==OtherDoor[n] else 0
'''
IfUserStays = float(len( np.where((Answer==UserDoorChoice)>0)[0] ))
IfUserChanges = float(len( np.where((Answer==OtherDoor)>0)[0] ))
if P:
print("Answer ="+str(Answer))
print("Other ="+str(OtherDoor))
print("UserDoorChoice="+str(UserDoorChoice))
print("OtherDoor ="+str(OtherDoor))
print("results")
print("UserDoorChoice="+str(UserDoorChoice==Answer)+" n="+str(IfUserStays)+" r="+str(IfUserStays/N))
print("OtherDoor ="+str(OtherDoor==Answer)+" n="+str(IfUserChanges)+" r="+str(IfUserChanges/N))
return IfUserStays/N, IfUserChanges/N
</code></pre>
| 0 | 2014-07-05T21:00:01Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 29,750,121 | <p>Here's my version ...</p>
<pre><code># by peedurrr
#
import random
wins = 0
for n in range(1000):
doors = [1, 2, 3]
carDoor = random.choice(doors)
playerDoor = random.choice(doors)
hostDoor = random.choice(list(set(doors) - set([carDoor, playerDoor])))
# To stick, just comment out the next line.
(playerDoor, ) = set(doors) - set([playerDoor, hostDoor]) # Player swaps doors.
if playerDoor == carDoor:
wins += 1
print str(round(wins / float(n) * 100, 2)) + '%'
</code></pre>
| 1 | 2015-04-20T14:03:47Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 30,945,981 | <p>I found this to be the most intuitive way of solving the problem.</p>
<pre><code>import random
# game_show will return True/False if the participant wins/loses the car:
def game_show(knows_bayes):
doors = [i for i in range(3)]
# Let the car be behind this door
car = random.choice(doors)
# The participant chooses this door..
choice = random.choice(doors)
# ..so the host opens another (random) door with no car behind it
open_door = random.choice([i for i in doors if i not in [car, choice]])
# If the participant knows_bayes she will switch doors now
if knows_bayes:
choice = [i for i in doors if i not in [choice, open_door]][0]
# Did the participant win a car?
if choice == car:
return True
else:
return False
# Let us run the game_show() for two participants. One knows_bayes and the other does not.
wins = [0, 0]
runs = 100000
for x in range(0, runs):
if game_show(True):
wins[0] += 1
if game_show(False):
wins[1] += 1
print "If the participant knows_bayes she wins %d %% of the time." % (float(wins[0])/runs*100)
print "If the participant does NOT knows_bayes she wins %d %% of the time." % (float(wins[1])/runs*100)
</code></pre>
<p>This outputs something like</p>
<pre><code>If the participant knows_bayes she wins 66 % of the time.
If the participant does NOT knows_bayes she wins 33 % of the time.
</code></pre>
| 0 | 2015-06-19T19:35:17Z | [
"python",
"language-agnostic",
"probability"
] |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | <p>Through trying to explain the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">Monty Hall problem</a> to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:</p>
<pre><code>import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
</code></pre>
<p>My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?</p>
<p>The problem I have with it is that the all choices are kind of hard coded in.</p>
<p><strong>Is this a good or bad 'simulation' for the Monty Hall problem? How come?</strong></p>
<p><strong>Can you come up with a better version?</strong></p>
| 14 | 2009-08-08T03:13:17Z | 37,274,039 | <p>Read a chapter about the famous Monty Hall problem today. This is my solution. </p>
<pre><code>import random
def one_round():
doors = [1,1,0] # 1==goat, 0=car
random.shuffle(doors) # shuffle doors
choice = random.randint(0,2)
return doors[choice]
#If a goat is chosen, it means the player loses if he/she does not change.
#This method returns if the player wins or loses if he/she changes. win = 1, lose = 0
def hall():
change_wins = 0
N = 10000
for index in range(0,N):
change_wins += one_round()
print change_wins
hall()
</code></pre>
| 0 | 2016-05-17T10:51:41Z | [
"python",
"language-agnostic",
"probability"
] |
Coroutines for game design? | 1,247,894 | <p>I've heard that coroutines are a good way to structure games (e.g., <a href="http://www.python.org/dev/peps/pep-0342/">PEP 342</a>: "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.</p>
<p>I see from this <a href="http://www.ibm.com/developerworks/library/l-pygen.html">article</a> that coroutines can represent states in a state machine which transition to each other using a scheduler, but it's not clear to me how this applies to a game where the game state is changing based on moves from multiple players.</p>
<p>Is there any simple example of a game written using coroutines available? Or can someone offer a sketch of how it might be done?</p>
| 16 | 2009-08-08T03:31:01Z | 1,247,973 | <p>Two links that you might find interesting:</p>
<p><a href="http://aigamedev.com/open/articles/coroutine-state-machine/" rel="nofollow">http://aigamedev.com/open/articles/coroutine-state-machine/</a></p>
<p><a href="http://www.dabeaz.com/coroutines/" rel="nofollow">http://www.dabeaz.com/coroutines/</a> (search for 'task' in this page and pdf)</p>
| 2 | 2009-08-08T04:28:34Z | [
"python",
"coroutine"
] |
Coroutines for game design? | 1,247,894 | <p>I've heard that coroutines are a good way to structure games (e.g., <a href="http://www.python.org/dev/peps/pep-0342/">PEP 342</a>: "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.</p>
<p>I see from this <a href="http://www.ibm.com/developerworks/library/l-pygen.html">article</a> that coroutines can represent states in a state machine which transition to each other using a scheduler, but it's not clear to me how this applies to a game where the game state is changing based on moves from multiple players.</p>
<p>Is there any simple example of a game written using coroutines available? Or can someone offer a sketch of how it might be done?</p>
| 16 | 2009-08-08T03:31:01Z | 1,247,985 | <p>Coroutines allow for creating large amounts of very-lightweight "microthreads" with cooperative multitasking (i.e. microthreads suspending themselves willfully to allow other microthreads to run). Read up in Dave Beazley's <a href="http://www.dabeaz.com/coroutines/">article</a> on this subject.</p>
<p>Now, it's obvious how such microthreads can be useful for game programming. Consider a realtime strategy game, where you have dozens of units - each with a mind of its own. It may be a convenient abstraction for each unit's AI to run as such a microthread in your simulated multitasking environment. This is just one example, I'm sure there are more.</p>
<p>The "coroutine game programming" search on Google seems to bring up interesting results.</p>
| 9 | 2009-08-08T04:35:05Z | [
"python",
"coroutine"
] |
Coroutines for game design? | 1,247,894 | <p>I've heard that coroutines are a good way to structure games (e.g., <a href="http://www.python.org/dev/peps/pep-0342/">PEP 342</a>: "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.</p>
<p>I see from this <a href="http://www.ibm.com/developerworks/library/l-pygen.html">article</a> that coroutines can represent states in a state machine which transition to each other using a scheduler, but it's not clear to me how this applies to a game where the game state is changing based on moves from multiple players.</p>
<p>Is there any simple example of a game written using coroutines available? Or can someone offer a sketch of how it might be done?</p>
| 16 | 2009-08-08T03:31:01Z | 1,247,990 | <p>One way coroutines can be used in games is as light weight threads in an actor like model, like in <a href="http://www.kamaelia.org/Home">Kamaelia</a>.</p>
<p>Each object in your game would be a Kamaelia 'component'. A component is an object that can pause execution by yielding when it's allowable to pause. These components also have a messaging system that allows them to safely communicate to each other asynchronously.</p>
<p>All the objects would be concurrently doing their own thing, with messages sent to each other when interactions occur.</p>
<p>So, it's not really specific to games, but anything when you have a multitude of communicating components acting concurrently could benefit from coroutines.</p>
| 7 | 2009-08-08T04:37:30Z | [
"python",
"coroutine"
] |
Coroutines for game design? | 1,247,894 | <p>I've heard that coroutines are a good way to structure games (e.g., <a href="http://www.python.org/dev/peps/pep-0342/">PEP 342</a>: "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.</p>
<p>I see from this <a href="http://www.ibm.com/developerworks/library/l-pygen.html">article</a> that coroutines can represent states in a state machine which transition to each other using a scheduler, but it's not clear to me how this applies to a game where the game state is changing based on moves from multiple players.</p>
<p>Is there any simple example of a game written using coroutines available? Or can someone offer a sketch of how it might be done?</p>
| 16 | 2009-08-08T03:31:01Z | 1,250,992 | <p>The most prominent case of coroutines are probally old graphical point&click adventure games, where they where used to script cutscenes and other animated sequences in the game. A simple code example would look like this:</p>
<pre><code># script_file.scr
bob.walkto(jane)
bob.lookat(jane)
bob.say("How are you?")
wait(2)
jane.say("Fine")
...
</code></pre>
<p>This whole sequence can't be written as normal code, as you want to see bob do his walk animation after you did <code>bob.walkto(jane)</code> instead of jumping right to the next line. For the walk animation to play you however need to give control back to the game engine and that is where coroutines come into play.</p>
<p>This whole sequence is executed as a coroutine, meaning you have the ability to suspend and resume it as you like. A command like <code>bob.walkto(jane)</code> thus tells the engine side bob object its target and then suspends the coroutine, waiting for a wakeup call when bob has reached his target.</p>
<p>On the engine side things might look like this (pseudo code):</p>
<pre><code>class Script:
def __init__(self, filename):
self.coroutine = Coroutine(filename)
self.is_wokenup = True
def wakeup(self):
self.is_wokenup = False;
def update():
if self.is_wokenup:
coroutine.run()
class Character:
def walkto(self, target, script):
self.script = script
self.target = target
def update(self):
if target:
move_one_step_closer_to(self.target)
if close_enough_to(self.target):
self.script.wakeup()
self.target = None
self.script = None
objects = [Character("bob"), Character("jane")]
scripts = [Script("script_file.scr")]
while True:
for obj in objects:
obj.update()
for scr in scripts:
scr.update()
</code></pre>
<p>A litte word of warning however, while coroutines make coding these sequences very simple, not every implementations you will find of them will be build with serialisation in mind, so game saving will become quite a troublesome issue if you make heavy use of coroutines.</p>
<p>This example is also just the most basic case of a coroutine in a game, coroutines themselves can be used for plenty of other tasks and algorithms as well.</p>
| 8 | 2009-08-09T09:11:34Z | [
"python",
"coroutine"
] |
Coroutines for game design? | 1,247,894 | <p>I've heard that coroutines are a good way to structure games (e.g., <a href="http://www.python.org/dev/peps/pep-0342/">PEP 342</a>: "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.</p>
<p>I see from this <a href="http://www.ibm.com/developerworks/library/l-pygen.html">article</a> that coroutines can represent states in a state machine which transition to each other using a scheduler, but it's not clear to me how this applies to a game where the game state is changing based on moves from multiple players.</p>
<p>Is there any simple example of a game written using coroutines available? Or can someone offer a sketch of how it might be done?</p>
| 16 | 2009-08-08T03:31:01Z | 1,255,130 | <p>It is quite common to want to use coroutines to represent individual actor AI scripts. Unfortunately people tend to forget that coroutines have all the same synchronisation and mutual exclusion problems that threads have, just at a higher level. So you often need to firstly do as much as you can to eliminate local state, and secondly write robust ways to handle the errors in a coroutine that arise when something you were referring to ceases to exist.</p>
<p>So in practice they are quite hard to get a benefit from, which is why languages like UnrealScript that use some semblance of coroutines push much of the useful logic out to atomic events. Some people get good utility out of them, eg. the EVE Online people, but they had to pretty much architect their entire system around the concept. (And how they handle contention over shared resources is not well documented.)</p>
| 1 | 2009-08-10T14:16:26Z | [
"python",
"coroutine"
] |
How to make translucent sprites in pygame | 1,247,921 | <p>I've just started working with pygame and I'm trying to make a semi-transparent sprite, and the sprite's source file is a non-transparent bitmap file loaded from the disk. I don't want to edit the source image if I can help it. I'm sure there's a way to do this with pygame code, but Google is of no help to me.</p>
| 4 | 2009-08-08T03:51:39Z | 1,247,962 | <p>After loading the image, you will need to enable an alpha channel on the <code>Surface</code>. that will look a little like this:</p>
<pre><code>background = pygame.Display.set_mode()
myimage = pygame.image.load("path/to/image.bmp").convert_alpha(background)
</code></pre>
<p>This will load the image and immediately convert it to a pixel format suitable for alpha blending onto the display surface. You could use some other surface if you need to blit to some other, off screen buffer in another format.</p>
<p>You can set per-pixel alpha simply enough, say you have a function which takes a 3-tuple for rgb color value and returns some desired 4tuple of rgba color+alpha, you could alter the surface per pixel:</p>
<pre><code>def set_alphas(color):
if color == (255,255,0): # magenta means clear
return (0,0,0,0)
if color == (0,255,255): # cyan means shadow
return (0,0,0,128)
r,g,b = color
return (r,g,b,255) # otherwise use the solid color from the image.
for row in range(myimage.get_height()):
for col in range(myimage,get_width()):
myimage.set_at((row, col), set_alphas(myimage.get_at((row, col))[:3]))
</code></pre>
<p>There are other, more useful ways to do this, but this gives you the idea, I hope.</p>
| 3 | 2009-08-08T04:21:41Z | [
"python",
"graphics",
"sprite",
"pygame"
] |
How to make translucent sprites in pygame | 1,247,921 | <p>I've just started working with pygame and I'm trying to make a semi-transparent sprite, and the sprite's source file is a non-transparent bitmap file loaded from the disk. I don't want to edit the source image if I can help it. I'm sure there's a way to do this with pygame code, but Google is of no help to me.</p>
| 4 | 2009-08-08T03:51:39Z | 1,247,984 | <p>you might consider switching to using png images where you can do any kind of transparency you want directly in the image.</p>
| 1 | 2009-08-08T04:34:59Z | [
"python",
"graphics",
"sprite",
"pygame"
] |
How to make translucent sprites in pygame | 1,247,921 | <p>I've just started working with pygame and I'm trying to make a semi-transparent sprite, and the sprite's source file is a non-transparent bitmap file loaded from the disk. I don't want to edit the source image if I can help it. I'm sure there's a way to do this with pygame code, but Google is of no help to me.</p>
| 4 | 2009-08-08T03:51:39Z | 1,248,120 | <p>If your image has a solid color background that you want it to became transparent you can set it as <a href="http://www.pygame.org/docs/ref/surface.html#Surface.set%5Fcolorkey" rel="nofollow">color_key</a> value, and pygame will make it transparent when blitting the image.</p>
<p>eg:</p>
<pre><code>color = image.get_at((0,0)) #we get the color of the upper-left corner pixel
image.set_colorkey(color)
</code></pre>
| 2 | 2009-08-08T06:19:04Z | [
"python",
"graphics",
"sprite",
"pygame"
] |
How to make translucent sprites in pygame | 1,247,921 | <p>I've just started working with pygame and I'm trying to make a semi-transparent sprite, and the sprite's source file is a non-transparent bitmap file loaded from the disk. I don't want to edit the source image if I can help it. I'm sure there's a way to do this with pygame code, but Google is of no help to me.</p>
| 4 | 2009-08-08T03:51:39Z | 1,253,061 | <p>I may have not been clear in my original question, but I think I figured it out on my own. What I was looking for turns out to be Surface's set_alpha() method, so all I had to do was make sure that translucent images were on their own surface.</p>
<p>Here's an example with my stripped down code:</p>
<pre><code>import pygame, os.path
from pygame.locals import *
class TranslucentSprite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self, TranslucentSprite.container)
self.image = pygame.image.load(os.path.join('data', 'image.bmp'))
self.image = self.image.convert()
self.image.set_colorkey(-1, RLEACCEL)
self.rect = self.image.get_rect()
self.rect.center = (320,240)
def main():
pygame.init()
screen = pygame.display.set_mode((640,480))
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250,250,250))
clock = pygame.time.Clock()
transgroups = pygame.sprite.Group()
TranslucentSprite.container = transgroups
"""Here's the Translucency Code"""
transsurface = pygame.display.set_mode(screen.get_size())
transsurface = transsurface.convert(screen)
transsurface.fill((255,0,255))
transsurface.set_colorkey((255,0,255))
transsurface.set_alpha(50)
TranslucentSprite()
while 1:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
return
elif event.type == KEYDOWN and event.key == K_ESCAPE:
return
transgroups.draw(transsurface)
screen.blit(background,(0,0))
screen.blit(transsurface,(0,0))
pygame.display.flip()
if __name__ == '__main__' : main()
</code></pre>
<p>Is this the best technique? It seems to be the most simple and straightforward.</p>
| 2 | 2009-08-10T04:01:55Z | [
"python",
"graphics",
"sprite",
"pygame"
] |
What does the "s!" operator in Perl do? | 1,248,812 | <p>I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.</p>
<pre><code> $var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
</code></pre>
<p>What is each line doing? I'd like to know in case I run into this operator again.</p>
<p>And, what would equivalent statements in Python be?</p>
| 4 | 2009-08-08T12:53:43Z | 1,248,825 | <p><code>s!foo!bar!</code> is the same as the more common <code>s/foo/bar/</code>, except that foo and bar can contain unescaped slashes without causing problems. What it does is, it replaces the first occurence of the regex foo with bar. The version with g replaces all occurences.</p>
| 15 | 2009-08-08T12:59:14Z | [
"python",
"regex",
"perl"
] |
What does the "s!" operator in Perl do? | 1,248,812 | <p>I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.</p>
<pre><code> $var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
</code></pre>
<p>What is each line doing? I'd like to know in case I run into this operator again.</p>
<p>And, what would equivalent statements in Python be?</p>
| 4 | 2009-08-08T12:53:43Z | 1,248,831 | <p><code>s</code> is the substitution operator. Normally this uses '/' for the delimiter:</p>
<pre><code>s/foo/bar/
</code></pre>
<p>, but this is not required: a number of other characters can be used as delimiters instead. In this case, '!' has been used as the delimiter, presumably to avoid the need to escape the '/' characters in the actual text to be substituted.</p>
<p>In your specific case, the first line removes text matching '.+?'; i.e. it removes 'foo' tags with or without content.</p>
<p>The second line replaces all ';' characters with '/' characters, globally (all occurences).</p>
<p>The python equivalent code uses the <code>re</code> module:</p>
<pre><code>f=re.sub(searchregx,replacement_str,line)
</code></pre>
| 2 | 2009-08-08T13:01:29Z | [
"python",
"regex",
"perl"
] |
What does the "s!" operator in Perl do? | 1,248,812 | <p>I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.</p>
<pre><code> $var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
</code></pre>
<p>What is each line doing? I'd like to know in case I run into this operator again.</p>
<p>And, what would equivalent statements in Python be?</p>
| 4 | 2009-08-08T12:53:43Z | 1,248,832 | <p>It's doing exactly the same as <code>$var =~ s///</code>. i.e. performing a search and replace within the <code>$var</code> variable.</p>
<p>In Perl you can define the delimiting character following the <code>s</code>. Why ? So, for example, if you're matching '/', you can specify another delimiting character ('!' in this case) and not have to escape or backtick the character you're matching. Otherwise you'd end up with (say)</p>
<pre><code>s/;/\//g;
</code></pre>
<p>which is a little more confusing.</p>
<p><a href="http://perldoc.perl.org/perlre.html" rel="nofollow">Perlre</a> has more info on this.</p>
| 13 | 2009-08-08T13:01:40Z | [
"python",
"regex",
"perl"
] |
What does the "s!" operator in Perl do? | 1,248,812 | <p>I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.</p>
<pre><code> $var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
</code></pre>
<p>What is each line doing? I'd like to know in case I run into this operator again.</p>
<p>And, what would equivalent statements in Python be?</p>
| 4 | 2009-08-08T12:53:43Z | 1,248,834 | <p>And the python equivalent is to use the <code>re</code> module.</p>
| 0 | 2009-08-08T13:01:56Z | [
"python",
"regex",
"perl"
] |
What does the "s!" operator in Perl do? | 1,248,812 | <p>I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.</p>
<pre><code> $var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
</code></pre>
<p>What is each line doing? I'd like to know in case I run into this operator again.</p>
<p>And, what would equivalent statements in Python be?</p>
| 4 | 2009-08-08T12:53:43Z | 1,248,839 | <p>s is the substitution operator. Usually it is in the form of <code>s/foo/bar/</code>, but you can replace // separator characters some other characters like <em>!</em>. Using other separator charaters may make working with things like paths a lot easier since you don't need to escape path separators.</p>
<p>See <a href="http://perldoc.perl.org/perlop.html#Quote-Like-Operators" rel="nofollow">manual page</a> for further info.</p>
<p>You can find similar functionality for python in <a href="http://docs.python.org/library/re.html" rel="nofollow">re-module</a>.</p>
| 3 | 2009-08-08T13:02:34Z | [
"python",
"regex",
"perl"
] |
What does the "s!" operator in Perl do? | 1,248,812 | <p>I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.</p>
<pre><code> $var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
</code></pre>
<p>What is each line doing? I'd like to know in case I run into this operator again.</p>
<p>And, what would equivalent statements in Python be?</p>
| 4 | 2009-08-08T12:53:43Z | 1,248,841 | <p>Perl lets you choose the delimiter for many of its constructs. This makes it easier to see what is going on in expressions like</p>
<pre><code>$str =~ s{/foo/bar/baz/}{/quux/};
</code></pre>
<p>As you can see though, not all delimiters have the same effects. Bracketing characters (<code><></code>, <code>[]</code>, <code>{}</code>, and <code>()</code>) use different characters for the beginning and ending. And <code>?</code>, when used as a delimiter to a regex, causes the regexes to match only once between calls to the <code>reset()</code> operator.</p>
<p>You may find it helpful to read <a href="http://perldoc.perl.org/perlop.html" rel="nofollow"><code>perldoc perlop</code></a> (in particular the sections on <a href="http://perldoc.perl.org/perlop.html#m/PATTERN/msixpogc" rel="nofollow"><code>m/PATTERN/msixpogc</code></a>, <a href="http://perldoc.perl.org/perlop.html#?PATTERN?" rel="nofollow"><code>?PATTERN?</code></a>, and <a href="http://perldoc.perl.org/perlop.html#s/PATTERN/REPLACEMENT/msixpogce" rel="nofollow">s/PATTERN/REPLACEMENT/msixpogce</a>).</p>
| 10 | 2009-08-08T13:02:43Z | [
"python",
"regex",
"perl"
] |
What does the "s!" operator in Perl do? | 1,248,812 | <p>I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.</p>
<pre><code> $var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
</code></pre>
<p>What is each line doing? I'd like to know in case I run into this operator again.</p>
<p>And, what would equivalent statements in Python be?</p>
| 4 | 2009-08-08T12:53:43Z | 1,248,842 | <p><code>s!</code> is syntactic sugar for the 'proper' <code>s///</code> operator. Basically, you can substitute whatever delimiter you want instead of the '/'s.</p>
<p>As to what each line is doing, the first line is matching occurances of the regex <code><foo>.+?</foo></code> and replacing the whole lot with nothing. The second is matching the regex <code>;</code> and replacing it with <code>/</code>.</p>
<p><code>s///</code> is the substitute operator. It takes a regular expression and a substitution string.</p>
<pre><code>s/regex/replace string/;
</code></pre>
<p>It supports most (all?) of the normal regular expression switches, which are used in the normal way (by appending them to the end of the operator).</p>
| 2 | 2009-08-08T13:03:16Z | [
"python",
"regex",
"perl"
] |
Best practise when using httplib2.Http() object | 1,248,926 | <p>I'm writing a pythonic web API wrapper with a class like this</p>
<pre><code>import httplib2
import urllib
class apiWrapper:
def __init__(self):
self.http = httplib2.Http()
def _http(self, url, method, dict):
'''
Im using this wrapper arround the http object
all the time inside the class
'''
params = urllib.urlencode(dict)
response, content = self.http.request(url,params,method)
</code></pre>
<p><hr /></p>
<p>as you can see I'm using the <code>_http()</code> method to simplify the interaction with the <code>httplib2.Http()</code> object. This method is called quite often inside the class and I'm wondering what's the best way to interact with this object:</p>
<ul>
<li>create the object in the <code>__init__</code> and then <strong>reuse</strong> it when the <code>_http()</code> method is called (as shown <strong>in the code above</strong>)</li>
<li>or create the <code>httplib2.Http()</code> object inside the method for every call of the <code>_http()</code> method (as shown <strong>in the code sample below</strong>)</li>
</ul>
<p><hr /></p>
<pre><code>import httplib2
import urllib
class apiWrapper:
def __init__(self):
def _http(self, url, method, dict):
'''Im using this wrapper arround the http object
all the time inside the class'''
http = httplib2.Http()
params = urllib.urlencode(dict)
response, content = http.request(url,params,method)
</code></pre>
| 6 | 2009-08-08T13:53:34Z | 1,249,097 | <p>You should keep the Http object if you reuse connections. It seems httplib2 is capable of reusing connections the way you use it in your first code, so this looks like a good approach.</p>
<p>At the same time, from a shallow inspection of the httplib2 code, it seems that httplib2 has no support for cleaning up unused connections, or to even notice when a server has decided to close a connection it no longer wants. If that is indeed the case, it looks like a bug in httplib2 to me - so I would rather use the standard library (httplib) instead.</p>
| 2 | 2009-08-08T14:59:42Z | [
"python",
"httplib2"
] |
Best practise when using httplib2.Http() object | 1,248,926 | <p>I'm writing a pythonic web API wrapper with a class like this</p>
<pre><code>import httplib2
import urllib
class apiWrapper:
def __init__(self):
self.http = httplib2.Http()
def _http(self, url, method, dict):
'''
Im using this wrapper arround the http object
all the time inside the class
'''
params = urllib.urlencode(dict)
response, content = self.http.request(url,params,method)
</code></pre>
<p><hr /></p>
<p>as you can see I'm using the <code>_http()</code> method to simplify the interaction with the <code>httplib2.Http()</code> object. This method is called quite often inside the class and I'm wondering what's the best way to interact with this object:</p>
<ul>
<li>create the object in the <code>__init__</code> and then <strong>reuse</strong> it when the <code>_http()</code> method is called (as shown <strong>in the code above</strong>)</li>
<li>or create the <code>httplib2.Http()</code> object inside the method for every call of the <code>_http()</code> method (as shown <strong>in the code sample below</strong>)</li>
</ul>
<p><hr /></p>
<pre><code>import httplib2
import urllib
class apiWrapper:
def __init__(self):
def _http(self, url, method, dict):
'''Im using this wrapper arround the http object
all the time inside the class'''
http = httplib2.Http()
params = urllib.urlencode(dict)
response, content = http.request(url,params,method)
</code></pre>
| 6 | 2009-08-08T13:53:34Z | 2,628,458 | <p>Supplying 'connection': 'close' in your headers should according to the docs close the connection after a response is received.:</p>
<pre><code>headers = {'connection': 'close'}
resp, content = h.request(url, headers=headers)
</code></pre>
| 7 | 2010-04-13T09:38:57Z | [
"python",
"httplib2"
] |
Escaping HTML in Python | 1,249,163 | <p>How to escape HTML with characters like <code>&#8211;</code> in Python?</p>
| 1 | 2009-08-08T15:38:17Z | 1,249,326 | <p>If you have a unicode string as input, you can use the xmlcharrefreplace error handler:</p>
<pre><code>py> u"<p>\N{EN DASH}</p>".encode("ascii", "xmlcharrefreplace")
'<p>&#8211;</p>'
</code></pre>
| 2 | 2009-08-08T16:52:23Z | [
"python",
"html",
"escaping"
] |
Escaping HTML in Python | 1,249,163 | <p>How to escape HTML with characters like <code>&#8211;</code> in Python?</p>
| 1 | 2009-08-08T15:38:17Z | 32,679,809 | <p>Try this</p>
<pre><code>import cgi
print cgi.escape("<b>Your HTML Bold Text</b>")
</code></pre>
| 0 | 2015-09-20T13:15:19Z | [
"python",
"html",
"escaping"
] |
Portable command execution syntax implemented in Python | 1,249,165 | <p>Python is not a pretty good language in <em>defining</em> a set of commands to run. Bash is. But Bash does not run naively on Windows.</p>
<p>Background: I am trying to build a set of programs - with established dependency relationships between them - on mac/win/linux. Something like macports but should work on all the three platforms listed.</p>
<p>This begets the necessary to have a shell-like language that can be used to <em>define</em> the command sequence to run for building/patching/etc.. a particular program, for instance:</p>
<pre><code>post-destroot {
xinstall -d ${destroot}${prefix}/share/emacs/${version}/leim
delete ${destroot}${prefix}/bin/ctags
delete ${destroot}${prefix}/share/man/man1/ctags.1
if {[variant_isset carbon]} {
global version
delete ${destroot}${prefix}/bin/emacs ${destroot}${prefix}/bin/emacs-${version}
}
}
</code></pre>
<p>The above is from the <a href="http://svn.macports.org/repository/macports/trunk/dports/editors/emacs/Portfile" rel="nofollow">emacs Portfile in macports</a>. Note the use of variables, conditionals, functions .. besides specifying a simple list of commands to execute in that order.</p>
<p>Although the syntax is not Python, the actual execution semantics has to be deferred to Python using subprocess or whatever. In short, I should be able to 'run' such a script .. but for each command a specified hook function gets called that actually runs any command passed as argument. I hope you get the idea.</p>
| 1 | 2009-08-08T15:38:42Z | 1,249,183 | <p>Sounds like you need some combination of <a href="http://pyparsing.wikispaces.com/" rel="nofollow">PyParsing</a> and <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">Python Subprocess</a>.</p>
<p>I find subprocess a little confusing, despite the <a href="http://blog.doughellmann.com/2007/07/pymotw-subprocess.html" rel="nofollow">MOTW</a> about it, so I use this kind of wrapper code a lot.</p>
<pre><code>from subprocess import Popen, PIPE
def shell(args, input=None):
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(input=input)
return stdout, stderr
</code></pre>
| 2 | 2009-08-08T15:49:25Z | [
"python",
"shell",
"cross-platform",
"command"
] |
Portable command execution syntax implemented in Python | 1,249,165 | <p>Python is not a pretty good language in <em>defining</em> a set of commands to run. Bash is. But Bash does not run naively on Windows.</p>
<p>Background: I am trying to build a set of programs - with established dependency relationships between them - on mac/win/linux. Something like macports but should work on all the three platforms listed.</p>
<p>This begets the necessary to have a shell-like language that can be used to <em>define</em> the command sequence to run for building/patching/etc.. a particular program, for instance:</p>
<pre><code>post-destroot {
xinstall -d ${destroot}${prefix}/share/emacs/${version}/leim
delete ${destroot}${prefix}/bin/ctags
delete ${destroot}${prefix}/share/man/man1/ctags.1
if {[variant_isset carbon]} {
global version
delete ${destroot}${prefix}/bin/emacs ${destroot}${prefix}/bin/emacs-${version}
}
}
</code></pre>
<p>The above is from the <a href="http://svn.macports.org/repository/macports/trunk/dports/editors/emacs/Portfile" rel="nofollow">emacs Portfile in macports</a>. Note the use of variables, conditionals, functions .. besides specifying a simple list of commands to execute in that order.</p>
<p>Although the syntax is not Python, the actual execution semantics has to be deferred to Python using subprocess or whatever. In short, I should be able to 'run' such a script .. but for each command a specified hook function gets called that actually runs any command passed as argument. I hope you get the idea.</p>
| 1 | 2009-08-08T15:38:42Z | 1,249,258 | <p>Ned Batchelder, in <a href="http://nedbatchelder.com/text/python-parsers.html" rel="nofollow">this post</a>, lists several dozens of different tools you might choose to perform parsing, in Python, of some arbitrary language (though I don't quite understand why you don't want to use Python itself as your "language to define a set of commands to run", I'm sure you have your own reasons). One of these tools Ned lists is pyparsing, as Gregg mentions, but there are more than thirty others so you may want to have a look before you pick one that's to your taste.</p>
<p>Once you have transformed your input source language into a syntax tree or other convenient in-memory representation, you can just walk the tree and execute as you go (inserting variable values, branching on conditionals and loops, etc). Besides the ability to run external processes (e.g. via subprocess, whether wrapped up as Gregg suggests, or not), don't forget that Python itself may be able to execute some of your elementary commands without breaking a sweat, and, when feasible, that will be significantly faster than delegating execution to a child process (indeed, one early motivation for Perl's success was that it could do a lot of things within one process, while sh was forking away like mad; modern descendants of sh like bash and ksh took the lesson, and now implement a lot of built-ins that can execute within the same process as the main script;-).</p>
<p>For example, that <code>delete</code> command in your example can be implemented "internally" via os.unlink (can't link to the Python online docs right now as python.org is currently down due to HW problems;-).</p>
| 1 | 2009-08-08T16:25:04Z | [
"python",
"shell",
"cross-platform",
"command"
] |
Portable command execution syntax implemented in Python | 1,249,165 | <p>Python is not a pretty good language in <em>defining</em> a set of commands to run. Bash is. But Bash does not run naively on Windows.</p>
<p>Background: I am trying to build a set of programs - with established dependency relationships between them - on mac/win/linux. Something like macports but should work on all the three platforms listed.</p>
<p>This begets the necessary to have a shell-like language that can be used to <em>define</em> the command sequence to run for building/patching/etc.. a particular program, for instance:</p>
<pre><code>post-destroot {
xinstall -d ${destroot}${prefix}/share/emacs/${version}/leim
delete ${destroot}${prefix}/bin/ctags
delete ${destroot}${prefix}/share/man/man1/ctags.1
if {[variant_isset carbon]} {
global version
delete ${destroot}${prefix}/bin/emacs ${destroot}${prefix}/bin/emacs-${version}
}
}
</code></pre>
<p>The above is from the <a href="http://svn.macports.org/repository/macports/trunk/dports/editors/emacs/Portfile" rel="nofollow">emacs Portfile in macports</a>. Note the use of variables, conditionals, functions .. besides specifying a simple list of commands to execute in that order.</p>
<p>Although the syntax is not Python, the actual execution semantics has to be deferred to Python using subprocess or whatever. In short, I should be able to 'run' such a script .. but for each command a specified hook function gets called that actually runs any command passed as argument. I hope you get the idea.</p>
| 1 | 2009-08-08T15:38:42Z | 1,252,426 | <p>Here's my trivial suggestion: parse it via regexp to Python so it becomes</p>
<pre><code>def post_destroot():
xinstall ('-d', '${destroot}${prefix}/share/emacs/${version}/leim')
delete ('${destroot}${prefix}/bin/ctags')
delete ('${destroot}${prefix}/share/man/man1/ctags.1')
if test('variant_isset', 'carbon'):
global('version')
delete('${destroot}${prefix}/bin/emacs', '${destroot}${prefix}/bin/emacs-${version}')
</code></pre>
<p>I think it's not hard to write <code>xinstall()</code>, <code>delete()</code> and <code>test()</code> functions, especially since Python already has built-in function to format strings <code>"{destroot}".format(dictionary).</code></p>
<p>But why bother? Try looking into <code>distutils</code> module from the standard library.</p>
| 0 | 2009-08-09T22:03:35Z | [
"python",
"shell",
"cross-platform",
"command"
] |
Python leaking memory while using PyQt and matplotlib | 1,249,182 | <p>I've created a small PyQt based utility in Python that creates PNG graphs using matplotlib when a user clicks a button. Everything works well during the first few clicks, however each time an image is created, the application's memory footprint grows about 120 MB, eventually crashing Python altogether.</p>
<p>How can I recover this memory after a graph is created? I've included a simplified version of my code here:</p>
<pre><code>import datetime as dt
from datetime import datetime
import os
import gc
# For Graphing
import matplotlib
from pylab import figure, show, savefig
from matplotlib import figure as matfigure
from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter, DayLocator
from matplotlib.ticker import MultipleLocator
import matplotlib.pyplot as plot
import matplotlib.ticker as ticker
# For GUI
import sys
from PyQt4 import QtGui, QtCore
class HyperGraph(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle('Title')
self.create_widgets()
def create_widgets(self):
grid = QtGui.QGridLayout()
self.generate_button = QtGui.QPushButton("Generate Graph", self)
grid.addWidget(self.generate_button, 1, 1)
QtCore.QObject.connect(self.generate_button, QtCore.SIGNAL("clicked()"), self.generate_graph)
def generate_graph(self):
try:
fig = figure()
ax = fig.add_axes([1,1,1,1])
# set title
ax.set_title('Title')
# configure x axis
plot.xlim(dt.date.today() - dt.timedelta(days=180), dt.date.today())
ax.set_xlabel('Date')
fig.set_figwidth(100)
# configure y axis
plot.ylim(0, 200)
ax.set_ylabel('Price')
fig.set_figheight(30)
# export the graph to a png file
plot.savefig('graph.png')
except:
print 'Error'
plot.close(fig)
gc.collect()
app = QtGui.QApplication(sys.argv)
hyper_graph = HyperGraph()
hyper_graph.show()
sys.exit(app.exec_())
</code></pre>
<p>The plot.savefig('graph.png') command seems to be what's gobbling up the memory.</p>
<p>I'd greatly appreciate any help!</p>
| 6 | 2009-08-08T15:49:14Z | 1,249,207 | <p>It seems that some backends are leaking memory. Try setting your backend explicitly, e.g.</p>
<pre><code>import matplotlib
matplotlib.use('Agg') # before import pylab
import pylab
</code></pre>
| 7 | 2009-08-08T15:57:59Z | [
"python",
"memory-leaks",
"pyqt",
"matplotlib"
] |
Python leaking memory while using PyQt and matplotlib | 1,249,182 | <p>I've created a small PyQt based utility in Python that creates PNG graphs using matplotlib when a user clicks a button. Everything works well during the first few clicks, however each time an image is created, the application's memory footprint grows about 120 MB, eventually crashing Python altogether.</p>
<p>How can I recover this memory after a graph is created? I've included a simplified version of my code here:</p>
<pre><code>import datetime as dt
from datetime import datetime
import os
import gc
# For Graphing
import matplotlib
from pylab import figure, show, savefig
from matplotlib import figure as matfigure
from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter, DayLocator
from matplotlib.ticker import MultipleLocator
import matplotlib.pyplot as plot
import matplotlib.ticker as ticker
# For GUI
import sys
from PyQt4 import QtGui, QtCore
class HyperGraph(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle('Title')
self.create_widgets()
def create_widgets(self):
grid = QtGui.QGridLayout()
self.generate_button = QtGui.QPushButton("Generate Graph", self)
grid.addWidget(self.generate_button, 1, 1)
QtCore.QObject.connect(self.generate_button, QtCore.SIGNAL("clicked()"), self.generate_graph)
def generate_graph(self):
try:
fig = figure()
ax = fig.add_axes([1,1,1,1])
# set title
ax.set_title('Title')
# configure x axis
plot.xlim(dt.date.today() - dt.timedelta(days=180), dt.date.today())
ax.set_xlabel('Date')
fig.set_figwidth(100)
# configure y axis
plot.ylim(0, 200)
ax.set_ylabel('Price')
fig.set_figheight(30)
# export the graph to a png file
plot.savefig('graph.png')
except:
print 'Error'
plot.close(fig)
gc.collect()
app = QtGui.QApplication(sys.argv)
hyper_graph = HyperGraph()
hyper_graph.show()
sys.exit(app.exec_())
</code></pre>
<p>The plot.savefig('graph.png') command seems to be what's gobbling up the memory.</p>
<p>I'd greatly appreciate any help!</p>
| 6 | 2009-08-08T15:49:14Z | 1,253,972 | <p>The pyplot interface is meant for easy interactive use, but for embedding in an application the object-oriented API is better. For example, pyplot keeps track of all figures you have created. Your <code>plot.close(figure)</code> <em>should</em> get rid of them, but maybe it doesn't get executed -- try putting it inside <code>finally</code> or reusing the same figure object.</p>
<p>See <a href="http://matplotlib.sourceforge.net/examples/user%5Finterfaces/embedding%5Fin%5Fqt4.html">this example</a> of embedding matplotlib in a PyQt4 application using the object-oriented API. It's more work, but since everything is explicit, you shouldn't get memory leaks from the behind-the-scenes automation that pyplot does.</p>
| 6 | 2009-08-10T09:44:18Z | [
"python",
"memory-leaks",
"pyqt",
"matplotlib"
] |
Removing all non-numeric characters from string in Python | 1,249,388 | <p>How do we remove all non-numeric characters from a string in Python?</p>
| 63 | 2009-08-08T17:13:01Z | 1,249,398 | <p>Not sure if this is the most efficient way, but:</p>
<pre><code>>>> ''.join(c for c in "abc123def456" if c.isdigit())
'123456'
</code></pre>
<p>The <code>''.join</code> part means to combine all the resulting characters together without any characters in between. Then the rest of it is a list comprehension, where (as you can probably guess) we only take the parts of the string that match the condition <code>isdigit</code>.</p>
| 48 | 2009-08-08T17:16:55Z | [
"python",
"numbers"
] |
Removing all non-numeric characters from string in Python | 1,249,388 | <p>How do we remove all non-numeric characters from a string in Python?</p>
| 63 | 2009-08-08T17:13:01Z | 1,249,424 | <pre><code>>>> import re
>>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd")
'987978098098098'
</code></pre>
| 118 | 2009-08-08T17:25:21Z | [
"python",
"numbers"
] |
Removing all non-numeric characters from string in Python | 1,249,388 | <p>How do we remove all non-numeric characters from a string in Python?</p>
| 63 | 2009-08-08T17:13:01Z | 1,249,449 | <p>Fastest approach, if you need to perform more than just one or two such removal operations (or even just one, but on a very long string!-), is to rely on the <code>translate</code> method of strings, even though it does need some prep:</p>
<pre><code>>>> import string
>>> allchars = ''.join(chr(i) for i in xrange(256))
>>> identity = string.maketrans('', '')
>>> nondigits = allchars.translate(identity, string.digits)
>>> s = 'abc123def456'
>>> s.translate(identity, nondigits)
'123456'
</code></pre>
<p>The <code>translate</code> method is different, and maybe a tad simpler simpler to use, on Unicode strings than it is on byte strings, btw:</p>
<pre><code>>>> unondig = dict.fromkeys(xrange(65536))
>>> for x in string.digits: del unondig[ord(x)]
...
>>> s = u'abc123def456'
>>> s.translate(unondig)
u'123456'
</code></pre>
<p>You might want to use a mapping class rather than an actual dict, especially if your Unicode string may potentially contain characters with very high ord values (that would make the dict excessively large;-). For example:</p>
<pre><code>>>> class keeponly(object):
... def __init__(self, keep):
... self.keep = set(ord(c) for c in keep)
... def __getitem__(self, key):
... if key in self.keep:
... return key
... return None
...
>>> s.translate(keeponly(string.digits))
u'123456'
>>>
</code></pre>
| 3 | 2009-08-08T17:35:59Z | [
"python",
"numbers"
] |
Removing all non-numeric characters from string in Python | 1,249,388 | <p>How do we remove all non-numeric characters from a string in Python?</p>
| 63 | 2009-08-08T17:13:01Z | 1,387,394 | <p>This should work for strings and unicode objects:</p>
<pre><code># python <3.0
def only_numerics(seq):
return filter(type(seq).isdigit, seq)
# python â¥3.0
def only_numerics(seq):
seq_type= type(seq)
return seq_type().join(filter(seq_type.isdigit, seq))
</code></pre>
| 10 | 2009-09-07T03:01:27Z | [
"python",
"numbers"
] |
Removing all non-numeric characters from string in Python | 1,249,388 | <p>How do we remove all non-numeric characters from a string in Python?</p>
| 63 | 2009-08-08T17:13:01Z | 12,316,431 | <p>Just to add another option to the mix, there are several useful constants within the <code>string</code> module. While more useful in other cases, they can be used here.</p>
<pre><code>>>> from string import digits
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'
</code></pre>
<p>There are several constants in the module, including:</p>
<ul>
<li><code>ascii_letters</code> (abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)</li>
<li><code>hexdigits</code> (0123456789abcdefABCDEF)</li>
</ul>
<p>If you are using these constants heavily, it can be worthwhile to covert them to a <code>frozenset</code>. That enables O(1) lookups, rather than O(n), where n is the length of the constant for the original strings.</p>
<pre><code>>>> digits = frozenset(digits)
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'
</code></pre>
| 2 | 2012-09-07T10:37:03Z | [
"python",
"numbers"
] |
Is the default configuration of re incorrect on macbooks? Or have I simply misunderstood something? | 1,249,390 | <p>Python came pre-installed on my macbook and I have been slowly getting acquainted with the langauge. However, it seems that my configuration of the re library is incorrect, or I simply misunderstand something and things are amiss. Whenever I run a python script with "import re", I recieve the following error:</p>
<pre><code>Traceback (most recent call last):
File "regex.py", line 2, in <module>
import re
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 4, in <module>
# re-compatible interface for the sre matching engine
AttributeError: 'module' object has no attribute 'compile'
</code></pre>
<p>What gives!</p>
| 0 | 2009-08-08T17:13:47Z | 1,249,419 | <p>Pretty mysterious problem, given that line 4 in that file (and many other lines around that line number) is a comment (indeed the error msg itself shows that comment line!-) so even with the worst misconfiguration I'd be hard put to reproduce the problem as given.</p>
<p>Let's try to simplify things and check how they may (or may not) break. Please open a Terminal, mkdir a new empty directory somewhere and cd into it (so we know there's no filename conflict wrt modules etc), at the bash prompt <code>unset PYTHONPATH</code> (so we know for sure that isn't interfering), <code>unset PYTHONSTARTUP</code> (ditto); then type the command:</p>
<pre><code>$ python -c'import re; print re.__file__'
</code></pre>
<p>It should emit the line:</p>
<pre><code>/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.pyc
</code></pre>
<p>does it? If so, then we can keep rooting around to understand what name clash (or whatever) caused your original problem. If the problem persists under such "clean" conditions then your system is jinxed and I would reinstal Mac OS X Leopard if I were in your shoes!</p>
| 3 | 2009-08-08T17:24:18Z | [
"python",
"regex"
] |
`cat filename | grep -B 5 -C 5 foo` | 1,249,412 | <pre><code>for filename in os.listdir("."):
for line in open(filename).xreadlines():
if "foo" in line:
print line
</code></pre>
<p>So this is a simple python equivalent of <code>cat filename | grep foo</code>. However, I would like the equivalent of <code>cat filename | grep -B 5 -C 5 foo</code>, how should the above code be modified?</p>
| 2 | 2009-08-08T17:22:35Z | 1,249,428 | <p>Simplest way is:</p>
<pre><code>for filename in os.listdir("."):
lines = open(filename).readlines()
for i, line in enumerate(lines):
if "foo" in line:
for x in lines[i-5 : i+6]:
print x,
</code></pre>
<p>add line numbers, breaks between blocks, etc, to taste;-).</p>
<p>In the extremely unlikely case that you have to deal with absolutely humungous text files (ones over 200-300 times larger than the King James Bible, for example, which is about 4.3 MB in its entirety as a text file), I recommend a generator producing a sliding window (a "FIFO" of lines). Focusing for simplicity only on searching lines excluding the first and last few ones of the file (which requires a couple of special-case loops in addition -- that's why I'm returning the index as well... because it's not always 5 in those two extra loops!-):</p>
<pre><code>import collections
def sliding_windows(it):
fifo = collections.deque()
# prime the FIFO with the first 10
for i, line in enumerate(it):
fifo.append(line)
if i == 9: break
# keep yielding 11-line sliding-windows
for line in it:
fifo.append(line)
yield fifo, 5
fifo.popleft()
for w, i in sliding_windows(open(filename)):
if "foo" in w[i]:
for line in w: print line,
</code></pre>
<p>I think I'll leave the special-case loops (and worries about files of very few lines;-) as exercises, since the whole thing is so incredibly hypothetical anyway.</p>
<p>Just a few hints...: the closing "special-case loop" is really simple -- just repeatedly drop the first line, without appending, obviously, as there's nothing more to append... the index should still be always 5, and you're done when you've just yielded a window where 5 is the last index (i.e., the last line of the file); the starting case is a tad subtler as you don't want to yield until you've read the first 6 lines, and at that point the index will be 0 (first line of the file)...</p>
<p>Finally, for extra credit, consider how to make this work on very short files, too!-)</p>
| 7 | 2009-08-08T17:27:04Z | [
"python",
"grep"
] |
`cat filename | grep -B 5 -C 5 foo` | 1,249,412 | <pre><code>for filename in os.listdir("."):
for line in open(filename).xreadlines():
if "foo" in line:
print line
</code></pre>
<p>So this is a simple python equivalent of <code>cat filename | grep foo</code>. However, I would like the equivalent of <code>cat filename | grep -B 5 -C 5 foo</code>, how should the above code be modified?</p>
| 2 | 2009-08-08T17:22:35Z | 1,249,705 | <p>Although I like the simplicity of Alex's answer, it would require lots of memory when grepping large files. How about this algorithm?</p>
<pre><code>import os
for filename in (f for f in os.listdir(".") if os.path.isfile(f)):
prevLines = []
followCount = 0
for line in open(filename):
prevLines.append(line)
if "foo" in line:
if followCount <= 0:
for prevLine in prevLines:
print prevLine.strip()
else:
print line.strip()
followCount = 5
elif followCount > 0:
print line.strip()
followCount -= 1
if len(prevLines) > 5:
prevLines.pop(0)
</code></pre>
| 1 | 2009-08-08T19:29:37Z | [
"python",
"grep"
] |
Simple python/Regex problem: Removing all new lines from a file | 1,249,670 | <p>I'm becoming acquainted with python and am creating problems in order to help myself learn the ins and outs of the language. My next problem comes as follows:</p>
<p>I have copied and pasted a huge slew of text from the internet, but the copy and paste added several new lines to break up the huge string. I wish to programatically remove all of these and return the string into a giant blob of characters. This is obviously a job for regex (I think), and parsing through the file and removing all instances of the newline character sounds like it would work, but it doesn't seem to be going over all that well for me. </p>
<p>Is there an easy way to go about this? It seems rather simple.</p>
| 14 | 2009-08-08T19:15:59Z | 1,249,685 | <pre><code>import re
re.sub("\n", "", file-contents-here)
</code></pre>
| 3 | 2009-08-08T19:21:59Z | [
"python",
"regex"
] |
Simple python/Regex problem: Removing all new lines from a file | 1,249,670 | <p>I'm becoming acquainted with python and am creating problems in order to help myself learn the ins and outs of the language. My next problem comes as follows:</p>
<p>I have copied and pasted a huge slew of text from the internet, but the copy and paste added several new lines to break up the huge string. I wish to programatically remove all of these and return the string into a giant blob of characters. This is obviously a job for regex (I think), and parsing through the file and removing all instances of the newline character sounds like it would work, but it doesn't seem to be going over all that well for me. </p>
<p>Is there an easy way to go about this? It seems rather simple.</p>
| 14 | 2009-08-08T19:15:59Z | 1,249,710 | <p>I wouldn't use a regex for simply replacing newlines - I'd use <code>string.replace()</code>. Here's a complete script:</p>
<pre><code>f = open('input.txt')
contents = f.read()
f.close()
new_contents = contents.replace('\n', '')
f = open('output.txt', 'w')
f.write(new_contents)
f.close()
</code></pre>
| 5 | 2009-08-08T19:33:14Z | [
"python",
"regex"
] |
Simple python/Regex problem: Removing all new lines from a file | 1,249,670 | <p>I'm becoming acquainted with python and am creating problems in order to help myself learn the ins and outs of the language. My next problem comes as follows:</p>
<p>I have copied and pasted a huge slew of text from the internet, but the copy and paste added several new lines to break up the huge string. I wish to programatically remove all of these and return the string into a giant blob of characters. This is obviously a job for regex (I think), and parsing through the file and removing all instances of the newline character sounds like it would work, but it doesn't seem to be going over all that well for me. </p>
<p>Is there an easy way to go about this? It seems rather simple.</p>
| 14 | 2009-08-08T19:15:59Z | 1,249,740 | <p>The two main alternatives: read everything in as a single string and remove newlines:</p>
<pre><code>clean = open('thefile.txt').read().replace('\n', '')
</code></pre>
<p>or, read line by line, removing the newline that ends each line, and join it up again:</p>
<pre><code>clean = ''.join(l[:-1] for l in open('thefile.txt'))
</code></pre>
<p>The former alternative is probably faster, but, as always, I strongly recommend you MEASURE speed (e.g., use <code>python -mtimeit</code>) in cases of your specific interest, rather than just assuming you know how performance will be. REs are probably slower, but, again: don't guess, MEASURE!</p>
<p>So here are some numbers for a specific text file on my laptop:</p>
<pre><code>$ python -mtimeit -s"import re" "re.sub('\n','',open('AV1611Bible.txt').read())"
10 loops, best of 3: 53.9 msec per loop
$ python -mtimeit "''.join(l[:-1] for l in open('AV1611Bible.txt'))"
10 loops, best of 3: 51.3 msec per loop
$ python -mtimeit "open('AV1611Bible.txt').read().replace('\n', '')"
10 loops, best of 3: 35.1 msec per loop
</code></pre>
<p>The file is a version of the KJ Bible, downloaded and unzipped from <a href="http://printkjv.ifbweb.com/AV%5Ftxt.zip">here</a> (I do think it's important to run such measurements on one easily fetched file, so others can easily reproduce them!).</p>
<p>Of course, a few milliseconds more or less on a file of 4.3 MB, 34,000 lines, may not matter much to you one way or another; but as the fastest approach is also the simplest one (far from an unusual occurrence, especially in Python;-), I think that's a pretty good recommendation.</p>
| 23 | 2009-08-08T19:54:28Z | [
"python",
"regex"
] |
Simple python/Regex problem: Removing all new lines from a file | 1,249,670 | <p>I'm becoming acquainted with python and am creating problems in order to help myself learn the ins and outs of the language. My next problem comes as follows:</p>
<p>I have copied and pasted a huge slew of text from the internet, but the copy and paste added several new lines to break up the huge string. I wish to programatically remove all of these and return the string into a giant blob of characters. This is obviously a job for regex (I think), and parsing through the file and removing all instances of the newline character sounds like it would work, but it doesn't seem to be going over all that well for me. </p>
<p>Is there an easy way to go about this? It seems rather simple.</p>
| 14 | 2009-08-08T19:15:59Z | 1,249,744 | <p>I know this is a python learning problem, but if you're ever trying to do this from the command-line, there's no need to write a python script. Here are a couple of other ways:</p>
<pre><code>cat $FILE | tr -d '\n'
awk '{printf("%s", $0)}' $FILE
</code></pre>
<p>Neither of these has to read the entire file into memory, so if you've got an enormous file to process, they might be better than the python solutions provided.</p>
| 2 | 2009-08-08T19:58:10Z | [
"python",
"regex"
] |
Simple python/Regex problem: Removing all new lines from a file | 1,249,670 | <p>I'm becoming acquainted with python and am creating problems in order to help myself learn the ins and outs of the language. My next problem comes as follows:</p>
<p>I have copied and pasted a huge slew of text from the internet, but the copy and paste added several new lines to break up the huge string. I wish to programatically remove all of these and return the string into a giant blob of characters. This is obviously a job for regex (I think), and parsing through the file and removing all instances of the newline character sounds like it would work, but it doesn't seem to be going over all that well for me. </p>
<p>Is there an easy way to go about this? It seems rather simple.</p>
| 14 | 2009-08-08T19:15:59Z | 9,051,969 | <p>Old question, but since it was in my search results for a similar query, and no one has mentioned the python string functions <code>strip() || lstrip() || rstrip()</code>, I'll just add that for posterity (and anyone who prefers not to use re when not necessary):</p>
<pre><code>old = open('infile.txt')
new = open('outfile.txt', 'w')
stripped = [line.strip() for line in old]
old.close()
new.write("".join(stripped))
new.close()
</code></pre>
| 0 | 2012-01-29T08:41:57Z | [
"python",
"regex"
] |
Is there a string-collapse library function in python? | 1,249,786 | <p>Is there a cross-platform library function that would collapse a multiline string into a single-line string with no repeating spaces?</p>
<p>I've come up with some snip below, but I wonder if there is a standard function which I could just import which is perhaps even optimized in C?</p>
<pre><code>def collapse(input):
import re
rn = re.compile(r'(\r\n)+')
r = re.compile(r'\r+')
n = re.compile(r'\n+')
s = re.compile(r'\ +')
return s.sub(' ',n.sub(' ',r.sub(' ',rn.sub(' ',input))))
</code></pre>
<p>P.S. Thanks for good observations. <code>' '.join(input.split())</code> seems to be the winner as it actually runs faster about twice in my case compared to search-replace with a precompiled <code>r'\s+'</code> regex.</p>
| 4 | 2009-08-08T20:18:54Z | 1,249,792 | <pre><code>multi_line.replace('\n', '')
</code></pre>
<p>will do the job. <code>'\n'</code> is a universal end of line character in python.</p>
| 0 | 2009-08-08T20:20:54Z | [
"python",
"string",
"line-breaks"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.