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 list |
|---|---|---|---|---|---|---|---|---|---|
I need a beginners guide to setting up windows for python development | 959,479 | <p>I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.</p>
<p>One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.</p>
<p>If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.</p>
<p>My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used. </p>
| 9 | 2009-06-06T11:08:51Z | 960,062 | <p>If you've worked with Eclipse before you could give <a href="http://pydev.sourceforge.net/" rel="nofollow">Pydev</a> a try</p>
| 0 | 2009-06-06T16:26:38Z | [
"python",
"windows",
"development-environment"
] |
I need a beginners guide to setting up windows for python development | 959,479 | <p>I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.</p>
<p>One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.</p>
<p>If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.</p>
<p>My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used. </p>
| 9 | 2009-06-06T11:08:51Z | 986,203 | <p>NOTE: I included a lot of links to frameworks, projects and what-not, but as a new user I was limited to 1 link per answer. If someone else with enough reputation to edit wants/can edit them into this answer instead of the footnotes, I'd be grateful.</p>
<p>There are some Python IDE's such as Wing IDE[1], I believe some people use Eclipse[2] with a python plugin[3] as well. A lot of people in the #python channel of FreeNode seem to prefer vim, emacs, nano and similar text editors in favor of IDE's. My personal preffered editor is Vim, but if you've mostly done .NET development on windows, presumably with the usual Visual X IDE's, vim and emacs will probably cause you culture shock and you'd be better of using an IDE.</p>
<p>Nearly all python web frameworks* support the WSGI standard[4], most of the large web servers have some sort of plugin to support WSGI, the others support WSGI via fast cgi or plain cgi.</p>
<p>The Zope[5] and Django[6] frameworks have their own ORM's, of other ORM's the two most well known appear to be SQL Alchemy[7] and SQL Object[8]. I only have experience with the former, but both support all possible sane database choices, including SQLite which is installed together with Python and hence perfectly suited to testing and experimenting without polluting your .NET environment with 3rd part web servers and database servers.</p>
<p>The builtin unittest[9] and pyunit[10] frameworks seem to be the preffered solutions for unit testing, but I don't have much experience with these.</p>
<p>bpython[11] and ipython[12] offer enhanced interactive python shells which can greatly help speed up and testing small bits of code and hence worth looking in to.</p>
<p>As for a list of well known and often used web frameworks, look into the following frameworks**:</p>
<ul>
<li>Twisted[13] is a generic networking framework, which supports almost every single protocol under the sun.</li>
<li>Pylons[14] is light-weight framework aimed at being as flexible as possible and leaving all the choices about what ORM, templating language and what-not to you.</li>
<li>CherryPy[15] tries to provide an interface to expose Python objects to the web. </li>
<li>Django[6] attempts to be an all-in-one solution, builtin template system, ORM, admin pages and internationalization. While the previous frameworks have more DIY wiring together various frameworks work involved with them.</li>
<li>Zope[5] is aimed to be suitable for large enterprise applications, I've heard nothing but good things about it, but consensus seems to be that for smaller you're probably better off with one of the simpler and smaller frameworks.</li>
<li>TurboGears[16] is the framework I know the least about, but it seems to be mostly competition for Django.</li>
</ul>
<p>This is everything I can think of right now, I'll edit and add stuff if I can think of it. I hope this helps you some in the wonderful world of python.</p>
<p><hr /></p>
<p>* - The main exception would be Apache's mod_python, which you should avoid for exactly that reason, use mod_wsgi instead.<br />
** - Word of warning, I have not personally used these frameworks this is just a very short impression I have gotten from talking to other people about each framework, it may be wildly inaccurate. (If anyone has any corrections, do comment and I'll try to edit and fix this answer).</p>
<p>(The http:// is missing since they're recognized as links otherwise)<br />
[1] www.wingware.com/<br />
[2] www.eclipse.org/<br />
[3] pydev.sourceforge.net/<br />
[4] wsgi.org/wsgi/<br />
[5] www.zope.org/<br />
[6] www.djangoproject.com/<br />
[7] www.sqlalchemy.org/<br />
[8] www.sqlobject.org/<br />
[9] docs.python.org/library/unittest.html<br />
[10] pyunit.sourceforge.net/pyunit.html<br />
[11] www.bpython-interpreter.org/<br />
[12] ipython.scipy.org/<br />
[13] twistedmatrix.com/trac/<br />
[14] pylonshq.com/<br />
[15] www.cherrypy.org/<br />
[16] turbogears.org/<br /></p>
| 1 | 2009-06-12T11:37:53Z | [
"python",
"windows",
"development-environment"
] |
What is the fastest way to draw an image in Gtk+? | 959,675 | <p>I have an image/pixbuf that I want to draw into a gtk.DrawingArea and refresh frequently, so the blitting operation has to be fast. Doing it the easy way:</p>
<pre><code>def __init__(self):
self.drawing_area = gtk.DrawingArea()
self.image = gtk.gdk.pixbuf_new_from_file("image.png")
def area_expose_cb(self, area, event):
self.drawing_area.window.draw_pixbuf(self.gc, self.image, 0, 0, x, y)
</code></pre>
<p>However leads to very slow performance, likely caused by the pixbuf not being in the displays color format. </p>
<p>I had no success with Cairo either, as it seems limited to 24/32bit formats and doesn't have a 16bit format (FORMAT_RGB16_565 is unsupported and deprecated).</p>
<p>What alternatives are there to drawing pictures quickly in Gtk+?</p>
| 8 | 2009-06-06T13:28:59Z | 960,498 | <p>Are you really not generating enough raw speed/throughput? Or is it just that you're seeing flickering?</p>
<p>If it's the latter, perhaps you should investigate double buffering for perfomring your updates instead? Basically the idea is to draw to an invisible buffer then tell the graphics card to use the new buffer.</p>
<p>Maybe check out this page which has some <a href="http://xfc.xfce.org/docs/howto/html/drawingarea.html" rel="nofollow">information on double buffering</a>.</p>
| 2 | 2009-06-06T20:46:53Z | [
"python",
"gtk",
"pygtk",
"cairo"
] |
What is the fastest way to draw an image in Gtk+? | 959,675 | <p>I have an image/pixbuf that I want to draw into a gtk.DrawingArea and refresh frequently, so the blitting operation has to be fast. Doing it the easy way:</p>
<pre><code>def __init__(self):
self.drawing_area = gtk.DrawingArea()
self.image = gtk.gdk.pixbuf_new_from_file("image.png")
def area_expose_cb(self, area, event):
self.drawing_area.window.draw_pixbuf(self.gc, self.image, 0, 0, x, y)
</code></pre>
<p>However leads to very slow performance, likely caused by the pixbuf not being in the displays color format. </p>
<p>I had no success with Cairo either, as it seems limited to 24/32bit formats and doesn't have a 16bit format (FORMAT_RGB16_565 is unsupported and deprecated).</p>
<p>What alternatives are there to drawing pictures quickly in Gtk+?</p>
| 8 | 2009-06-06T13:28:59Z | 961,332 | <p>Try creating Pixmap that uses the same colormap as your drawing area.</p>
<pre><code>dr_area.realize()
self.gc = dr_area.get_style().fg_gc[gtk.STATE_NORMAL]
img = gtk.gdk.pixbuf_new_from_file("image.png")
self.image = gtk.gdk.Pixmap(dr_area.window, img.get_width(), img.get_height())
self.image.draw_pixbuf(self.gc, img, 0, 0, 0, 0)
</code></pre>
<p>and drawing it to the screen using</p>
<pre><code>dr_area.window.draw_drawable(self.gc, self.image, 0, 0, x, y, *self.image.get_size())
</code></pre>
| 6 | 2009-06-07T06:29:24Z | [
"python",
"gtk",
"pygtk",
"cairo"
] |
What is the fastest way to draw an image in Gtk+? | 959,675 | <p>I have an image/pixbuf that I want to draw into a gtk.DrawingArea and refresh frequently, so the blitting operation has to be fast. Doing it the easy way:</p>
<pre><code>def __init__(self):
self.drawing_area = gtk.DrawingArea()
self.image = gtk.gdk.pixbuf_new_from_file("image.png")
def area_expose_cb(self, area, event):
self.drawing_area.window.draw_pixbuf(self.gc, self.image, 0, 0, x, y)
</code></pre>
<p>However leads to very slow performance, likely caused by the pixbuf not being in the displays color format. </p>
<p>I had no success with Cairo either, as it seems limited to 24/32bit formats and doesn't have a 16bit format (FORMAT_RGB16_565 is unsupported and deprecated).</p>
<p>What alternatives are there to drawing pictures quickly in Gtk+?</p>
| 8 | 2009-06-06T13:28:59Z | 1,287,134 | <p>It may be worth doing some benchmarking - if you draw with a small area is it still slow?</p>
<p>If it is, it may be worth asking on pygtk or gtk mailing lists...</p>
| 0 | 2009-08-17T10:03:00Z | [
"python",
"gtk",
"pygtk",
"cairo"
] |
Any graphics library for unix that can draw histograms? | 959,702 | <p>A python program needs to draw histograms. It's ok to use 3rd party library (free). What is the best way to do that?</p>
| 1 | 2009-06-06T13:43:46Z | 959,706 | <p>You can use <a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.hist" rel="nofollow">matplotlib</a>.</p>
| 9 | 2009-06-06T13:46:26Z | [
"python",
"unix",
"graphics"
] |
Any graphics library for unix that can draw histograms? | 959,702 | <p>A python program needs to draw histograms. It's ok to use 3rd party library (free). What is the best way to do that?</p>
| 1 | 2009-06-06T13:43:46Z | 959,714 | <p><a href="http://gnuplot-py.sourceforge.net/" rel="nofollow">Gnuplot.py</a> lets you use <a href="http://www.gnuplot.info/" rel="nofollow">Gnuplot</a> from python. </p>
| 3 | 2009-06-06T13:52:49Z | [
"python",
"unix",
"graphics"
] |
Any graphics library for unix that can draw histograms? | 959,702 | <p>A python program needs to draw histograms. It's ok to use 3rd party library (free). What is the best way to do that?</p>
| 1 | 2009-06-06T13:43:46Z | 960,258 | <p>How much power do you need? How much external weight are you willing to take on? <a href="http://root.cern.ch/" rel="nofollow">ROOT</a> is accessible in python <a href="http://root.cern.ch/drupal/content/how-use-use-python-pyroot-interpreter" rel="nofollow">using PyROOT</a>. Heavy and a lot to learn to get the most out of it, but very powerful.</p>
| 1 | 2009-06-06T18:30:56Z | [
"python",
"unix",
"graphics"
] |
chunk_split in python | 959,780 | <p>I'm trying to find a pythonic way to do this PHP code:</p>
<pre><code>chunk_split(base64_encode($picture));
</code></pre>
<p><a href="http://us2.php.net/chunk%5Fsplit" rel="nofollow">http://us2.php.net/chunk_split</a></p>
<p>chunk_split split the string into smaller chunks of 76 character long by adding a "\r\n" (RFC 2045). </p>
<p>thank you</p>
| 0 | 2009-06-06T14:18:42Z | 959,803 | <pre><code>chunk_split = lambda s: '\r\n'.join(s[i:min(i+76, len(s))] for i in xrange(0, len(s), 76))
</code></pre>
| 1 | 2009-06-06T14:31:05Z | [
"php",
"python"
] |
chunk_split in python | 959,780 | <p>I'm trying to find a pythonic way to do this PHP code:</p>
<pre><code>chunk_split(base64_encode($picture));
</code></pre>
<p><a href="http://us2.php.net/chunk%5Fsplit" rel="nofollow">http://us2.php.net/chunk_split</a></p>
<p>chunk_split split the string into smaller chunks of 76 character long by adding a "\r\n" (RFC 2045). </p>
<p>thank you</p>
| 0 | 2009-06-06T14:18:42Z | 959,809 | <p>This should do it:</p>
<pre><code>str.encode("base64").replace("\n", "\r\n")
</code></pre>
| 2 | 2009-06-06T14:34:51Z | [
"php",
"python"
] |
How to ensure xml.dom.minidom can parse its own output? | 959,782 | <p>I'm trying to serialize some data to xml in a way that can be read back. I'm doing this by manually building a DOM via xml.dom.minidom, and writing it to a file using the included writexml method.</p>
<p>Of particular interest is how I build the text nodes. I do this by initializing a Text object and then setting its data attribute. I'm not sure why the Text object doesn't take its content in the constructor, but that's just the way it in simplemented in xml.dom.minidom.</p>
<p>To give a concrete example, the code looks something like this:</p>
<pre><code>import xml.dom.minidom as dom
e = dom.Element('node')
t = dom.Text()
t.data = "The text content"
e.appendChild(t)
dom.parseString(e.toxml())
</code></pre>
<p>This seemed reasonable to me, particularly since createTextNode itself is implemented exactly like this:</p>
<pre><code>def createTextNode(self, data):
if not isinstance(data, StringTypes):
raise TypeError, "node contents must be a string"
t = Text()
t.data = data
t.ownerDocument = self
return t
</code></pre>
<p>The problem is that setting the data like this allows us to write text that later cannot be parsed back. To give an example, I am having difficulty with the following character:</p>
<pre><code>you´ll
</code></pre>
<p>The quote is ord(180), '\xb4'. My question is, what is the correct procedure to encode this data into an xml document suck that I parse the document with minidom to restore the original tree?</p>
| 0 | 2009-06-06T14:19:19Z | 959,799 | <p>The issue you're encountering, as explained in Python's <a href="http://docs.python.org/library/xml.dom.minidom.html" rel="nofollow">online docs</a>, is that of Unicode encoding:</p>
<pre><code>Node.toxml([encoding])
Return the XML that the DOM represents as a string.
With no argument, the XML header does not specify an encoding, and the result is
Unicode string if the default encoding cannot represent all characters in the
document. Encoding this string in an encoding other than UTF-8 is likely
incorrect, since UTF-8 is the default encoding of XML.
With an explicit encoding [1] argument, the result is a byte string in the
specified encoding. It is recommended that this argument is always specified.
To avoid UnicodeError exceptions in case of unrepresentable text data, the
encoding argument should be specified as âutf-8â.
</code></pre>
<p>So, call <code>.toxml('utf8')</code>, not just <code>.toxml()</code>, and use unicode strings as text contents, and you should be fine for a "round-trip" as you desire. For example:</p>
<pre><code>>>> t.data = u"The text\u0180content"
>>> dom.parseString(e.toxml('utf8')).toxml('utf8')
'<?xml version="1.0" encoding="utf8"?><node>The text\xc6\x80content</node>'
>>>
</code></pre>
| 3 | 2009-06-06T14:29:45Z | [
"python",
"xml",
"dom",
"escaping"
] |
Django EmailMultiAlternatives and HTML e-mail display in Outlook 2003 on Win2003 | 959,985 | <p>I'm using django.core.mail.EmailMultiAlternatives when sending e-mails from my django app in an attempt to make sure that the message downgrades to text if the e-mail client doesn't support HTML.</p>
<p>Here is my send_email method:</p>
<pre><code>def send_email(self, from_address, to_list, subject, msg_text, msg_html):
subject=subject.replace('\r','').replace('\n',' ')
self.msg = EmailMultiAlternatives(subject, msg_text, from_address, to_list)
self.msg.attach_alternative(msg_html, "text/html")
self.msg.content_subtype = "html"
self.msg.send()
</code></pre>
<p>It works great with Gmail, Hotmail and many other e-mail clients - displaying the HTML content without a problem. But it will not display the HTML content in Outlook 2003 running on Win2003 - just the text version.</p>
<p>If I forcefully put the HTML in the EmailMultiAlternatives call, i.e. use msg<code>_html instead of msg</code>_text like so:</p>
<pre><code>self.msg = EmailMultiAlternatives(subject, msg_html, from_address, to_list)
</code></pre>
<p>then it works correctly in all clients; but that means that there is no text fallback for clients that don't support HTML or (more likely) that have disabled support for it.</p>
<p>I think it is worth mentioning that the e-mail is being generated on a django app running on Mac OS X (just in case it has to do with line terminator differences between the OSes).</p>
<p>I see that <a href="http://stackoverflow.com/questions/322298/how-to-send-html-email-to-outlook-from-java">people using other languages</a> have had similar problems with outlook...</p>
<p>I wonder if anyone has any idea of WHY outlook would behave differently and if there is simple fix that can be applied in my code?</p>
| 2 | 2009-06-06T15:48:27Z | 963,481 | <p>I don't have an Outlook installation available to test this, so I'm wondering about the reason for the fifth line in your function.</p>
<pre><code>self.msg.content_subtype = "html"</code></pre>
<p>I don't know much about multipart email internals, but on my system that line causes both parts of the message have a content-type of text/html. Leaving it out produces a message with "Content-Type: text/plain" on the first part and "Content-Type: text/html" on the second.</p>
<p>In any case, one of the answers to the question about Java mentions changing the character set to iso-8859-1. I think you should be able to do that with django.core.mail.</p>
<p>The EmailMessage class (from which EmailMultiAlternatives inherits) has an attribute named "encoding" which sets the charset to use. By default it's None so the default charset of utf-8 (unless overridden in settings) is used instead.</p>
<p>In other words, add something like the following before the send line in the function listed in the question:</p>
<pre><code>self.msg.content_subtype = "iso-8859-1"</code></pre>
<p>Unfortunately, that will only change the encoding specified on the first part (msg_text in the function above). The function that attaches the alternative content doesn't seem to use the encoding attribute. I'm not sure it's the correct approach but I subclassed EmailMultiAlternatives to override the relevant function and it seemed to work okay.</p>
<pre><code>class EmailMultiAlternativesWithEncoding(EmailMultiAlternatives):
def _create_attachment(self, filename, content, mimetype=None):
"""
Converts the filename, content, mimetype triple into a MIME attachment
object. Use self.encoding when handling text attachments.
"""
if mimetype is None:
mimetype, _ = mimetypes.guess_type(filename)
if mimetype is None:
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
basetype, subtype = mimetype.split('/', 1)
if basetype == 'text':
encoding = self.encoding or settings.DEFAULT_CHARSET
attachment = SafeMIMEText(smart_str(content,
settings.DEFAULT_CHARSET), subtype, encoding)
# original text being replaced above (not last argument)
# attachment = SafeMIMEText(smart_str(content,
# settings.DEFAULT_CHARSET), subtype, settings.DEFAULT_CHARSET)
else:
# Encode non-text attachments with base64.
attachment = MIMEBase(basetype, subtype)
attachment.set_payload(content)
Encoders.encode_base64(attachment)
if filename:
attachment.add_header('Content-Disposition', 'attachment',
filename=filename)
return attachment</code></pre>
<p>I'm not sure if the "smart_str(content, settings.DEFAULT_CHARSET)" part should also reference "encoding" rather than "settings.DEFAULT_CHARSET" but that's the message body handling text is written (django.core.mail.EmailMessage.message).</p>
<p>As I said, I don't have Outlook so I can't actually test the Outlook aspect but it does seem to change the charset to iso-8859-1 for both parts.</p>
| 5 | 2009-06-08T05:02:20Z | [
"python",
"html",
"django",
"email"
] |
where can I find GladeGen? | 960,049 | <p>I'd like to design a GUI using Glade, and generate python code from it. The thing is, I can't find GladeGen. Does anyone know where it can be downloaded from?</p>
| 3 | 2009-06-06T16:18:05Z | 960,057 | <p>Why not use the GUI designer is something like Anjuta or the Glade program, write that out to <strong>glade XML</strong> and use the python bindings for libglade to use the XML file ... Kind of like XAML.</p>
<p><strong>Edit, added some links to Glade.xml->python</strong></p>
<p><a href="http://glc.sourceforge.net/" rel="nofollow">http://glc.sourceforge.net/</a><br />
<a href="http://www.pygtk.org/" rel="nofollow">http://www.pygtk.org/</a> (might help)</p>
| 2 | 2009-06-06T16:23:17Z | [
"python",
"gtk",
"glade"
] |
where can I find GladeGen? | 960,049 | <p>I'd like to design a GUI using Glade, and generate python code from it. The thing is, I can't find GladeGen. Does anyone know where it can be downloaded from?</p>
| 3 | 2009-06-06T16:18:05Z | 960,245 | <p>Google is your friend.</p>
<p><a href="http://www.linuxjournal.com/article/7558" rel="nofollow">http://www.linuxjournal.com/article/7558</a></p>
| 2 | 2009-06-06T18:23:09Z | [
"python",
"gtk",
"glade"
] |
where can I find GladeGen? | 960,049 | <p>I'd like to design a GUI using Glade, and generate python code from it. The thing is, I can't find GladeGen. Does anyone know where it can be downloaded from?</p>
| 3 | 2009-06-06T16:18:05Z | 989,765 | <p>My suggestion is - don't generate code. Glade 3.6 can now save in the GtkBuilder format (xml), which can be loaded in your code. This is much easier to deal with!</p>
<p><a href="http://www.pygtk.org/pygtk2reference/class-gtkbuilder.html" rel="nofollow">http://www.pygtk.org/pygtk2reference/class-gtkbuilder.html</a></p>
| 0 | 2009-06-13T02:16:26Z | [
"python",
"gtk",
"glade"
] |
where can I find GladeGen? | 960,049 | <p>I'd like to design a GUI using Glade, and generate python code from it. The thing is, I can't find GladeGen. Does anyone know where it can be downloaded from?</p>
| 3 | 2009-06-06T16:18:05Z | 24,479,543 | <p>It seems to have been copied to this Bazaar repository in launchpad:</p>
<p><a href="https://code.launchpad.net/~wattazoum/pydevtools/gladegen" rel="nofollow">launchpad.net/~wattazoum: gladegen : Code : Python dev tools</a></p>
<p>(direct <a href="http://bazaar.launchpad.net/~wattazoum/pydevtools/gladegen/tarball/3?start_revid=3" rel="nofollow">download tarball</a> - used this for the snippet below)</p>
<p>Also, the links to the article by the author of GladeGen:</p>
<ul>
<li><a href="http://www.linuxjournal.com/article/7421" rel="nofollow">Rapid Application Development with Python and Glade | Linux Journal</a></li>
<li><a href="http://www.linuxjournal.com/article/7558" rel="nofollow">Resources for âRapid Application Development with Python and Gladeâ | Linux Journal</a></li>
</ul>
<p>Note that in Glade 3.8.0, you can export files as either <code>Libglade</code> or <code>GtkBuilder</code>; I made a little test which shows you should save the files as Libglade; GladeGen can parse both:</p>
<pre class="lang-none prettyprint-override"><code>$ python2.7 GladeGen.py /tmp/test-libglade.glade TestMe TestMe
funcs
main <function main at 0xb72d98b4>
search_file <function search_file at 0xb72d964c>
classes
GladeWindow <class 'GladeWindow.GladeWindow'>
TestMe <class 'TestMe.TestMe'>
methods
('GladeWindow', '__init__')
('GladeWindow', 'hide')
('GladeWindow', 'set_callback_function')
('GladeWindow', 'set_search_path')
('GladeWindow', 'set_top_window')
('GladeWindow', 'show')
('TestMe', '__init__')
('TestMe', 'hide')
('TestMe', 'init')
('TestMe', 'set_callback_function')
('TestMe', 'set_search_path')
('TestMe', 'set_top_window')
('TestMe', 'show')
widgets
('GtkWindow', 'window1')
('GtkHBox', 'hbox1')
('GtkScrolledWindow', 'scrolledwindow1')
handlers
$ python2.7 GladeGen.py /tmp/test-gtkbuilder.glade TestMe2 TestMe2
funcs
main <function main at 0x95778ec>
search_file <function search_file at 0x9577684>
classes
GladeWindow <class 'GladeWindow.GladeWindow'>
TestMe2 <class 'TestMe2.TestMe2'>
methods
('GladeWindow', '__init__')
('GladeWindow', 'hide')
('GladeWindow', 'set_callback_function')
('GladeWindow', 'set_search_path')
('GladeWindow', 'set_top_window')
('GladeWindow', 'show')
('TestMe2', '__init__')
('TestMe2', 'hide')
('TestMe2', 'init')
('TestMe2', 'set_callback_function')
('TestMe2', 'set_search_path')
('TestMe2', 'set_top_window')
('TestMe2', 'show')
widgets
handlers
</code></pre>
<p>However, if you try to run the exported python code, only the first (<code>python TestMe.py</code>) will run; while the second, gtkbuilder one, will fail:</p>
<pre class="lang-none prettyprint-override"><code>$ python2.7 TestMe2.py
(TestMe2.py:24883): libglade-WARNING **: Expected <glade-interface>. Got <interface>.
(TestMe2.py:24883): libglade-WARNING **: did not finish in PARSER_FINISH state
Traceback (most recent call last):
File "TestMe2.py", line 66, in <module>
main(sys.argv)
File "TestMe2.py", line 59, in main
w = TestMe2()
File "TestMe2.py", line 37, in __init__
self.init()
File "TestMe2.py", line 52, in init
GladeWindow.__init__(self, filename, top_window, widget_list, handlers)
File "/path/to/src/wattazoum_pydevtools_gladegen/src/GladeWindow.py", line 77, in __init__
self.xml = gtk.glade.XML(fname)
RuntimeError: could not create GladeXML object
</code></pre>
<p>Well, I'm just glad I can still use this, as apparently it is not possible for Glade to generate / export / create / save-as Python code ...</p>
<hr>
<p>... EDIT: although, it should be noted that the export is just:</p>
<pre><code>def init(self):
filename = '/tmp/test-libglade.glade'
widget_list = [
'window1',
'hbox1',
'scrolledwindow1',
]
handlers = [
]
top_window = 'window1'
GladeWindow.__init__(self, filename, top_window, widget_list, handlers)
</code></pre>
<p>... that is, it just interfaces to the glade file (pretty much as in the starting tutorial <a href="http://www.pygtk.org/articles/pygtk-glade-gui/Creating_a_GUI_using_PyGTK_and_Glade.htm" rel="nofollow">http://www.pygtk.org/articles/pygtk-glade-gui/Creating_a_GUI_using_PyGTK_and_Glade.htm</a>), and it doesn't actually create python code that I expected, as in translated code, like:</p>
<pre><code>self.window1 = gtk.Window(gtk.WINDOW_TOPLEVEL)
</code></pre>
<p>... and so on... which is a shame, because that was what I was otherwise looking for <code>:)</code></p>
| 0 | 2014-06-29T19:36:40Z | [
"python",
"gtk",
"glade"
] |
Python App Engine projects with sophisticated user-role-permission structures | 960,125 | <p>In followup to an <a href="http://stackoverflow.com/questions/948631/users-and-roles-in-context">earlier question</a>, I'd be interested to know whether anyone can recommend some open-source Python-based Google App Engine projects with complex user-role-permission models to consult as a reference. A link to the code would be nice.</p>
<p>In my own project, I'd like to add a layer of organizations in addition to the usual roles and permissions, e.g., users are members of one ore more organizations, and their roles are relative to the organizations. A lot like an issue tracker where there is a many-to-many relationship between users and projects.</p>
| 2 | 2009-06-06T17:14:01Z | 965,605 | <p>App-Engine-Patch ports the django permission model over to AppEngine. Scroll down to the Permissions section of this page: <a href="http://code.google.com/p/app-engine-patch/wiki/GettingStarted" rel="nofollow">http://code.google.com/p/app-engine-patch/wiki/GettingStarted</a>. The source code is available from that site as well.</p>
| 3 | 2009-06-08T15:50:45Z | [
"python",
"google-app-engine",
"roles"
] |
How do I use 'F' keys in gtk Accelerators? | 960,269 | <p>I'm trying (in python) to use gtk.Widget.add_accelerator... what should I pass as accel_key to use the F keys? Have attempted to check the docs to no avail.
Thanks</p>
| 2 | 2009-06-06T18:34:54Z | 960,314 | <p>Found it:</p>
<pre><code>key,mods=gtk.accelerator_parse("F10")
</code></pre>
| 1 | 2009-06-06T19:06:46Z | [
"python",
"gtk",
"accelerator"
] |
How do I use 'F' keys in gtk Accelerators? | 960,269 | <p>I'm trying (in python) to use gtk.Widget.add_accelerator... what should I pass as accel_key to use the F keys? Have attempted to check the docs to no avail.
Thanks</p>
| 2 | 2009-06-06T18:34:54Z | 960,315 | <p>Consider using <code>gtk.accelerator_parse()</code>. <a href="http://www.islascruz.org/html/index.php?Blog/SingleView/id/Pygtk%3A-About-keyboard-accelerators" rel="nofollow">Here is an informative post on dealing with keyboard codes in pygtk</a>.</p>
| 2 | 2009-06-06T19:07:01Z | [
"python",
"gtk",
"accelerator"
] |
how can I add a QMenu and QMenuItems to a window from Qt Designer | 960,467 | <p>Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this.</p>
| 0 | 2009-06-06T20:33:32Z | 960,479 | <p>Adding menu editing for every widget in the designer would probably make a very awkward and inconvenient UI. There's really no place you can visualize it on.</p>
<p>If you're editing a QMainWindow you can edit the menu bar and its popups because there's a proper place for them to be displayed in.</p>
| 0 | 2009-06-06T20:38:38Z | [
"python",
"qt",
"widget",
"designer"
] |
how can I add a QMenu and QMenuItems to a window from Qt Designer | 960,467 | <p>Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this.</p>
| 0 | 2009-06-06T20:33:32Z | 960,506 | <p>When you edit a QMainWindow you can right click the window and then choose "create menu bar".</p>
<p>Or are you talking about a "context menu" aka "right click menu"?</p>
| 2 | 2009-06-06T20:48:02Z | [
"python",
"qt",
"widget",
"designer"
] |
how can I add a QMenu and QMenuItems to a window from Qt Designer | 960,467 | <p>Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this.</p>
| 0 | 2009-06-06T20:33:32Z | 1,235,766 | <p>I have a single main window with a QGraphicsView and lots of QGraphicsItem objects. Each type of the Items have a different context menu.</p>
<p>I find that not being able to create the contextMenu's, or at least the actions that are in them a serious limitation of QtDesigner. It means that I can create about 10% or so of the actions using the designer, and I have to create 90% programaticaly. Compare that with the Microsoft resource editor which allows all of these things to be created, and maintained effortlessly. </p>
<p>I hope this will be addressed at some point.</p>
| 2 | 2009-08-05T21:08:00Z | [
"python",
"qt",
"widget",
"designer"
] |
Python's file.read() on Ubuntu | 960,487 | <p>Python's <code>file.read()</code> function won't read anything. It always returns <code>''</code> no matter what's inside the file. What can it be? I know it must be something straightforward, but I can't figure it out.</p>
<p><strong>UPD</strong>: I tried with 'r' and 'w+' modes.</p>
<p><strong>UPD</strong>: The code was:</p>
<pre><code> >>> file = open('helloworld', 'w+')
>>> file.read()
''
</code></pre>
<p><strong>Solution</strong>: It just came to me that, although a file is available for reading in 'w+' mode, Python truncates it after opening. 'r' (or 'r+') mode should be used instead. Thanks everyone.</p>
| 1 | 2009-06-06T20:42:52Z | 960,514 | <p>Caveat: I'm just guessing as to behavior that is not 'working':</p>
<p>If you're working in the Python interpreter, <br />
and you do something like this:</p>
<pre><code>>>> f = open('myfile.txt', 'r')
>>> f.read()
</code></pre>
<p>...you'll get the whole file printed to the screen.</p>
<p>But if you do this again:</p>
<pre><code>>>> f.read()
''
</code></pre>
<p>...you get an empty string.</p>
<p>So, if you haven't already, maybe try restarting your interpreter.</p>
<p>From the <a href="http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">documentation</a>:</p>
<p>"To read a fileâs contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; itâs your problem if the file is twice as large as your machineâs memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("")."</p>
| 2 | 2009-06-06T20:53:33Z | [
"python",
"file",
"ubuntu"
] |
What is the proper way to compute the fully expanded width of wx.TreeCtrl | 960,489 | <p>The preferred size of the wx.TreeCtrl seems to be the minimum size into which all elements will fit when the tree is completely collapsed. Is there a good (ie cross-platform compatible) way to compute the width of the tree with everything expanded? My current solution is this:</p>
<pre><code>def max_width(self):
dc = wx.ScreenDC()
dc.SetFont(self.GetFont())
widths = []
for item, depth in self.__walk_items():
if item != self.root:
width = dc.GetTextExtent(self.GetItemText(item))[0] + self.GetIndent()*depth
widths.append(width)
return max(widths) + self.GetIndent()
</code></pre>
<p>This works great in win32, but no good under linux. Is there some way to get the TreeCtrl itself to tell me its size so that I can override the size it reports? (ALways returning the maximally expanded width)</p>
<p><em>edit: pardon me for not providing the functions I use above, but you get the idea, I'm walking the tree, and getting the width of every label, and returning the total width of the widest one (accounting for indent)</em></p>
| 2 | 2009-06-06T20:44:16Z | 960,957 | <p>I find that the <code>GetBestSize</code> seems to consider the collapsed items. For example, with the <code>wxTreeCtrl</code> in the demo (using Ubuntu, and wxPython 2.8.7.1), when I change the length of the inner text string (line 74 in my version of the demo) the return value of <code>self.tree.GetBestSize()</code> does take this new length of the inner string into account, even though the tree is unexpanded. Maybe you need to call <code>SetQuickBestSize(False)</code>?</p>
| 1 | 2009-06-07T01:11:04Z | [
"python",
"wxpython",
"size"
] |
What is the proper way to compute the fully expanded width of wx.TreeCtrl | 960,489 | <p>The preferred size of the wx.TreeCtrl seems to be the minimum size into which all elements will fit when the tree is completely collapsed. Is there a good (ie cross-platform compatible) way to compute the width of the tree with everything expanded? My current solution is this:</p>
<pre><code>def max_width(self):
dc = wx.ScreenDC()
dc.SetFont(self.GetFont())
widths = []
for item, depth in self.__walk_items():
if item != self.root:
width = dc.GetTextExtent(self.GetItemText(item))[0] + self.GetIndent()*depth
widths.append(width)
return max(widths) + self.GetIndent()
</code></pre>
<p>This works great in win32, but no good under linux. Is there some way to get the TreeCtrl itself to tell me its size so that I can override the size it reports? (ALways returning the maximally expanded width)</p>
<p><em>edit: pardon me for not providing the functions I use above, but you get the idea, I'm walking the tree, and getting the width of every label, and returning the total width of the widest one (accounting for indent)</em></p>
| 2 | 2009-06-06T20:44:16Z | 975,622 | <p>This code works for me on both windows and linux:</p>
<pre><code>def compute_best_size(self):
if os.name == 'nt':
best_size = (self.__max_width_win32(), -1)
else:
best_size = (self.__max_width(), -1)
self.SetMinSize(best_size)
def __max_width_win32(self):
dc = wx.ScreenDC()
dc.SetFont(self.GetFont())
widths = []
for item, depth in self.__walk_items():
if item != self.root:
width = dc.GetTextExtent(self.GetItemText(item))[0] + self.GetIndent()*depth
widths.append(width)
return max(widths) + self.GetIndent()
def __max_width(self):
self.Freeze()
expanded = {}
for item in self.get_items():
if item is not self.root:
expanded[item] = self.IsExpanded(item)
self.ExpandAll()
best_size = self.GetBestSize()
for item in expanded:
if not expanded[item]: self.Collapse(item)
self.Thaw()
return best_size[0]
</code></pre>
<p>... And call <code>compute_best_size()</code> every time a new item is added to the tree.</p>
| 0 | 2009-06-10T13:32:11Z | [
"python",
"wxpython",
"size"
] |
How to generate permutations of a list without "reverse duplicates" in Python using generators | 960,557 | <p>This is related to question <a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>
<p>How to generate all permutations that <em>match following criteria</em>: <strong>if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result</strong>.</p>
<p>Example:</p>
<pre><code>permutations_without_duplicates ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
</code></pre>
<p>I am permuting lists that contain unique integers.</p>
<p>The number of resulting permutations will be high so I'd like to use Python's generators if possible.</p>
<p>Edit: I'd like not to store list of all permutations to memory if possible.</p>
| 5 | 2009-06-06T21:15:22Z | 960,571 | <p><a href="http://docs.python.org/library/itertools.html?highlight=itertools#itertools.permutations" rel="nofollow"><code>itertools.permutations</code></a> does exactly what you want. you might make of use of <a href="http://docs.python.org/library/functions.html?highlight=reversed#reversed" rel="nofollow"><code>reversed</code> built-in</a> as well</p>
| 0 | 2009-06-06T21:23:19Z | [
"python",
"algorithm",
"generator",
"combinatorics"
] |
How to generate permutations of a list without "reverse duplicates" in Python using generators | 960,557 | <p>This is related to question <a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>
<p>How to generate all permutations that <em>match following criteria</em>: <strong>if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result</strong>.</p>
<p>Example:</p>
<pre><code>permutations_without_duplicates ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
</code></pre>
<p>I am permuting lists that contain unique integers.</p>
<p>The number of resulting permutations will be high so I'd like to use Python's generators if possible.</p>
<p>Edit: I'd like not to store list of all permutations to memory if possible.</p>
| 5 | 2009-06-06T21:15:22Z | 960,612 | <p><strong>EDIT</strong>: changed completely to keep everything as a generator (never the whole list in memory). Should fulfill the requirements (only calculates half of the possible permutations (not the reverse ones).
<strong>EDIT2</strong>: added shorter (and simpler) factorial function from <a href="http://importantshock.wordpress.com/2006/11/03/one-line-factorial-function-in-python/" rel="nofollow">here</a>.</p>
<p><strong>EDIT3:</strong>: (see comments) - a version with improvements can be found in <a href="http://stackoverflow.com/questions/960557/how-to-generate-permutations-of-a-list-without-reverse-duplicates-in-python-usi/962134#962134">bwopah's version</a>.</p>
<pre><code>def fac(x):
return (1 if x==0 else x * fac(x-1))
def all_permutations(plist):
global counter
if len(plist) <=1:
yield plist
else:
for perm in all_permutations(plist[1:]):
for i in xrange(len(perm)+1):
if len(perm[:i] + plist[0:1] + perm[i:]) == lenplist:
if counter == limit:
raise StopIteration
else:
counter = counter + 1
yield perm[:i] + plist[0:1] + perm[i:]
counter = 0
plist = ['a','b','c']
lenplist = len(plist)
limit = fac(lenplist) / 2
all_permutations_gen = all_permutations(plist)
print all_permutations_gen
print list(all_permutations_gen)
</code></pre>
| 3 | 2009-06-06T21:41:56Z | [
"python",
"algorithm",
"generator",
"combinatorics"
] |
How to generate permutations of a list without "reverse duplicates" in Python using generators | 960,557 | <p>This is related to question <a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>
<p>How to generate all permutations that <em>match following criteria</em>: <strong>if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result</strong>.</p>
<p>Example:</p>
<pre><code>permutations_without_duplicates ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
</code></pre>
<p>I am permuting lists that contain unique integers.</p>
<p>The number of resulting permutations will be high so I'd like to use Python's generators if possible.</p>
<p>Edit: I'd like not to store list of all permutations to memory if possible.</p>
| 5 | 2009-06-06T21:15:22Z | 960,651 | <p>How about this:</p>
<pre><code>from itertools import permutations
def rev_generator(plist):
reversed_elements = set()
for i in permutations(plist):
if i not in reversed_elements:
reversed_i = tuple(reversed(i))
reversed_elements.add(reversed_i)
yield i
>>> list(rev_generator([1,2,3]))
[(1, 2, 3), (1, 3, 2), (2, 1, 3)]
</code></pre>
<p>Also, if the return value must be a list, you could just change the yield i to yield list(i), but for iteration purposes, the tuples will work just fine.</p>
| 2 | 2009-06-06T22:01:06Z | [
"python",
"algorithm",
"generator",
"combinatorics"
] |
How to generate permutations of a list without "reverse duplicates" in Python using generators | 960,557 | <p>This is related to question <a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>
<p>How to generate all permutations that <em>match following criteria</em>: <strong>if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result</strong>.</p>
<p>Example:</p>
<pre><code>permutations_without_duplicates ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
</code></pre>
<p>I am permuting lists that contain unique integers.</p>
<p>The number of resulting permutations will be high so I'd like to use Python's generators if possible.</p>
<p>Edit: I'd like not to store list of all permutations to memory if possible.</p>
| 5 | 2009-06-06T21:15:22Z | 960,686 | <p>Here is code that does the trick. To get rid of the dups I noticed that for your list if the value of the first location is greater than the value of the last location then it will be a dup. I create a map to keep track of where each item was in the list to start with and then use that map to do the test. The code also does not use recursion so it keeps its memory footprint small. Also the list can be of any type items not just numbers see the last two test cases.</p>
<p>Here is the code.</p>
<pre><code>class Permutation:
def __init__(self, justalist):
self._data = justalist[:]
self._len=len(self._data)
self._s=[]
self._nfact=1
self._map ={}
i=0
for elem in self._data:
self._s.append(elem)
self._map[str(elem)]=i
i+=1
self._nfact*=i
if i != 0:
self._nfact2=self._nfact//i
def __iter__(self):
for k in range(self._nfact):
for i in range(self._len):
self._s[i]=self._data[i]
s=self._s
factorial=self._nfact2
for i in range(self._len-1):
tempi = (k // factorial) % (self._len - i)
temp = s[i + tempi]
for j in range(i + tempi,i,-1):
s[j] = s[j-1]
s[i] = temp
factorial //= (self._len - (i + 1))
if self._map[str(s[0])] < self._map[str(s[-1])]:
yield s
s=[1,2]
print("_"*25)
print("input list:",s)
for sx in Permutation(s):
print(sx)
s=[1,2,3]
print("_"*25)
print("input list:",s)
for sx in Permutation(s):
print(sx)
s=[1,2,3,4]
print("_"*25)
print("input list:",s)
for sx in Permutation(s):
print(sx)
s=[3,2,1]
print("_"*25)
print("input list:",s)
for sx in Permutation(s):
print(sx)
s=["Apple","Pear","Orange"]
print("_"*25)
print("input list:",s)
for sx in Permutation(s):
print(sx)
s=[[1,4,5],"Pear",(1,6,9),Permutation([])]
print("_"*25)
print("input list:",s)
for sx in Permutation(s):
print(sx)
</code></pre>
<p>and here is the output for my test cases.</p>
<pre><code>_________________________
input list: [1, 2]
[1, 2]
_________________________
input list: [1, 2, 3]
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
_________________________
input list: [1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 2, 3]
[1, 4, 3, 2]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 4, 1, 3]
[3, 1, 2, 4]
[3, 2, 1, 4]
_________________________
input list: [3, 2, 1]
[3, 2, 1]
[3, 1, 2]
[2, 3, 1]
_________________________
input list: ['Apple', 'Pear', 'Orange']
['Apple', 'Pear', 'Orange']
['Apple', 'Orange', 'Pear']
['Pear', 'Apple', 'Orange']
_________________________
input list: [[1, 4, 5], 'Pear', (1, 6, 9), <__main__.Permutation object at 0x0142DEF0>]
[[1, 4, 5], 'Pear', (1, 6, 9), <__main__.Permutation object at 0x0142DEF0>]
[[1, 4, 5], 'Pear', <__main__.Permutation object at 0x0142DEF0>, (1, 6, 9)]
[[1, 4, 5], (1, 6, 9), 'Pear', <__main__.Permutation object at 0x0142DEF0>]
[[1, 4, 5], (1, 6, 9), <__main__.Permutation object at 0x0142DEF0>, 'Pear']
[[1, 4, 5], <__main__.Permutation object at 0x0142DEF0>, 'Pear', (1, 6, 9)]
[[1, 4, 5], <__main__.Permutation object at 0x0142DEF0>, (1, 6, 9), 'Pear']
['Pear', [1, 4, 5], (1, 6, 9), <__main__.Permutation object at 0x0142DEF0>]
['Pear', [1, 4, 5], <__main__.Permutation object at 0x0142DEF0>, (1, 6, 9)]
['Pear', (1, 6, 9), [1, 4, 5], <__main__.Permutation object at 0x0142DEF0>]
['Pear', <__main__.Permutation object at 0x0142DEF0>, [1, 4, 5], (1, 6, 9)]
[(1, 6, 9), [1, 4, 5], 'Pear', <__main__.Permutation object at 0x0142DEF0>]
[(1, 6, 9), 'Pear', [1, 4, 5], <__main__.Permutation object at 0x0142DEF0>]
</code></pre>
| 2 | 2009-06-06T22:18:05Z | [
"python",
"algorithm",
"generator",
"combinatorics"
] |
How to generate permutations of a list without "reverse duplicates" in Python using generators | 960,557 | <p>This is related to question <a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>
<p>How to generate all permutations that <em>match following criteria</em>: <strong>if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result</strong>.</p>
<p>Example:</p>
<pre><code>permutations_without_duplicates ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
</code></pre>
<p>I am permuting lists that contain unique integers.</p>
<p>The number of resulting permutations will be high so I'd like to use Python's generators if possible.</p>
<p>Edit: I'd like not to store list of all permutations to memory if possible.</p>
| 5 | 2009-06-06T21:15:22Z | 960,725 | <p>this is an implementation of onebyone's suggestion</p>
<p>from <a href="http://en.wikipedia.org/wiki/Permutation#Lexicographical_order_generation" rel="nofollow">http://en.wikipedia.org/wiki/Permutation#Lexicographical_order_generation</a>
The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.</p>
<ol>
<li>Find the highest index i such that s[i] < s[i+1]. If no such index exists, the permutation is the last permutation.</li>
<li>Find the highest index j > i such that s[j] > s[i]. Such a j must exist, since i+1 is such an index.</li>
<li>Swap s[i] with s[j].</li>
<li>Reverse all the order of all of the elements after index i</li>
</ol>
<p>the function:</p>
<pre><code>def perms(items):
items.sort()
yield items[:]
m = [len(items)-2] # step 1
while m:
i = m[-1]
j = [ j for j in range(i+1,len(items)) if items[j]>items[i] ][-1] # step 2
items[i], items[j] = items[j], items[i] # step 3
items[i+1:] = list(reversed(items[i+1:])) # step 4
if items<list(reversed(items)):
yield items[:]
m = [ i for i in range(len(items)-1) if items[i]<items[i+1] ] # step 1
</code></pre>
<p>checking our work:</p>
<pre><code>>>> foo=list(perms([1,3,2,4,5]))
>>> True in [(list(reversed(i)) in foo) for i in foo]
False
</code></pre>
| 1 | 2009-06-06T22:44:03Z | [
"python",
"algorithm",
"generator",
"combinatorics"
] |
How to generate permutations of a list without "reverse duplicates" in Python using generators | 960,557 | <p>This is related to question <a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>
<p>How to generate all permutations that <em>match following criteria</em>: <strong>if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result</strong>.</p>
<p>Example:</p>
<pre><code>permutations_without_duplicates ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
</code></pre>
<p>I am permuting lists that contain unique integers.</p>
<p>The number of resulting permutations will be high so I'd like to use Python's generators if possible.</p>
<p>Edit: I'd like not to store list of all permutations to memory if possible.</p>
| 5 | 2009-06-06T21:15:22Z | 960,730 | <p>If you generate permutations in lexicographical order, then you don't need to store anything to work out whether the reverse of a given permutation has already been seen. You just have to lexicographically compare it to its reverse - if it's smaller then return it, if it's larger then skip it.</p>
<p>There's probably a more efficient way to do it, but this is simple and has the properties you require (implementable as a generator, uses O(n) working memory).</p>
| 10 | 2009-06-06T22:46:24Z | [
"python",
"algorithm",
"generator",
"combinatorics"
] |
How to generate permutations of a list without "reverse duplicates" in Python using generators | 960,557 | <p>This is related to question <a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>
<p>How to generate all permutations that <em>match following criteria</em>: <strong>if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result</strong>.</p>
<p>Example:</p>
<pre><code>permutations_without_duplicates ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
</code></pre>
<p>I am permuting lists that contain unique integers.</p>
<p>The number of resulting permutations will be high so I'd like to use Python's generators if possible.</p>
<p>Edit: I'd like not to store list of all permutations to memory if possible.</p>
| 5 | 2009-06-06T21:15:22Z | 961,563 | <p>Some setup code first:</p>
<pre><code>try:
from itertools import permutations
except ImportError:
# straight from http://docs.python.org/library/itertools.html#itertools.permutations
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
def non_reversed_permutations(iterable):
"Return non-reversed permutations for an iterable with unique items"
for permutation in permutations(iterable):
if permutation[0] < permutation[-1]:
yield permutation
</code></pre>
| 1 | 2009-06-07T09:14:46Z | [
"python",
"algorithm",
"generator",
"combinatorics"
] |
How to generate permutations of a list without "reverse duplicates" in Python using generators | 960,557 | <p>This is related to question <a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>
<p>How to generate all permutations that <em>match following criteria</em>: <strong>if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result</strong>.</p>
<p>Example:</p>
<pre><code>permutations_without_duplicates ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
</code></pre>
<p>I am permuting lists that contain unique integers.</p>
<p>The number of resulting permutations will be high so I'd like to use Python's generators if possible.</p>
<p>Edit: I'd like not to store list of all permutations to memory if possible.</p>
| 5 | 2009-06-06T21:15:22Z | 962,134 | <p>This is a more concise and faster version of ChristopheD's accepted answer, which I liked a lot. Recursion is great. I made it enforce uniquenss of the incoming list by removing duplicates, however maybe it should just raise an exception instead.</p>
<pre><code>def fac(x):
return (1 if x==0 else x * fac(x-1))
def permz(plist):
plist = sorted(set(plist))
plen = len(plist)
limit = fac(plen) / 2
counter = 0
if plen==1:
yield plist
else:
for perm in permz(plist[1:]):
for i in xrange(plen):
if counter == limit:
raise StopIteration
counter += 1
yield perm[:i] + plist[0:1] + perm[i:]
# ---- testing ----
plists = [
list('love'),
range(5),
[1,4,2,3,9],
['a',2,2.1],
range(8)]
for plist in plists:
perms = list(permz(plist))
print plist, True in [(list(reversed(i)) in foo) for i in perms]
</code></pre>
| 3 | 2009-06-07T15:46:56Z | [
"python",
"algorithm",
"generator",
"combinatorics"
] |
How to generate permutations of a list without "reverse duplicates" in Python using generators | 960,557 | <p>This is related to question <a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>
<p>How to generate all permutations that <em>match following criteria</em>: <strong>if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result</strong>.</p>
<p>Example:</p>
<pre><code>permutations_without_duplicates ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
</code></pre>
<p>I am permuting lists that contain unique integers.</p>
<p>The number of resulting permutations will be high so I'd like to use Python's generators if possible.</p>
<p>Edit: I'd like not to store list of all permutations to memory if possible.</p>
| 5 | 2009-06-06T21:15:22Z | 963,022 | <p>Here is my implementation:</p>
<pre><code>a = [1,2,3,4]
def p(l):
if len(l) <= 1:
yield l
else:
for i in range(len(l)):
for q in p([l[j] for j in range(len(l)) if j != i]):
yield [l[i]] + q
out = (i for i in p(a) if i < i[::-1])
</code></pre>
<p>P function is a regular permu function, yields all possibilities. The filter is done when iterates the result. Simply, it has two possible results, the smaller half of the all permus and the bigger half of the permus. In this example, the out contains the smaller half of the list.</p>
| 2 | 2009-06-07T23:26:32Z | [
"python",
"algorithm",
"generator",
"combinatorics"
] |
How to generate permutations of a list without "reverse duplicates" in Python using generators | 960,557 | <p>This is related to question <a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>
<p>How to generate all permutations that <em>match following criteria</em>: <strong>if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result</strong>.</p>
<p>Example:</p>
<pre><code>permutations_without_duplicates ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
</code></pre>
<p>I am permuting lists that contain unique integers.</p>
<p>The number of resulting permutations will be high so I'd like to use Python's generators if possible.</p>
<p>Edit: I'd like not to store list of all permutations to memory if possible.</p>
| 5 | 2009-06-06T21:15:22Z | 1,985,841 | <p>I have a marvelous followup to SilentGhost's proposal - posting a separate answer since the margins of a comment would be too narrow to contain code :-)</p>
<p><code>itertools.permutations</code> is built in (since 2.6) and fast. We just need a filtering condition that for every (perm, perm[::-1]) would accept exactly one of them. Since the OP says items are always distinct, we can just compare any 2 elements:</p>
<pre><code>for p in itertools.permutations(range(3)):
if p[0] < p[-1]:
print p
</code></pre>
<p>which prints:</p>
<pre><code>(0, 1, 2)
(0, 2, 1)
(1, 0, 2)
</code></pre>
<p>This works because reversing the permutation would always flip the relation!<br>
<code>p[0] < p[1]</code> or any other pair would also work, so you also have some control over which half of permutations you get.</p>
<p>I'm not sure if there is any more effecient way to filter. <code>itertools.permutations</code> guarantees lexicographic order, but the lexicographic position <code>p</code> and <code>p[::-1]</code> are related in a quite complex way. In particular, just stopping at the middle doesn't work.</p>
<p>But I suspect (didn't check) that the built-in iterator with 2:1 filtering would outperform any custom implementation. And of course it wins on simplicity!</p>
| 6 | 2009-12-31T15:32:12Z | [
"python",
"algorithm",
"generator",
"combinatorics"
] |
python3.0: imputils | 960,646 | <p>Why was the imputil module removed from python3.0 and what should be used in its place?</p>
| 4 | 2009-06-06T21:58:16Z | 960,665 | <p>According to <a href="http://www.python.org/dev/peps/pep-3108/#hardly-used-done">PEP 3108</a>, it was rarely used, undocumented and never updated to support absolute imports.</p>
| 9 | 2009-06-06T22:09:39Z | [
"python-3.x",
"python"
] |
python3.0: imputils | 960,646 | <p>Why was the imputil module removed from python3.0 and what should be used in its place?</p>
| 4 | 2009-06-06T21:58:16Z | 960,759 | <p>In Python 3.1, there is a module called <a href="http://doc.python.org/dev/py3k/library/importlib.html">importlib</a>, which should be a superior replacement for imputil.</p>
| 10 | 2009-06-06T23:04:26Z | [
"python-3.x",
"python"
] |
Python creating a dictionary of lists | 960,733 | <p>I want to create a dictionary whose values are lists. For example: </p>
<pre><code>{
1: ['1'],
2: ['1','2'],
3: ['2']
}
</code></pre>
<p>If I do:</p>
<pre><code>d = dict()
a = ['1', '2']
for i in a:
for j in range(int(i), int(i) + 2):
d[j].append(i)
</code></pre>
<p>I get a KeyError, because d[...] isn't a list. In this case, I can add the following code after the assignment of a to initialize the dictionary. </p>
<pre><code>for x in range(1, 4):
d[x] = list()
</code></pre>
<p>Is there a better way to do this? Lets say I don't know the keys I am going to need until I am in the second <code>for</code> loop. For example:</p>
<pre><code>class relation:
scope_list = list()
...
d = dict()
for relation in relation_list:
for scope_item in relation.scope_list:
d[scope_item].append(relation)
</code></pre>
<p>An alternative would then be replacing </p>
<pre><code>d[scope_item].append(relation)
</code></pre>
<p>with </p>
<pre><code>if d.has_key(scope_item):
d[scope_item].append(relation)
else:
d[scope_item] = [relation,]
</code></pre>
<p>What is the best way to handle this? Ideally, appending would "just work". Is there some way to express that I want a dictionary of empty lists, even if I don't know every key when I first create the list?</p>
| 131 | 2009-06-06T22:47:29Z | 960,735 | <p>Use <code>setdefault</code>:</p>
<pre><code>d = dict()
a = ['1', '2']
for i in a:
for j in range(int(i), int(i) + 2):
d.setdefault(j, []).append(i)
print d # prints {1: ['1'], 2: ['1', '2'], 3: ['2']}
</code></pre>
<p>The rather oddly-named <code>setdefault</code> function says "Get the value with this key, or if that key isn't there, add this value and then return it."</p>
<p><strong>Edit</strong>: As others have rightly pointed out, <code>defaultdict</code> is a better and more modern choice. <code>setdefault</code> is still useful in older versions of Python (prior to 2.5).</p>
| 18 | 2009-06-06T22:49:49Z | [
"python",
"dictionary"
] |
Python creating a dictionary of lists | 960,733 | <p>I want to create a dictionary whose values are lists. For example: </p>
<pre><code>{
1: ['1'],
2: ['1','2'],
3: ['2']
}
</code></pre>
<p>If I do:</p>
<pre><code>d = dict()
a = ['1', '2']
for i in a:
for j in range(int(i), int(i) + 2):
d[j].append(i)
</code></pre>
<p>I get a KeyError, because d[...] isn't a list. In this case, I can add the following code after the assignment of a to initialize the dictionary. </p>
<pre><code>for x in range(1, 4):
d[x] = list()
</code></pre>
<p>Is there a better way to do this? Lets say I don't know the keys I am going to need until I am in the second <code>for</code> loop. For example:</p>
<pre><code>class relation:
scope_list = list()
...
d = dict()
for relation in relation_list:
for scope_item in relation.scope_list:
d[scope_item].append(relation)
</code></pre>
<p>An alternative would then be replacing </p>
<pre><code>d[scope_item].append(relation)
</code></pre>
<p>with </p>
<pre><code>if d.has_key(scope_item):
d[scope_item].append(relation)
else:
d[scope_item] = [relation,]
</code></pre>
<p>What is the best way to handle this? Ideally, appending would "just work". Is there some way to express that I want a dictionary of empty lists, even if I don't know every key when I first create the list?</p>
| 131 | 2009-06-06T22:47:29Z | 960,748 | <p>You can build it with list comprehension like this:</p>
<pre><code>>>> dict((i, range(int(i), int(i) + 2)) for i in ['1', '2'])
{'1': [1, 2], '2': [2, 3]}
</code></pre>
<p>And for the second part of your question use <a href="http://www.python.org/doc/2.5.2/lib/defaultdict-examples.html">defaultdict</a></p>
<pre><code>>>> from collections import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
d[k].append(v)
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
</code></pre>
| 34 | 2009-06-06T22:54:33Z | [
"python",
"dictionary"
] |
Python creating a dictionary of lists | 960,733 | <p>I want to create a dictionary whose values are lists. For example: </p>
<pre><code>{
1: ['1'],
2: ['1','2'],
3: ['2']
}
</code></pre>
<p>If I do:</p>
<pre><code>d = dict()
a = ['1', '2']
for i in a:
for j in range(int(i), int(i) + 2):
d[j].append(i)
</code></pre>
<p>I get a KeyError, because d[...] isn't a list. In this case, I can add the following code after the assignment of a to initialize the dictionary. </p>
<pre><code>for x in range(1, 4):
d[x] = list()
</code></pre>
<p>Is there a better way to do this? Lets say I don't know the keys I am going to need until I am in the second <code>for</code> loop. For example:</p>
<pre><code>class relation:
scope_list = list()
...
d = dict()
for relation in relation_list:
for scope_item in relation.scope_list:
d[scope_item].append(relation)
</code></pre>
<p>An alternative would then be replacing </p>
<pre><code>d[scope_item].append(relation)
</code></pre>
<p>with </p>
<pre><code>if d.has_key(scope_item):
d[scope_item].append(relation)
else:
d[scope_item] = [relation,]
</code></pre>
<p>What is the best way to handle this? Ideally, appending would "just work". Is there some way to express that I want a dictionary of empty lists, even if I don't know every key when I first create the list?</p>
| 131 | 2009-06-06T22:47:29Z | 960,753 | <p>You can use <a href="http://docs.python.org/library/collections.html#collections.defaultdict">defaultdict</a>:</p>
<pre><code>>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for i in a:
... for j in range(int(i), int(i) + 2):
... d[j].append(i)
...
>>> d
defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']})
>>> d.items()
[(1, ['1']), (2, ['1', '2']), (3, ['2'])]
</code></pre>
| 164 | 2009-06-06T23:00:39Z | [
"python",
"dictionary"
] |
Python creating a dictionary of lists | 960,733 | <p>I want to create a dictionary whose values are lists. For example: </p>
<pre><code>{
1: ['1'],
2: ['1','2'],
3: ['2']
}
</code></pre>
<p>If I do:</p>
<pre><code>d = dict()
a = ['1', '2']
for i in a:
for j in range(int(i), int(i) + 2):
d[j].append(i)
</code></pre>
<p>I get a KeyError, because d[...] isn't a list. In this case, I can add the following code after the assignment of a to initialize the dictionary. </p>
<pre><code>for x in range(1, 4):
d[x] = list()
</code></pre>
<p>Is there a better way to do this? Lets say I don't know the keys I am going to need until I am in the second <code>for</code> loop. For example:</p>
<pre><code>class relation:
scope_list = list()
...
d = dict()
for relation in relation_list:
for scope_item in relation.scope_list:
d[scope_item].append(relation)
</code></pre>
<p>An alternative would then be replacing </p>
<pre><code>d[scope_item].append(relation)
</code></pre>
<p>with </p>
<pre><code>if d.has_key(scope_item):
d[scope_item].append(relation)
else:
d[scope_item] = [relation,]
</code></pre>
<p>What is the best way to handle this? Ideally, appending would "just work". Is there some way to express that I want a dictionary of empty lists, even if I don't know every key when I first create the list?</p>
| 131 | 2009-06-06T22:47:29Z | 961,154 | <p>Your question has already been answered, but IIRC you can replace lines like:</p>
<pre><code>if d.has_key(scope_item):
</code></pre>
<p>with:</p>
<pre><code>if scope_item in d:
</code></pre>
<p>That is, <code>d</code> references <code>d.keys()</code> in that construction. Sometimes <code>defaultdict</code> isn't the best option (for example, if you want to execute multiple lines of code after the <code>else</code> associated with the above <code>if</code>), and I find the <code>in</code> syntax easier to read.</p>
| 1 | 2009-06-07T03:51:47Z | [
"python",
"dictionary"
] |
PEP 302 Example: New Import Hooks | 960,832 | <p>Where can I find an example implementation of the "New Import Hooks" described in <a href="http://www.python.org/dev/peps/pep-0302/">PEP 302</a>?</p>
<p>I would like to implement a custom finder and loader in the most forward compatible way possible. In other words, the implementation should work in python 2.x and 3.x.</p>
| 12 | 2009-06-06T23:50:42Z | 960,844 | <p>You can find thousands of open-source examples e.g. with a <a href="http://www.google.com/codesearch?hl=en&lr=&q="imp.find_module"+"imp.load_module"&sbtn=Search" rel="nofollow">google code search</a>, here it is:</p>
<pre><code>http://www.google.com/codesearch?hl=en&lr=&q="imp.find_module"+"imp.load_module"&sbtn=Search
</code></pre>
<p>Edit: as the questioner clarified he's looking for example of implementation, not use, a better <a href="http://www.google.com/codesearch?hl=en&sa=N&q="path_hooks"++lang:python&ct=rr&cs_r=lang:python" rel="nofollow">URL</a> for the search is:</p>
<pre><code>http://www.google.com/codesearch?hl=en&sa=N&q="path_hooks"++lang:python&ct=rr&cs_r=lang:python
</code></pre>
<p>One readable example (though NOT suitable for production use, as the <a href="http://www.reddit.com/r/programming/comments/8nl4/a_python_script_for_importing_modules_over_the_net" rel="nofollow">reddit</a> discussion points out!) is <a href="http://urlimport.codeshift.net/UrlImport" rel="nofollow">urlimport</a>.</p>
<p>As for supporting Python 2 and Python 3 at the same time, that sounds ambitious -- I don't know of any existing import hook which claims to. In your shoes, I'd start with offering full support for Python 2.6, then once that's working (and has a good battery of tests and makes nary a peep with the <code>-3</code> switch), I'd <code>2to3</code> the sources and see if anything breaks (if so, find out why, fix the 2.6 sources, iterate).</p>
| 4 | 2009-06-06T23:56:27Z | [
"python-3.x",
"python",
"http-status-code-302",
"import-hooks"
] |
Trie (Prefix Tree) in Python | 960,963 | <p>I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :)</p>
<p>If anything is unclear I'm very happy to clarify things.</p>
<p>I just implemented a <a href="http://en.wikipedia.org/wiki/Trie">Trie</a> in python. However, one bit seemed to be more complicated than it ought to (as someone who loves simplicity). Perhaps someone has had a similar problem?</p>
<p>My aim was to minimize the number of nodes by storing the largest common prefix of a sub-trie in its root. For example, if we had the words <strong>stackoverflow</strong>, <strong>stackbase</strong> and <strong>stackbased</strong>, then the tree would look something like this:</p>
<pre><code> [s]tack
[o]verflow ______/ \_______ [b]ase
\___ [d]
</code></pre>
<p>Note that one can still think of the edges having one character (the first one of the child node).</p>
<p><em>Find</em>-query is simple to implement.
<em>Insertion</em> is not hard, but somewhat more complex than I want.. :(</p>
<p>My idea was to insert the keys one after the other (starting from an empty trie), by first searching for the to-be-inserted key k (<em>Find</em>(k)), and then rearranging/splitting the nodes locally at the place where the find-procedure stops. There turn out to be 4 cases:
(Let k be the key we want to insert, and k' be the key of the node, where the search ended)</p>
<ol>
<li>k is identical to k'</li>
<li>k is a "proper" prefix of k'</li>
<li>k' is a "proper" prefix of k</li>
<li>k and k' share some common prefix, but none of the cases (1), (2) or (3) occur.</li>
</ol>
<p>It seems that each of the cases are unique and thus imply different modifications of the Trie. BUT: is it really that complex? Am I missing something? Is there a better approach?</p>
<p>Thanks :)</p>
| 16 | 2009-06-07T01:14:07Z | 960,971 | <p>I don't see anything wrong with your approach. If you're looking for a spike solution, perhaps the action taken in case 4 is actually feasible for the first three cases, IE find the common prefix to <code>k</code> and <code>k'</code> and rebuild the node with that in mind. If it happens that the keys were prefixes of one-another, the resulting trie will still be correct, only the implementation did a bit more work than it really had to. but then again, without any code to look at it's hard to say if this works in your case.</p>
| 2 | 2009-06-07T01:21:00Z | [
"python",
"algorithm",
"trie"
] |
Trie (Prefix Tree) in Python | 960,963 | <p>I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :)</p>
<p>If anything is unclear I'm very happy to clarify things.</p>
<p>I just implemented a <a href="http://en.wikipedia.org/wiki/Trie">Trie</a> in python. However, one bit seemed to be more complicated than it ought to (as someone who loves simplicity). Perhaps someone has had a similar problem?</p>
<p>My aim was to minimize the number of nodes by storing the largest common prefix of a sub-trie in its root. For example, if we had the words <strong>stackoverflow</strong>, <strong>stackbase</strong> and <strong>stackbased</strong>, then the tree would look something like this:</p>
<pre><code> [s]tack
[o]verflow ______/ \_______ [b]ase
\___ [d]
</code></pre>
<p>Note that one can still think of the edges having one character (the first one of the child node).</p>
<p><em>Find</em>-query is simple to implement.
<em>Insertion</em> is not hard, but somewhat more complex than I want.. :(</p>
<p>My idea was to insert the keys one after the other (starting from an empty trie), by first searching for the to-be-inserted key k (<em>Find</em>(k)), and then rearranging/splitting the nodes locally at the place where the find-procedure stops. There turn out to be 4 cases:
(Let k be the key we want to insert, and k' be the key of the node, where the search ended)</p>
<ol>
<li>k is identical to k'</li>
<li>k is a "proper" prefix of k'</li>
<li>k' is a "proper" prefix of k</li>
<li>k and k' share some common prefix, but none of the cases (1), (2) or (3) occur.</li>
</ol>
<p>It seems that each of the cases are unique and thus imply different modifications of the Trie. BUT: is it really that complex? Am I missing something? Is there a better approach?</p>
<p>Thanks :)</p>
| 16 | 2009-06-07T01:14:07Z | 961,039 | <p>At a glance, it sounds like you've implemented a <a href="http://portal.acm.org/citation.cfm?id=321481">Patricia Trie</a>. This approach also is called path compression in some of the literature. There should be copies of that paper that aren't behind the ACM paywall, which will include an insertion algorithm.</p>
<p>There's also another compression method you may want to look at: level compression. The idea behind path compression is to replace strings of single child nodes with a single super node that has a "skip" count. The idea behind level compression is to replace full or nearly full subtrees with a super node with a "degree" count that says how many digits of the key the node decodes. There's also a 3rd approach called width compression, but I'm afraid my memory fails me and I couldn't find a description of it with quick googling. </p>
<p>Level compression can shorten the average path considerably, but insertion and removal algorithms get quite complicated as they need to manage the trie nodes as similarly to dynamic arrays. For the right data sets, level compressed trees can be <em>fast</em>. From what I remember, they're the 2nd fastest approach for storing IP routing tables, the fastest is some sort of hash trie.</p>
| 18 | 2009-06-07T02:09:25Z | [
"python",
"algorithm",
"trie"
] |
Trie (Prefix Tree) in Python | 960,963 | <p>I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :)</p>
<p>If anything is unclear I'm very happy to clarify things.</p>
<p>I just implemented a <a href="http://en.wikipedia.org/wiki/Trie">Trie</a> in python. However, one bit seemed to be more complicated than it ought to (as someone who loves simplicity). Perhaps someone has had a similar problem?</p>
<p>My aim was to minimize the number of nodes by storing the largest common prefix of a sub-trie in its root. For example, if we had the words <strong>stackoverflow</strong>, <strong>stackbase</strong> and <strong>stackbased</strong>, then the tree would look something like this:</p>
<pre><code> [s]tack
[o]verflow ______/ \_______ [b]ase
\___ [d]
</code></pre>
<p>Note that one can still think of the edges having one character (the first one of the child node).</p>
<p><em>Find</em>-query is simple to implement.
<em>Insertion</em> is not hard, but somewhat more complex than I want.. :(</p>
<p>My idea was to insert the keys one after the other (starting from an empty trie), by first searching for the to-be-inserted key k (<em>Find</em>(k)), and then rearranging/splitting the nodes locally at the place where the find-procedure stops. There turn out to be 4 cases:
(Let k be the key we want to insert, and k' be the key of the node, where the search ended)</p>
<ol>
<li>k is identical to k'</li>
<li>k is a "proper" prefix of k'</li>
<li>k' is a "proper" prefix of k</li>
<li>k and k' share some common prefix, but none of the cases (1), (2) or (3) occur.</li>
</ol>
<p>It seems that each of the cases are unique and thus imply different modifications of the Trie. BUT: is it really that complex? Am I missing something? Is there a better approach?</p>
<p>Thanks :)</p>
| 16 | 2009-06-07T01:14:07Z | 961,271 | <p>Somewhat of a tangent, but if you are super worried about the number of nodes in your Trie, you may look at joining your word suffixes too. I'd take a look at the DAWG (Directed Acyclic Word Graph) idea: <a href="http://en.wikipedia.org/wiki/Directed_acyclic_word_graph" rel="nofollow">http://en.wikipedia.org/wiki/Directed_acyclic_word_graph</a></p>
<p>The downside of these is that they aren't very dynamic and creating them can be difficult. But, if your dictionary is static, they can be super compact.</p>
| 2 | 2009-06-07T05:33:28Z | [
"python",
"algorithm",
"trie"
] |
Trie (Prefix Tree) in Python | 960,963 | <p>I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :)</p>
<p>If anything is unclear I'm very happy to clarify things.</p>
<p>I just implemented a <a href="http://en.wikipedia.org/wiki/Trie">Trie</a> in python. However, one bit seemed to be more complicated than it ought to (as someone who loves simplicity). Perhaps someone has had a similar problem?</p>
<p>My aim was to minimize the number of nodes by storing the largest common prefix of a sub-trie in its root. For example, if we had the words <strong>stackoverflow</strong>, <strong>stackbase</strong> and <strong>stackbased</strong>, then the tree would look something like this:</p>
<pre><code> [s]tack
[o]verflow ______/ \_______ [b]ase
\___ [d]
</code></pre>
<p>Note that one can still think of the edges having one character (the first one of the child node).</p>
<p><em>Find</em>-query is simple to implement.
<em>Insertion</em> is not hard, but somewhat more complex than I want.. :(</p>
<p>My idea was to insert the keys one after the other (starting from an empty trie), by first searching for the to-be-inserted key k (<em>Find</em>(k)), and then rearranging/splitting the nodes locally at the place where the find-procedure stops. There turn out to be 4 cases:
(Let k be the key we want to insert, and k' be the key of the node, where the search ended)</p>
<ol>
<li>k is identical to k'</li>
<li>k is a "proper" prefix of k'</li>
<li>k' is a "proper" prefix of k</li>
<li>k and k' share some common prefix, but none of the cases (1), (2) or (3) occur.</li>
</ol>
<p>It seems that each of the cases are unique and thus imply different modifications of the Trie. BUT: is it really that complex? Am I missing something? Is there a better approach?</p>
<p>Thanks :)</p>
| 16 | 2009-06-07T01:14:07Z | 961,282 | <p>I have a question regarding your implementation. What is the level of granularity that you decide to split your strings on to make the prefix tree. You could split stack as either s,t,a,c,k or st,ta,ac,ck and many other ngrams of it. Most prefix tree implementations take into account an alphabet for the language, based on this alphabet, you do the splitting. </p>
<p>If you were building a prefix tree implementation for python then your alphabets would be things like def, : , if , else... etc </p>
<p>Choosing the right alphabet makes a huge difference in building efficient prefix trees. As for your answers, you could look for PERL packages on CPAN which do longest common substring computation using trie's. You may have some luck there as most of their implementation is pretty robust. </p>
| 2 | 2009-06-07T05:46:21Z | [
"python",
"algorithm",
"trie"
] |
Trie (Prefix Tree) in Python | 960,963 | <p>I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :)</p>
<p>If anything is unclear I'm very happy to clarify things.</p>
<p>I just implemented a <a href="http://en.wikipedia.org/wiki/Trie">Trie</a> in python. However, one bit seemed to be more complicated than it ought to (as someone who loves simplicity). Perhaps someone has had a similar problem?</p>
<p>My aim was to minimize the number of nodes by storing the largest common prefix of a sub-trie in its root. For example, if we had the words <strong>stackoverflow</strong>, <strong>stackbase</strong> and <strong>stackbased</strong>, then the tree would look something like this:</p>
<pre><code> [s]tack
[o]verflow ______/ \_______ [b]ase
\___ [d]
</code></pre>
<p>Note that one can still think of the edges having one character (the first one of the child node).</p>
<p><em>Find</em>-query is simple to implement.
<em>Insertion</em> is not hard, but somewhat more complex than I want.. :(</p>
<p>My idea was to insert the keys one after the other (starting from an empty trie), by first searching for the to-be-inserted key k (<em>Find</em>(k)), and then rearranging/splitting the nodes locally at the place where the find-procedure stops. There turn out to be 4 cases:
(Let k be the key we want to insert, and k' be the key of the node, where the search ended)</p>
<ol>
<li>k is identical to k'</li>
<li>k is a "proper" prefix of k'</li>
<li>k' is a "proper" prefix of k</li>
<li>k and k' share some common prefix, but none of the cases (1), (2) or (3) occur.</li>
</ol>
<p>It seems that each of the cases are unique and thus imply different modifications of the Trie. BUT: is it really that complex? Am I missing something? Is there a better approach?</p>
<p>Thanks :)</p>
| 16 | 2009-06-07T01:14:07Z | 990,277 | <p>Look at : Judy-arrays and the python interface at <a href="http://www.dalkescientific.com/Python/PyJudy.html" rel="nofollow">http://www.dalkescientific.com/Python/PyJudy.html</a></p>
| 1 | 2009-06-13T08:05:25Z | [
"python",
"algorithm",
"trie"
] |
Python Comet Server | 960,969 | <p>I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very little documentation regarding these options and I cannot find good information online about production scale users of comet on Python.</p>
<p>Has anyone successfully implemented comet on Python in a production system? How did you go about doing it and where can I find resources to implement my own?</p>
| 30 | 2009-06-07T01:18:21Z | 960,973 | <p>I haven't done it, but <a href="http://www.rkblog.rk.edu.pl/w/p/django-and-comet/" rel="nofollow">this guy</a> has and writes a good article about it, with Django examples and pointers (which I haven't checked) to other frameworks.</p>
| 2 | 2009-06-07T01:22:44Z | [
"python",
"cometd",
"python-stackless"
] |
Python Comet Server | 960,969 | <p>I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very little documentation regarding these options and I cannot find good information online about production scale users of comet on Python.</p>
<p>Has anyone successfully implemented comet on Python in a production system? How did you go about doing it and where can I find resources to implement my own?</p>
| 30 | 2009-06-07T01:18:21Z | 961,191 | <p>I've done tons of APIs using twisted for stuff like that, most of which are available on my <a href="http://github.com/dustin" rel="nofollow">github</a> account.</p>
<p>Most are client-side, but <a href="http://github.com/dustin/slosh" rel="nofollow">slosh</a> is a server I wrote to do a realtime cheap pubsub sort of thing. It scales somewhat horizontally for reads by allowing for simple stream replication. Writes are a little different when you stick to plain HTTP, but I've pushed a decent amount through it for a demo.</p>
<p>Otherwise, you have full-on BOSH which most XMPP servers support and will allow you to decouple the message distribution from the web frontend.</p>
| 3 | 2009-06-07T04:18:34Z | [
"python",
"cometd",
"python-stackless"
] |
Python Comet Server | 960,969 | <p>I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very little documentation regarding these options and I cannot find good information online about production scale users of comet on Python.</p>
<p>Has anyone successfully implemented comet on Python in a production system? How did you go about doing it and where can I find resources to implement my own?</p>
| 30 | 2009-06-07T01:18:21Z | 1,216,820 | <p><a href="http://www.orbited.org/">Orbited</a> seems as a nice solution. Haven't tried it though.</p>
<hr>
<p><em><strong>Update</strong>: things have changed in the last 2.5 years.</em></p>
<p>We now have websockets in all major browsers, except IE (naturally) and a couple of very good abstractions over it, that provide many methods of emulating real-time communication.</p>
<ul>
<li><a href="http://socket.io/">socket.io</a> along with <a href="https://github.com/MrJoes/tornadio">tornadio</a> (socket.io 0.6) and <a href="https://github.com/MrJoes/tornadio2">tornadio2</a> (socket.io 0.7+)</li>
<li><a href="https://github.com/sockjs/sockjs-client">sock.js</a> along with <a href="https://github.com/MrJoes/sockjs-tornado">SockJS-tornado</a></li>
</ul>
| 12 | 2009-08-01T15:27:37Z | [
"python",
"cometd",
"python-stackless"
] |
Python Comet Server | 960,969 | <p>I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very little documentation regarding these options and I cannot find good information online about production scale users of comet on Python.</p>
<p>Has anyone successfully implemented comet on Python in a production system? How did you go about doing it and where can I find resources to implement my own?</p>
| 30 | 2009-06-07T01:18:21Z | 1,309,560 | <p>I recommend you use <a href="http://www.stream-hub.com/">StreamHub Comet Server</a> - its used by a lot of people - personally I use it with a couple of Django sites I run. You will need to write a tiny bit of Java to handle the streaming - I did this using <a href="http://www.jython.org/">Jython</a>. The front-end code is some real simple Javascript a la:</p>
<pre><code>StreamHub hub = new StreamHub();
hub.connect("http://myserver.com/");
hub.subscribe("newsfeed", function(sTopic, oData) { alert("new news item: " + oData.Title); });
</code></pre>
<p>The documentation is pretty good - I had similar problems as you trying to get started with the sparse docs of Cometd et al. For a start I'd read <a href="http://streamhub.blogspot.com/2009/07/getting-started-with-streamhub-and.html">Getting Started With Comet and StreamHub</a>, download and see how some of the examples work and reference the API docs if you need to:</p>
<ul>
<li><a href="http://www.stream-hub.com/doc/2.0.3/jsdoc/">Javascript API JSDoc</a> </li>
<li><a href="http://www.stream-hub.com/doc/2.0.3/javadoc/">Streaming from Java Javadoc</a></li>
</ul>
| 8 | 2009-08-21T00:41:01Z | [
"python",
"cometd",
"python-stackless"
] |
Python Comet Server | 960,969 | <p>I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very little documentation regarding these options and I cannot find good information online about production scale users of comet on Python.</p>
<p>Has anyone successfully implemented comet on Python in a production system? How did you go about doing it and where can I find resources to implement my own?</p>
| 30 | 2009-06-07T01:18:21Z | 1,690,327 | <p>Here is a full-featured example of combining Django, Orbited,and Twisted to create a real-time (Comet) app: <a href="http://github.com/clemesha/hotdot">http://github.com/clemesha/hotdot</a> using Python.</p>
| 5 | 2009-11-06T20:49:39Z | [
"python",
"cometd",
"python-stackless"
] |
Python Comet Server | 960,969 | <p>I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very little documentation regarding these options and I cannot find good information online about production scale users of comet on Python.</p>
<p>Has anyone successfully implemented comet on Python in a production system? How did you go about doing it and where can I find resources to implement my own?</p>
| 30 | 2009-06-07T01:18:21Z | 2,303,584 | <p>the orbited and redis solutions are nice, but not longer relevant when you have something like the PubSubHubbub that google released. This makes it very easy to be the publisher or the subscriber to a given feed. <a href="http://code.google.com/p/pubsubhubbub/" rel="nofollow">http://code.google.com/p/pubsubhubbub/</a></p>
| 1 | 2010-02-20T20:21:08Z | [
"python",
"cometd",
"python-stackless"
] |
Python Comet Server | 960,969 | <p>I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very little documentation regarding these options and I cannot find good information online about production scale users of comet on Python.</p>
<p>Has anyone successfully implemented comet on Python in a production system? How did you go about doing it and where can I find resources to implement my own?</p>
| 30 | 2009-06-07T01:18:21Z | 2,612,344 | <p><a href="http://blog.gevent.org/2009/10/10/simpler-long-polling-with-django-and-gevent/" rel="nofollow">Here's an example that does long-polling with gevent and Django</a>.</p>
<p>It uses <a href="http://pypi.python.org/pypi/greenlet" rel="nofollow">greenlet</a> - stack switching functionality from Stackless packaged as a CPython extension.</p>
| 1 | 2010-04-10T05:17:08Z | [
"python",
"cometd",
"python-stackless"
] |
Get class that defined method | 961,048 | <p>How can I get the class that defined a method in Python?</p>
<p>I'd want the following example to print "<code>__main__.FooClass</code>":</p>
<pre><code>class FooClass:
def foo_method(self):
print "foo"
class BarClass(FooClass):
pass
bar = BarClass()
print get_class_that_defined_method(bar.foo_method)
</code></pre>
| 35 | 2009-06-07T02:18:12Z | 961,057 | <pre><code>import inspect
def get_class_that_defined_method(meth):
for cls in inspect.getmro(meth.im_class):
if meth.__name__ in cls.__dict__:
return cls
return None
</code></pre>
| 44 | 2009-06-07T02:23:02Z | [
"python",
"python-2.6",
"python-datamodel"
] |
Get class that defined method | 961,048 | <p>How can I get the class that defined a method in Python?</p>
<p>I'd want the following example to print "<code>__main__.FooClass</code>":</p>
<pre><code>class FooClass:
def foo_method(self):
print "foo"
class BarClass(FooClass):
pass
bar = BarClass()
print get_class_that_defined_method(bar.foo_method)
</code></pre>
| 35 | 2009-06-07T02:18:12Z | 13,628,116 | <p>Thanks Sr2222 for pointing out I was missing the point...</p>
<p>Here's the corrected approach which is just like Alex's but does not require to import anything. I don't think it's an improvement though, unless there's a huge hierarchy of inherited classes as this approach stops as soon as the defining class is found, instead of returning the whole inheritance as <code>getmro</code> does. As said, this is a <strong>very</strong> unlikely scenario.</p>
<pre><code>def get_class_that_defined_method(method):
method_name = method.__name__
if method.__self__:
classes = [method.__self__.__class__]
else:
#unbound method
classes = [method.im_class]
while classes:
c = classes.pop()
if method_name in c.__dict__:
return c
else:
classes = list(c.__bases__) + classes
return None
</code></pre>
<p>And the Example:</p>
<pre><code>>>> class A(object):
... def test(self): pass
>>> class B(A): pass
>>> class C(B): pass
>>> class D(A):
... def test(self): print 1
>>> class E(D,C): pass
>>> get_class_that_defined_method(A().test)
<class '__main__.A'>
>>> get_class_that_defined_method(A.test)
<class '__main__.A'>
>>> get_class_that_defined_method(B.test)
<class '__main__.A'>
>>> get_class_that_defined_method(C.test)
<class '__main__.A'>
>>> get_class_that_defined_method(D.test)
<class '__main__.D'>
>>> get_class_that_defined_method(E().test)
<class '__main__.D'>
>>> get_class_that_defined_method(E.test)
<class '__main__.D'>
>>> E().test()
1
</code></pre>
<p>Alex solution returns the same results. As long as Alex approach can be used, I would use it instead of this one.</p>
| 3 | 2012-11-29T14:38:10Z | [
"python",
"python-2.6",
"python-datamodel"
] |
Get class that defined method | 961,048 | <p>How can I get the class that defined a method in Python?</p>
<p>I'd want the following example to print "<code>__main__.FooClass</code>":</p>
<pre><code>class FooClass:
def foo_method(self):
print "foo"
class BarClass(FooClass):
pass
bar = BarClass()
print get_class_that_defined_method(bar.foo_method)
</code></pre>
| 35 | 2009-06-07T02:18:12Z | 26,391,792 | <p>I started doing something somewhat similar, basically the idea was checking whenever a method in a base class had been implemented or not in a sub class. Turned out the way I originally did it I could not detect when an intermediate class was actually implementing the method.</p>
<p>My workaround for it was quite simple actually; setting a method <strong>attribute</strong> and testing its presence later. Here's an simplification of the whole thing:</p>
<pre><code>class A():
def method(self):
pass
method._orig = None # This attribute will be gone once the method is implemented
def run_method(self, *args, **kwargs):
if hasattr(self.method, '_orig'):
raise Exception('method not implemented')
self.method(*args, **kwargs)
class B(A):
pass
class C(B):
def method(self):
pass
class D(C):
pass
B().run_method() # ==> Raises Exception: method not implemented
C().run_method() # OK
D().run_method() # OK
</code></pre>
<p>UPDATE: Actually call <code>method()</code> from <code>run_method()</code> (isn't that the spirit?) and have it pass all arguments unmodified to the method.</p>
<p>P.S.: This answer does not directly answer the question. IMHO there are two reasons one would want to know which class defined a method; first is to point fingers at a class in debug code (such as in exception handling), and the second is to determine if the method has been re-implemented (where method is a stub meant to be implemented by the programmer). This answer solves that second case in a different way.</p>
| 1 | 2014-10-15T20:44:40Z | [
"python",
"python-2.6",
"python-datamodel"
] |
Reloading module giving NameError: name 'reload' is not defined | 961,162 | <p>I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the <code>import</code> command again won't do anything. </p>
<p>Executing <code>reload(foo)</code> is giving this error:</p>
<pre><code>Traceback (most recent call last):
File "(stdin)", line 1, in (module)
...
NameError: name 'reload' is not defined
</code></pre>
<p>What does the error mean?</p>
| 68 | 2009-06-07T03:55:15Z | 961,165 | <p>You deleted your __builtins__ variable. </p>
<p>How to fix this? Don't delete __builtins__.</p>
<blockquote>
<p>Also can someone explain step by step what that error message means?</p>
</blockquote>
<p>It means python can't find the function "reload".</p>
<blockquote>
<p>reload (script4.py)</p>
</blockquote>
<p>This is incorrect. if you did "import script4", then you must do "reload(script4)"</p>
| -9 | 2009-06-07T04:00:16Z | [
"python",
"python-3.x"
] |
Reloading module giving NameError: name 'reload' is not defined | 961,162 | <p>I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the <code>import</code> command again won't do anything. </p>
<p>Executing <code>reload(foo)</code> is giving this error:</p>
<pre><code>Traceback (most recent call last):
File "(stdin)", line 1, in (module)
...
NameError: name 'reload' is not defined
</code></pre>
<p>What does the error mean?</p>
| 68 | 2009-06-07T03:55:15Z | 961,219 | <p><a href="https://docs.python.org/2/library/functions.html#reload"><code>reload</code></a> is a builtin in Python 2, but not in Python 3, so the error you're seeing is expected.</p>
<p>If you truly must reload a module in Python 3, you should use either:</p>
<ul>
<li><a href="https://docs.python.org/3/library/importlib.html#importlib.reload"><code>importlib.reload</code></a> for Python 3.4 and above</li>
<li><a href="https://docs.python.org/3/library/imp.html#imp.reload"><code>imp.reload</code></a> for Python 3.0 to 3.3 (deprecated since Python 3.4 in favour of <a href="https://docs.python.org/3/library/importlib.html"><code>importlib</code></a>) </li>
</ul>
| 98 | 2009-06-07T04:41:25Z | [
"python",
"python-3.x"
] |
Reloading module giving NameError: name 'reload' is not defined | 961,162 | <p>I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the <code>import</code> command again won't do anything. </p>
<p>Executing <code>reload(foo)</code> is giving this error:</p>
<pre><code>Traceback (most recent call last):
File "(stdin)", line 1, in (module)
...
NameError: name 'reload' is not defined
</code></pre>
<p>What does the error mean?</p>
| 68 | 2009-06-07T03:55:15Z | 8,691,152 | <pre><code>import imp
imp.reload(script4)
</code></pre>
| 47 | 2012-01-01T00:02:09Z | [
"python",
"python-3.x"
] |
Reloading module giving NameError: name 'reload' is not defined | 961,162 | <p>I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the <code>import</code> command again won't do anything. </p>
<p>Executing <code>reload(foo)</code> is giving this error:</p>
<pre><code>Traceback (most recent call last):
File "(stdin)", line 1, in (module)
...
NameError: name 'reload' is not defined
</code></pre>
<p>What does the error mean?</p>
| 68 | 2009-06-07T03:55:15Z | 33,409,066 | <p><strong><em>For >= Python3.4:</em></strong></p>
<pre><code>import importlib
importlib.reload(module)
</code></pre>
<p><strong><em>For <= Python3.3:</em></strong></p>
<pre><code>import imp
imp.reload(module)
</code></pre>
<p><strong><em>For Python2.x:</em></strong></p>
<p>Use the in-built <code>reload()</code> function.</p>
<pre><code>reload(module)
</code></pre>
| 25 | 2015-10-29T08:19:33Z | [
"python",
"python-3.x"
] |
Reloading module giving NameError: name 'reload' is not defined | 961,162 | <p>I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the <code>import</code> command again won't do anything. </p>
<p>Executing <code>reload(foo)</code> is giving this error:</p>
<pre><code>Traceback (most recent call last):
File "(stdin)", line 1, in (module)
...
NameError: name 'reload' is not defined
</code></pre>
<p>What does the error mean?</p>
| 68 | 2009-06-07T03:55:15Z | 40,119,302 | <p>To expand on the previously written answers, if you want a single solution which will work across Python versions 2 and 3, you can use the following:</p>
<pre><code>try:
reload # Python 2.7
except NameError:
try:
from importlib import reload # Python 3.4+
except ImportError:
from imp import reload # Python 3.0 - 3.3
</code></pre>
| 0 | 2016-10-18T22:44:41Z | [
"python",
"python-3.x"
] |
Two values from one input in python? | 961,263 | <p>This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python? </p>
<p>For instance, in C I can do something like this: <code>scanf("%d %d", &var1, &var2)</code>. However, I can't figure out what the Python equivalent of that is. I figured it would just be something like <code>var1, var2 = input("Enter two numbers here: ")</code>, but that doesn't work and I'm not complaining because it wouldn't make a whole lot of sense if it did. </p>
<p>Does anyone out there know a good way to do this elegantly and concisely? </p>
| 15 | 2009-06-07T05:27:53Z | 961,276 | <p>You can't really do it the C way (I think) but a pythonic way of doing this would be (if your 'inputs' have spaces in between them):</p>
<pre><code>raw_answer = raw_input()
answers = raw_answer.split(' ') # list of 'answers'
</code></pre>
<p>So you could rewrite your try to:</p>
<pre><code>var1, var2 = raw_input("enter two numbers:").split(' ')
</code></pre>
<p>Note that this it somewhat less flexible than using the 'first' solution (for example if you add a space at the end this will already break).</p>
<p>Also be aware that var1 and var2 will still be strings with this method when not cast to int.</p>
| 4 | 2009-06-07T05:39:01Z | [
"python",
"variables",
"input"
] |
Two values from one input in python? | 961,263 | <p>This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python? </p>
<p>For instance, in C I can do something like this: <code>scanf("%d %d", &var1, &var2)</code>. However, I can't figure out what the Python equivalent of that is. I figured it would just be something like <code>var1, var2 = input("Enter two numbers here: ")</code>, but that doesn't work and I'm not complaining because it wouldn't make a whole lot of sense if it did. </p>
<p>Does anyone out there know a good way to do this elegantly and concisely? </p>
| 15 | 2009-06-07T05:27:53Z | 961,300 | <p>The Python way to map</p>
<pre><code>printf("Enter two numbers here: ");
scanf("%d %d", &var1, &var2)
</code></pre>
<p>would be </p>
<pre><code>var1, var2 = raw_input("Enter two numbers here: ").split()
</code></pre>
<p>Note that we don't have to explicitly specify <code>split(' ')</code> because <code>split()</code> uses any whitespace characters as delimiter as default. That means if we simply called <code>split()</code> then the user could have separated the numbers using tabs, if he really wanted, and also spaces.,</p>
<p>Python has dynamic typing so there is no need to specify <code>%d</code>. However, if you ran the above then <code>var1</code> and <code>var2</code> would be both Strings. You can convert them to <code>int</code> using another line</p>
<pre><code>var1, var2 = [int(var1), int(var2)]
</code></pre>
<p>Or you could use <em>list comprehension</em></p>
<pre><code>var1, var2 = [int(x) for x in [var1, var2]]
</code></pre>
<p>To sum it up, you could have done the whole thing with this one-liner:</p>
<pre><code>var1, var2 = [int(x) for x in raw_input("Enter two numbers here: ").split()]
</code></pre>
| 28 | 2009-06-07T05:59:45Z | [
"python",
"variables",
"input"
] |
Two values from one input in python? | 961,263 | <p>This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python? </p>
<p>For instance, in C I can do something like this: <code>scanf("%d %d", &var1, &var2)</code>. However, I can't figure out what the Python equivalent of that is. I figured it would just be something like <code>var1, var2 = input("Enter two numbers here: ")</code>, but that doesn't work and I'm not complaining because it wouldn't make a whole lot of sense if it did. </p>
<p>Does anyone out there know a good way to do this elegantly and concisely? </p>
| 15 | 2009-06-07T05:27:53Z | 961,322 | <p>In <code>Python 2.*</code>, <code>input</code> lets the user enter any expression, e.g. a tuple:</p>
<pre><code>>>> a, b = input('Two numbers please (with a comma in between): ')
Two numbers please (with a comma in between): 23, 45
>>> print a, b
23 45
</code></pre>
<p>In <code>Python 3.*</code>, <code>input</code> is like <code>2.*</code>'s <code>raw_input</code>, returning you a string that's just what the user typed (rather than <code>eval</code>ing it as <code>2.*</code> used to do on <code>input</code>), so you'll have to <code>.split</code>, and/or <code>eval</code>, &c but you'll also be MUCH more in control of the whole thing.</p>
| 8 | 2009-06-07T06:19:06Z | [
"python",
"variables",
"input"
] |
Two values from one input in python? | 961,263 | <p>This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python? </p>
<p>For instance, in C I can do something like this: <code>scanf("%d %d", &var1, &var2)</code>. However, I can't figure out what the Python equivalent of that is. I figured it would just be something like <code>var1, var2 = input("Enter two numbers here: ")</code>, but that doesn't work and I'm not complaining because it wouldn't make a whole lot of sense if it did. </p>
<p>Does anyone out there know a good way to do this elegantly and concisely? </p>
| 15 | 2009-06-07T05:27:53Z | 961,329 | <p>All input will be through a string. It's up to you to process that string after you've received it. Unless that is, you use the eval(input()) method, but that isn't recommended for most situations anyway.</p>
<pre><code>input_string = raw_input("Enter 2 numbers here: ")
a, b = split_string_into_numbers(input_string)
do_stuff(a, b)
</code></pre>
| 2 | 2009-06-07T06:26:38Z | [
"python",
"variables",
"input"
] |
Two values from one input in python? | 961,263 | <p>This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python? </p>
<p>For instance, in C I can do something like this: <code>scanf("%d %d", &var1, &var2)</code>. However, I can't figure out what the Python equivalent of that is. I figured it would just be something like <code>var1, var2 = input("Enter two numbers here: ")</code>, but that doesn't work and I'm not complaining because it wouldn't make a whole lot of sense if it did. </p>
<p>Does anyone out there know a good way to do this elegantly and concisely? </p>
| 15 | 2009-06-07T05:27:53Z | 21,816,747 | <p>Check this handy function:</p>
<pre><code>def gets(*types):
return tuple([types[i](val) for i, val in enumerate(raw_input().split(' '))])
# usage:
a, b, c = gets(int, float, str)
</code></pre>
| 1 | 2014-02-16T21:15:48Z | [
"python",
"variables",
"input"
] |
Two values from one input in python? | 961,263 | <p>This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python? </p>
<p>For instance, in C I can do something like this: <code>scanf("%d %d", &var1, &var2)</code>. However, I can't figure out what the Python equivalent of that is. I figured it would just be something like <code>var1, var2 = input("Enter two numbers here: ")</code>, but that doesn't work and I'm not complaining because it wouldn't make a whole lot of sense if it did. </p>
<p>Does anyone out there know a good way to do this elegantly and concisely? </p>
| 15 | 2009-06-07T05:27:53Z | 30,421,198 | <p>If you need to take two integers say a,b in python you can use map function.<br>
Suppose input is,</p>
<pre>
1
5 3
1 2 3 4 5
</pre>
<p>where 1 represent test case, 5 represent number of values and 3 represents a task value and in next line given 5 values, we can take such input using this method in PYTH 2.x Version.</p>
<pre><code>testCases=int(raw_input())
number, taskValue = map(int, raw_input().split())
array = map(int, raw_input().split())
</code></pre>
<p>You can replace 'int' in map() with another datatype needed.</p>
| 1 | 2015-05-24T07:42:18Z | [
"python",
"variables",
"input"
] |
how to multiply two different array of integers in python? | 961,326 | <p>i have taken input in two different lists by splitting a line having integers 1 2</p>
<p>for eg
1 2</p>
<p>3 4</p>
<p>so now i have split it and kept it in lists , and want to multiply them like 1*3 +2*4, but when i try to do it , its giving me that it can only multiply integers and not lists !!
help here</p>
<p>can't multiply sequence by non-int of type 'list'.. that's the error i am getting â
when i do </p>
<pre><code>c=sum(i*j for i, j in zip(a,b))
</code></pre>
<p>...</p>
<pre><code>t=raw_input()
d =[]
for j in range(0,int(t)):
c=0
n=raw_input()
s = raw_input()
s1=raw_input()
a=[]
b=[]
a.append( [int(i) for i in s.split(' ')])
b.append([int(i) for i in s.split(' ')])
d.append(sum(i*j for i, j in zip(a,b)))
for i in d:
print i
</code></pre>
<p>that's my code</p>
| 2 | 2009-06-07T06:20:45Z | 961,327 | <p>You need:</p>
<pre><code>>>> a = [1,2]
>>> b = [3,4]
>>> sum(i*j for i, j in zip(a,b))
11
</code></pre>
| 7 | 2009-06-07T06:22:43Z | [
"python"
] |
how to multiply two different array of integers in python? | 961,326 | <p>i have taken input in two different lists by splitting a line having integers 1 2</p>
<p>for eg
1 2</p>
<p>3 4</p>
<p>so now i have split it and kept it in lists , and want to multiply them like 1*3 +2*4, but when i try to do it , its giving me that it can only multiply integers and not lists !!
help here</p>
<p>can't multiply sequence by non-int of type 'list'.. that's the error i am getting â
when i do </p>
<pre><code>c=sum(i*j for i, j in zip(a,b))
</code></pre>
<p>...</p>
<pre><code>t=raw_input()
d =[]
for j in range(0,int(t)):
c=0
n=raw_input()
s = raw_input()
s1=raw_input()
a=[]
b=[]
a.append( [int(i) for i in s.split(' ')])
b.append([int(i) for i in s.split(' ')])
d.append(sum(i*j for i, j in zip(a,b)))
for i in d:
print i
</code></pre>
<p>that's my code</p>
| 2 | 2009-06-07T06:20:45Z | 961,391 | <p>You can do it in a pythonic way using sum, map and a lambda expression. </p>
<pre><code>>>> a = [1,2]
>>> b = [3,4]
>>> prod = lambda a, b: a*b
>>> sum(map(prod, a, b))
11
</code></pre>
<p>the <code>lambda a, b: a*b</code> bit also has a special name in python, <code>operator.mul</code></p>
<pre><code>>>> import operator
>>> sum(map(operator.mul, a, b))
11
</code></pre>
| 2 | 2009-06-07T07:18:54Z | [
"python"
] |
how to multiply two different array of integers in python? | 961,326 | <p>i have taken input in two different lists by splitting a line having integers 1 2</p>
<p>for eg
1 2</p>
<p>3 4</p>
<p>so now i have split it and kept it in lists , and want to multiply them like 1*3 +2*4, but when i try to do it , its giving me that it can only multiply integers and not lists !!
help here</p>
<p>can't multiply sequence by non-int of type 'list'.. that's the error i am getting â
when i do </p>
<pre><code>c=sum(i*j for i, j in zip(a,b))
</code></pre>
<p>...</p>
<pre><code>t=raw_input()
d =[]
for j in range(0,int(t)):
c=0
n=raw_input()
s = raw_input()
s1=raw_input()
a=[]
b=[]
a.append( [int(i) for i in s.split(' ')])
b.append([int(i) for i in s.split(' ')])
d.append(sum(i*j for i, j in zip(a,b)))
for i in d:
print i
</code></pre>
<p>that's my code</p>
| 2 | 2009-06-07T06:20:45Z | 961,413 | <p>It has nothing to do with multiplying integers, but you should probably be using the <code>extend</code> method:</p>
<pre><code> a.extend([int(i) for i in s.split(' ')])
b.extend([int(i) for i in s.split(' ')])
</code></pre>
<p><code>append</code> just tacks its argument on to the list as its last element. Since you are passing a list to <code>append</code>, you wind up with a list of lists. <code>extend</code>, however, takes the elements of the argument list and adds them to the end of the "source" list, which is what it seems like you mean to do.</p>
<p>(There are a bunch of other things you could do to fix up this code but that's probably a matter for a different question)</p>
| 0 | 2009-06-07T07:32:01Z | [
"python"
] |
how to multiply two different array of integers in python? | 961,326 | <p>i have taken input in two different lists by splitting a line having integers 1 2</p>
<p>for eg
1 2</p>
<p>3 4</p>
<p>so now i have split it and kept it in lists , and want to multiply them like 1*3 +2*4, but when i try to do it , its giving me that it can only multiply integers and not lists !!
help here</p>
<p>can't multiply sequence by non-int of type 'list'.. that's the error i am getting â
when i do </p>
<pre><code>c=sum(i*j for i, j in zip(a,b))
</code></pre>
<p>...</p>
<pre><code>t=raw_input()
d =[]
for j in range(0,int(t)):
c=0
n=raw_input()
s = raw_input()
s1=raw_input()
a=[]
b=[]
a.append( [int(i) for i in s.split(' ')])
b.append([int(i) for i in s.split(' ')])
d.append(sum(i*j for i, j in zip(a,b)))
for i in d:
print i
</code></pre>
<p>that's my code</p>
| 2 | 2009-06-07T06:20:45Z | 961,424 | <p>Is this what you want?</p>
<pre><code>t=raw_input()
d =[]
for j in range(0,int(t)):
#c=0
#n=raw_input()
s = raw_input()
s1 =raw_input()
a = [int(i) for i in s.split(' ')]
b = [int(i) for i in s1.split(' ')] # <--s1 not s
d.append(sum(i*j for i, j in zip(a,b)))
for i in d:
print i
</code></pre>
| 1 | 2009-06-07T07:38:44Z | [
"python"
] |
What does the percentage sign mean in Python 3.1 | 961,344 | <p>In the tutorial there is an example for finding prime numbers.</p>
<pre><code>>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
</code></pre>
<p>I understand that the double == is a test for equality, but I don't understand the "if n % x" part. Like I can verbally walk through each part and say what the statement does for the example. But I don't understand how the percentage sign falls in. What does "if n % x" actually say?</p>
| 24 | 2009-06-07T06:47:03Z | 961,349 | <p>In python 2.6 the '%' operator performed a modulus. I don't think they changed it in 3.0.1</p>
<p>The modulo operator tells you the remainder of a division of two numbers. </p>
| 1 | 2009-06-07T06:49:41Z | [
"python"
] |
What does the percentage sign mean in Python 3.1 | 961,344 | <p>In the tutorial there is an example for finding prime numbers.</p>
<pre><code>>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
</code></pre>
<p>I understand that the double == is a test for equality, but I don't understand the "if n % x" part. Like I can verbally walk through each part and say what the statement does for the example. But I don't understand how the percentage sign falls in. What does "if n % x" actually say?</p>
| 24 | 2009-06-07T06:47:03Z | 961,351 | <p>Modulus operator; gives the remainder of the left value divided by the right value. Like:</p>
<p><code>3 % 1</code> would equal zero (since 3 divides evenly by 1)</p>
<p><code>3 % 2</code> would equal 1 (since dividing 3 by 2 results in a remainder of 1).</p>
| 32 | 2009-06-07T06:50:49Z | [
"python"
] |
What does the percentage sign mean in Python 3.1 | 961,344 | <p>In the tutorial there is an example for finding prime numbers.</p>
<pre><code>>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
</code></pre>
<p>I understand that the double == is a test for equality, but I don't understand the "if n % x" part. Like I can verbally walk through each part and say what the statement does for the example. But I don't understand how the percentage sign falls in. What does "if n % x" actually say?</p>
| 24 | 2009-06-07T06:47:03Z | 961,352 | <p>It checks if the modulo of the division. For example, in the case you are iterating over all numbers from 2 to n and checking if n is divisible by any of the numbers in between. Simply put, you are checking if a given number n is prime. (Hint: You could check up to n/2).</p>
| 1 | 2009-06-07T06:50:55Z | [
"python"
] |
What does the percentage sign mean in Python 3.1 | 961,344 | <p>In the tutorial there is an example for finding prime numbers.</p>
<pre><code>>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
</code></pre>
<p>I understand that the double == is a test for equality, but I don't understand the "if n % x" part. Like I can verbally walk through each part and say what the statement does for the example. But I don't understand how the percentage sign falls in. What does "if n % x" actually say?</p>
| 24 | 2009-06-07T06:47:03Z | 961,365 | <p>The % does two things, depending on its arguments. In this case, it acts as the modulo operator, meaning when its arguments are numbers, it divides the first by the second and returns the <em>remainder</em>. <code>34 % 10 == 4</code> since 34 divided by 10 is three, with a remainder of four. </p>
<p>If the first argument is a string, it formats it using the second argument. This is a bit involved, so I will refer to the <a href="http://docs.python.org/3.3/library/stdtypes.html#printf-style-string-formatting">documentation</a>, but just as an example: </p>
<pre><code>>>> "foo %d bar"%5
'foo 5 bar'
</code></pre>
<p>However, the string formatting behavior is supplemented as of <a href="http://docs.python.org/3.0/whatsnew/2.6.html#pep-3101-advanced-string-formatting">Python 3.1</a> in favor of the <em>string</em><code>.format()</code> mechanism:</p>
<blockquote>
<p>The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer <a href="http://docs.python.org/3.3/library/string.html#format-string-syntax"><code>str.format()</code></a> interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.</p>
</blockquote>
<p>And thankfully, almost all of the new features are also available from python 2.6 onwards.</p>
| 64 | 2009-06-07T06:58:52Z | [
"python"
] |
What does the percentage sign mean in Python 3.1 | 961,344 | <p>In the tutorial there is an example for finding prime numbers.</p>
<pre><code>>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
</code></pre>
<p>I understand that the double == is a test for equality, but I don't understand the "if n % x" part. Like I can verbally walk through each part and say what the statement does for the example. But I don't understand how the percentage sign falls in. What does "if n % x" actually say?</p>
| 24 | 2009-06-07T06:47:03Z | 8,027,142 | <p>The modulus operator. The remainder when you divide two number.</p>
<p>For Example:</p>
<pre><code>>>> 5 % 2 = 1 # remainder of 5 divided by 2 is 1
>>> 7 % 3 = 1 # remainer of 7 divided by 3 is 1
>>> 3 % 1 = 0 # because 1 divides evenly into 3
</code></pre>
| 1 | 2011-11-06T13:03:08Z | [
"python"
] |
Identical Error Codes | 961,465 | <p>I use python 2.4.1 on Linux, and a python package written inside the company I work in, for establishing a connection between 2 hosts for test purposes.</p>
<p>Upon establishing the connection the side defined as the client side failed when calling <code>socket.connect</code> with the correct parameters (I checked) with the error code 111. After searching the web for this error means, I learned that it means that the connection was actively refused.</p>
<p>But the code in the package for establishing the connection is supposed to deal with it, only it knows 10061 as the error code for this same error: The connection is refused.</p>
<p>Could it be that there are identical error codes for the same logical errors? Could it be that 111 is a system error of the Linux OS, as 10061 is python's or even another OS? Even so, isn't the entire concept of error codes to unify the logical errors with the same codes?</p>
<p>Should I simply add the 111 error code to the handling condition?</p>
| 2 | 2009-06-07T08:08:26Z | 961,484 | <p>It appears Python is exposing the error code from the OS - the interpretation of the code is OS-dependent.</p>
<p>111 is <code>ECONNREFUSED</code> on many Linux systems, and on Cygwin.</p>
<p>146 is <code>ECONNREFUSED</code> on Solaris.</p>
<p>10061 is <code>WSAECONNREFUSED</code> in winerror.h - it's the Windows Socket API's version of <code>ECONNREFUSED</code>.</p>
<p>No doubt on other systems, it's different again.</p>
<p>The correct way to handle this is use symbolic comparisons based on the OS's definition of <code>ECONNREFUSED</code>; that's the way you do it in C, for example. In other words, have a constant called ECONNREFUSED that has the value of ECONNREFUSED for that platform, in a platform-specific library (which will be necessary to link to the OS's socket primitives in any case), and compare error codes with the ECONNREFUSED constant, rather than magic numbers.</p>
<p>I don't know what Python's standard approach to OS error codes is. I suspect it's not terribly well thought out.</p>
| 6 | 2009-06-07T08:19:49Z | [
"python",
"error-handling",
"sockets"
] |
How to find out a^b of very large numbers in python? | 961,533 | <p>I am trying to find out <code>a^b</code> in python, of really large no.s </p>
<p>My code is this:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
c.extend(pow(a,b))
for j in c:
print j
</code></pre>
<p>And I am getting an error like this:</p>
<pre><code>raceback (most recent call last):
File "C:/Python26/lastdig.py", line 7, in <module>
c.extend(pow(a,b))
TypeError: 'int' object is not iterable
</code></pre>
<p>Whats wrong in my prob and is it an efficent way to find out powers of large numbers?</p>
| 0 | 2009-06-07T08:50:01Z | 961,633 | <p>You should try <a href="http://gmpy.sourceforge.net/" rel="nofollow">GMPY</a>. Try something like:</p>
<pre><code>import gmpy
a = gmpy.mpz(10**10)
b = a**10000000
</code></pre>
<p>I don't know how much "big" your numbers are, this solution isn't that fast (but the result is big enough :P )</p>
| 1 | 2009-06-07T10:23:21Z | [
"python"
] |
How to find out a^b of very large numbers in python? | 961,533 | <p>I am trying to find out <code>a^b</code> in python, of really large no.s </p>
<p>My code is this:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
c.extend(pow(a,b))
for j in c:
print j
</code></pre>
<p>And I am getting an error like this:</p>
<pre><code>raceback (most recent call last):
File "C:/Python26/lastdig.py", line 7, in <module>
c.extend(pow(a,b))
TypeError: 'int' object is not iterable
</code></pre>
<p>Whats wrong in my prob and is it an efficent way to find out powers of large numbers?</p>
| 0 | 2009-06-07T08:50:01Z | 961,655 | <p>Another way you might want to try calculating exponents is by using logarithm laws.</p>
<p>x^y = e^(y ln x)</p>
<p>I can't say for certain but this might reduce the number of operations required to calculate large exponents.</p>
| -1 | 2009-06-07T10:31:32Z | [
"python"
] |
How to find out a^b of very large numbers in python? | 961,533 | <p>I am trying to find out <code>a^b</code> in python, of really large no.s </p>
<p>My code is this:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
c.extend(pow(a,b))
for j in c:
print j
</code></pre>
<p>And I am getting an error like this:</p>
<pre><code>raceback (most recent call last):
File "C:/Python26/lastdig.py", line 7, in <module>
c.extend(pow(a,b))
TypeError: 'int' object is not iterable
</code></pre>
<p>Whats wrong in my prob and is it an efficent way to find out powers of large numbers?</p>
| 0 | 2009-06-07T08:50:01Z | 961,681 | <p>python integer ops are arbitrary precision
If you want arbitrary precision floating point ops import Decimal</p>
<pre><code>from decimal import *
d=Decimal('2.0')
print d**1234
</code></pre>
| 1 | 2009-06-07T10:43:00Z | [
"python"
] |
How to find out a^b of very large numbers in python? | 961,533 | <p>I am trying to find out <code>a^b</code> in python, of really large no.s </p>
<p>My code is this:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
c.extend(pow(a,b))
for j in c:
print j
</code></pre>
<p>And I am getting an error like this:</p>
<pre><code>raceback (most recent call last):
File "C:/Python26/lastdig.py", line 7, in <module>
c.extend(pow(a,b))
TypeError: 'int' object is not iterable
</code></pre>
<p>Whats wrong in my prob and is it an efficent way to find out powers of large numbers?</p>
| 0 | 2009-06-07T08:50:01Z | 961,696 | <p>10000**10000 prints in my machine in under a second.</p>
<p>How large is your input.</p>
<p>Your problem is not related to power function.</p>
<p>Use </p>
<pre><code>c.append()
</code></pre>
<p>instead of</p>
<pre><code>c.extend()
</code></pre>
<p>c.extend takes an iterable (a list/tuple/set/custom iterables) as an input.</p>
| 2 | 2009-06-07T10:52:47Z | [
"python"
] |
How to find out a^b of very large numbers in python? | 961,533 | <p>I am trying to find out <code>a^b</code> in python, of really large no.s </p>
<p>My code is this:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
c.extend(pow(a,b))
for j in c:
print j
</code></pre>
<p>And I am getting an error like this:</p>
<pre><code>raceback (most recent call last):
File "C:/Python26/lastdig.py", line 7, in <module>
c.extend(pow(a,b))
TypeError: 'int' object is not iterable
</code></pre>
<p>Whats wrong in my prob and is it an efficent way to find out powers of large numbers?</p>
| 0 | 2009-06-07T08:50:01Z | 961,785 | <p>You are using extend wrong. A.extend( B ), requires that B is some iterable object( ie a list, tuple ). You really want to use append instead.</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a,b= (int(i) for i in n.split(' '))
c.append( pow(a,b) ) ## or you could extend c.extend( [ pow(a,b) ] ), but thats silly.
for j in c:
print j
</code></pre>
| 3 | 2009-06-07T12:11:54Z | [
"python"
] |
How to find out a^b of very large numbers in python? | 961,533 | <p>I am trying to find out <code>a^b</code> in python, of really large no.s </p>
<p>My code is this:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
c.extend(pow(a,b))
for j in c:
print j
</code></pre>
<p>And I am getting an error like this:</p>
<pre><code>raceback (most recent call last):
File "C:/Python26/lastdig.py", line 7, in <module>
c.extend(pow(a,b))
TypeError: 'int' object is not iterable
</code></pre>
<p>Whats wrong in my prob and is it an efficent way to find out powers of large numbers?</p>
| 0 | 2009-06-07T08:50:01Z | 6,312,357 | <p><code>x**y</code> works greatly for exponents. If you want a more original solution, you can use:</p>
<pre><code>def exp(base, exponent):
round(exponent, 0)
if exponent < 0:
return 1.0 / exp(base, -1 * exponent)
if exponent == 0:
return 1
if exponent > 0:
return base * exp(base, exponent - 1)`
</code></pre>
<p>Sadly, this only works exactly for integer exponents.</p>
| 1 | 2011-06-10T21:41:12Z | [
"python"
] |
Converting integer to string in Python? | 961,632 | <p>I want to convert an integer to a string in Python. I am typecasting it in vain:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
d=pow(a,b)
d.str()
c.append(d[0])
for j in c:
print j
</code></pre>
<p>When I try to convert it to string, it's showing an error like <code>int</code> doesn't have any attribute called <code>str</code>.</p>
| 649 | 2009-06-07T10:22:38Z | 961,636 | <p>Try this:</p>
<pre><code>str(i)
</code></pre>
| 48 | 2009-06-07T10:23:58Z | [
"python"
] |
Converting integer to string in Python? | 961,632 | <p>I want to convert an integer to a string in Python. I am typecasting it in vain:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
d=pow(a,b)
d.str()
c.append(d[0])
for j in c:
print j
</code></pre>
<p>When I try to convert it to string, it's showing an error like <code>int</code> doesn't have any attribute called <code>str</code>.</p>
| 649 | 2009-06-07T10:22:38Z | 961,638 | <pre><code>>>> str(10)
'10'
>>> int('10')
10
</code></pre>
<p>[Edit]</p>
<p>Links to the documentation:<br>
<a href="https://docs.python.org/2/library/functions.html#int"><code>int()</code></a><br>
<a href="https://docs.python.org/2/library/functions.html#str"><code>str()</code></a></p>
<p>[Edit]</p>
<p>The problem seems to come from this line: <code>d.str()</code><br>
Conversion to string is done with the builtin <code>str()</code> function, which basically calls the <code>__str__()</code> method of its parameter.</p>
<p>Also, it shouldn't be necessary to call <code>pow()</code>. Try using the <code>**</code> operator.</p>
| 1,037 | 2009-06-07T10:24:15Z | [
"python"
] |
Converting integer to string in Python? | 961,632 | <p>I want to convert an integer to a string in Python. I am typecasting it in vain:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
d=pow(a,b)
d.str()
c.append(d[0])
for j in c:
print j
</code></pre>
<p>When I try to convert it to string, it's showing an error like <code>int</code> doesn't have any attribute called <code>str</code>.</p>
| 649 | 2009-06-07T10:22:38Z | 961,641 | <pre><code>>>> i = 5
>>> s = str(5)
>>> print "Hello, world the number is " + s
Hello, world the number is 5
</code></pre>
| 10 | 2009-06-07T10:24:40Z | [
"python"
] |
Converting integer to string in Python? | 961,632 | <p>I want to convert an integer to a string in Python. I am typecasting it in vain:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
d=pow(a,b)
d.str()
c.append(d[0])
for j in c:
print j
</code></pre>
<p>When I try to convert it to string, it's showing an error like <code>int</code> doesn't have any attribute called <code>str</code>.</p>
| 649 | 2009-06-07T10:22:38Z | 961,652 | <p>There is not typecast and no type coercion in Python. You have to convert your variable in a explicit way.</p>
<p>To convert an object in string you use the <code>str()</code> function. It works with any object that has a method called <code>__str__()</code> defined. In fact</p>
<pre><code>str(a)
</code></pre>
<p>is equivalent to</p>
<pre><code>a.__str__()
</code></pre>
<p>The same is if you want to convert something to int, float etc.</p>
| 28 | 2009-06-07T10:30:48Z | [
"python"
] |
Converting integer to string in Python? | 961,632 | <p>I want to convert an integer to a string in Python. I am typecasting it in vain:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
d=pow(a,b)
d.str()
c.append(d[0])
for j in c:
print j
</code></pre>
<p>When I try to convert it to string, it's showing an error like <code>int</code> doesn't have any attribute called <code>str</code>.</p>
| 649 | 2009-06-07T10:22:38Z | 961,661 | <p>To manage non-integer inputs:</p>
<pre><code>number = raw_input()
try:
value = int(number)
except ValueError:
value = 0
</code></pre>
<hr>
<p>Ok, if I take your latest code and rewrite a bit to get it working with Python:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
d=pow(a,b)
d2=str(d)
c.append(d2[0])
for j in c:
print j
</code></pre>
<p>It gives me something like:</p>
<pre><code>>>> 2
>>> 8 2
>>> 2 3
6
8
</code></pre>
<p>Which is the first characters of the string result <code>pow(a,b)</code>.
What are we trying to do here?</p>
| 12 | 2009-06-07T10:32:28Z | [
"python"
] |
Converting integer to string in Python? | 961,632 | <p>I want to convert an integer to a string in Python. I am typecasting it in vain:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
d=pow(a,b)
d.str()
c.append(d[0])
for j in c:
print j
</code></pre>
<p>When I try to convert it to string, it's showing an error like <code>int</code> doesn't have any attribute called <code>str</code>.</p>
| 649 | 2009-06-07T10:22:38Z | 14,801,285 | <pre><code>a=2
</code></pre>
<p>you can use <code>str(a)</code>
which gives you a string object of <code>int(2)</code></p>
| 18 | 2013-02-10T18:47:04Z | [
"python"
] |
Converting integer to string in Python? | 961,632 | <p>I want to convert an integer to a string in Python. I am typecasting it in vain:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
d=pow(a,b)
d.str()
c.append(d[0])
for j in c:
print j
</code></pre>
<p>When I try to convert it to string, it's showing an error like <code>int</code> doesn't have any attribute called <code>str</code>.</p>
| 649 | 2009-06-07T10:22:38Z | 30,063,942 | <p>The most decent way in my opinion is ``.</p>
<pre><code>i = 32 --> `i` == '32'
</code></pre>
| 1 | 2015-05-05T21:55:46Z | [
"python"
] |
Converting integer to string in Python? | 961,632 | <p>I want to convert an integer to a string in Python. I am typecasting it in vain:</p>
<pre><code>t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
d=pow(a,b)
d.str()
c.append(d[0])
for j in c:
print j
</code></pre>
<p>When I try to convert it to string, it's showing an error like <code>int</code> doesn't have any attribute called <code>str</code>.</p>
| 649 | 2009-06-07T10:22:38Z | 40,102,958 | <p><strong>By using str()</strong> </p>
<pre><code>integer_value=100
str(integer_value)
</code></pre>
<p><strong>By creating String</strong></p>
<pre><code>integer_value = 100
s = "%d" % integer_value
print s
</code></pre>
| 0 | 2016-10-18T08:13:22Z | [
"python"
] |
pygtk: How to set the height of pop-up window in gtk.EntryCompletion | 961,735 | <p>I use gtk.EntryCompletion to implement the autocomletion function.
But the list is so long that the pop-up window touches the bottom of screen.
And I cant find the method of set the height of pop-up window in doc of pygtk.
How to set the height of pop-up window in gtk.EntryCompletion?</p>
| 2 | 2009-06-07T11:19:34Z | 962,054 | <p>I don't know if this applies to gtk.EntryCompletion widgets, but for cell like widgets you can control their height with the <code>cell.set_fixed_height_from_font(True)</code> method. </p>
<p>Look at the <code>gtk.CellRendererText</code> API for details. </p>
| 0 | 2009-06-07T15:07:19Z | [
"python",
"gtk",
"pygtk"
] |
pygtk: How to set the height of pop-up window in gtk.EntryCompletion | 961,735 | <p>I use gtk.EntryCompletion to implement the autocomletion function.
But the list is so long that the pop-up window touches the bottom of screen.
And I cant find the method of set the height of pop-up window in doc of pygtk.
How to set the height of pop-up window in gtk.EntryCompletion?</p>
| 2 | 2009-06-07T11:19:34Z | 7,963,132 | <p>Maybe you can solve the problem using <code>gtk.EntryCompletion.set_minimum_key_length</code> to prevent long list of suggestions.</p>
| 0 | 2011-11-01T06:25:19Z | [
"python",
"gtk",
"pygtk"
] |
How to spawn multiple python scripts from a python program? | 961,838 | <p>I want to spawn (fork?) multiple Python scripts from my program (written in Python as well).</p>
<p>My problem is that I want to dedicate one terminal to each script, because I'll gather their output using <code>pexpect</code>.</p>
<p>I've tried using <code>pexpect</code>, <code>os.execlp</code>, and <code>os.forkpty</code> but neither of them do as I expect.</p>
<p>I want to spawn the child processes and forget about them (they will process some data, write the output to the terminal which I could read with <code>pexpect</code> and then exit).</p>
<p>Is there any library/best practice/etc. to accomplish this job?</p>
<p>p.s. Before you ask why I would write to STDOUT and read from it, I shall say that I don't write to STDOUT, I read the output of <code>tshark</code>.</p>
| 3 | 2009-06-07T12:59:37Z | 961,864 | <p>See the <a href="http://docs.python.org/library/subprocess.html#module-subprocess" rel="nofollow">subprocess module</a></p>
<blockquote>
<p>The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, such as:</p>
<p>os.system</p>
<p>os.spawn*</p>
<p>os.popen*</p>
<p>popen2.*</p>
<p>commands.*</p>
</blockquote>
| 4 | 2009-06-07T13:12:46Z | [
"python",
"pexpect",
"spawn",
"tshark"
] |
How to spawn multiple python scripts from a python program? | 961,838 | <p>I want to spawn (fork?) multiple Python scripts from my program (written in Python as well).</p>
<p>My problem is that I want to dedicate one terminal to each script, because I'll gather their output using <code>pexpect</code>.</p>
<p>I've tried using <code>pexpect</code>, <code>os.execlp</code>, and <code>os.forkpty</code> but neither of them do as I expect.</p>
<p>I want to spawn the child processes and forget about them (they will process some data, write the output to the terminal which I could read with <code>pexpect</code> and then exit).</p>
<p>Is there any library/best practice/etc. to accomplish this job?</p>
<p>p.s. Before you ask why I would write to STDOUT and read from it, I shall say that I don't write to STDOUT, I read the output of <code>tshark</code>.</p>
| 3 | 2009-06-07T12:59:37Z | 970,325 | <p>I don't understand why you need expect for this. <code>tshark</code> should send its output to stdout, and only for some strange reason would it send it to stderr.</p>
<p>Therefore, what you want should be:</p>
<pre><code>import subprocess
fp= subprocess.Popen( ("/usr/bin/tshark", "option1", "option2"), stdout=subprocess.PIPE).stdout
# now, whenever you are ready, read stuff from fp
</code></pre>
| 0 | 2009-06-09T14:15:19Z | [
"python",
"pexpect",
"spawn",
"tshark"
] |
How to spawn multiple python scripts from a python program? | 961,838 | <p>I want to spawn (fork?) multiple Python scripts from my program (written in Python as well).</p>
<p>My problem is that I want to dedicate one terminal to each script, because I'll gather their output using <code>pexpect</code>.</p>
<p>I've tried using <code>pexpect</code>, <code>os.execlp</code>, and <code>os.forkpty</code> but neither of them do as I expect.</p>
<p>I want to spawn the child processes and forget about them (they will process some data, write the output to the terminal which I could read with <code>pexpect</code> and then exit).</p>
<p>Is there any library/best practice/etc. to accomplish this job?</p>
<p>p.s. Before you ask why I would write to STDOUT and read from it, I shall say that I don't write to STDOUT, I read the output of <code>tshark</code>.</p>
| 3 | 2009-06-07T12:59:37Z | 24,715,421 | <p>You want to dedicate one terminal <strong><em>or</em></strong> one python shell?</p>
<p>You already have some useful answers for Popen and Subprocess, you could also use pexpect if you're already planning on using it anyways.</p>
<pre><code>#for multiple python shells
import pexpect
#make your commands however you want them, this is just one method
mycommand1 = "print 'hello first python shell'"
mycommand2 = "print 'this is my second shell'"
#add a "for" statement if you want
child1 = pexpect.spawn('python')
child1.sendline(mycommand1)
child2 = pexpect.spawn('python')
child2.sendline(mycommand2)
</code></pre>
<p>Make as many children/shells as you want and then use the child.before() or child.after() to get your responses.</p>
<p>Of course you would want to add definitions or classes to be sent instead of "mycommand1", but this is just a simple example.</p>
<p>If you wanted to make a bunch of terminals in linux, you just need to replace the 'python' in the pextpext.spawn line</p>
<p>Note: I haven't tested the above code. I'm just replying from past experience with pexpect.</p>
| 0 | 2014-07-12T17:14:43Z | [
"python",
"pexpect",
"spawn",
"tshark"
] |
python logarithm | 961,972 | <p>i want to find out a log10 of an integer in python and i get an error like
math domain error </p>
<p>my code is this
w=math.log10(q*q1)/math.log10(2)</p>
<p>where q1,q2 are integers</p>
<p>yeah q1 is 0 sometimes</p>
| 1 | 2009-06-07T14:29:43Z | 961,977 | <p>Is q or q1 equal to zero or one of them negative?</p>
| 6 | 2009-06-07T14:31:53Z | [
"python"
] |
python logarithm | 961,972 | <p>i want to find out a log10 of an integer in python and i get an error like
math domain error </p>
<p>my code is this
w=math.log10(q*q1)/math.log10(2)</p>
<p>where q1,q2 are integers</p>
<p>yeah q1 is 0 sometimes</p>
| 1 | 2009-06-07T14:29:43Z | 961,992 | <p>math.log10(0) is minus infinity.
See: <a href="http://en.wikipedia.org/wiki/Logarithm" rel="nofollow">http://en.wikipedia.org/wiki/Logarithm</a></p>
| 1 | 2009-06-07T14:37:40Z | [
"python"
] |
python logarithm | 961,972 | <p>i want to find out a log10 of an integer in python and i get an error like
math domain error </p>
<p>my code is this
w=math.log10(q*q1)/math.log10(2)</p>
<p>where q1,q2 are integers</p>
<p>yeah q1 is 0 sometimes</p>
| 1 | 2009-06-07T14:29:43Z | 961,993 | <p>You can only compute the logarithm of a positive number. Trying to compute the logarithm for a negative number or zero will result in a "math domain error" in Python.</p>
<p>By the way: it looks like you're actually trying to compute a logarithm base 2. You can do this with <code>math.log</code>:</p>
<pre><code>w=math.log(q*q1, 2)
</code></pre>
<p>The second, optional, parameter is the base. It defaults to e (ie: natural log).</p>
| 10 | 2009-06-07T14:37:51Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.