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
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code ...
116
2008-11-29T01:24:09Z
327,063
<p>using Claudiu's code, on my machine even with "from math import sqrt" x**.5 is faster but using psyco.full() sqrt(x) becomes much faster, at least by 200%</p>
4
2008-11-29T02:28:52Z
[ "python", "performance" ]
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code ...
116
2008-11-29T01:24:09Z
2,695,986
<p>Claudiu's results differ from mine. I'm using Python 2.6 on Ubuntu on an old P4 2.4Ghz machine... Here's my results:</p> <pre><code>&gt;&gt;&gt; timeit1() Took 0.564911 seconds &gt;&gt;&gt; timeit2() Took 0.403087 seconds &gt;&gt;&gt; timeit1() Took 0.604713 seconds &gt;&gt;&gt; timeit2() Took 0.387749 seconds &gt;...
0
2010-04-23T03:14:26Z
[ "python", "performance" ]
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code ...
116
2008-11-29T01:24:09Z
2,696,173
<p>In python 2.6 the <code>(float).__pow__()</code> function uses the C <code>pow()</code> function and the <code>math.sqrt()</code> functions uses the C <code>sqrt()</code> function.</p> <p>In glibc compiler the implementation of <code>pow(x,y)</code> is quite complex and it is well optimized for various exceptional...
4
2010-04-23T04:17:49Z
[ "python", "performance" ]
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code ...
116
2008-11-29T01:24:09Z
2,696,402
<p>Someone commented about the "fast Newton-Raphson square root" from Quake 3... I implemented it with ctypes, but it's super slow in comparison to the native versions. I'm going to try a few optimizations and alternate implementations.</p> <pre><code>from ctypes import c_float, c_long, byref, POINTER, cast def sqrt(...
2
2010-04-23T05:27:31Z
[ "python", "performance" ]
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code ...
116
2008-11-29T01:24:09Z
29,231,648
<p>What would be even faster is if you went into math.py and copied the function "sqrt" into your program. It takes time for your program to find math.py, then open it, find the function you are looking for, and then bring that back to your program. If that function is faster even with the "lookup" steps, then the func...
-2
2015-03-24T11:37:06Z
[ "python", "performance" ]
Attribute BOLD doesn't seem to work in my curses
327,026
<p>I use something like this: screen.addstr(text, color_pair(1) | A_BOLD), but it doesn't seem to work.. However, A_REVERSE and all others attribute does work! </p> <p>In fact, I'm trying to print something in white, but the COLOR_WHITE prints it gray.. and after a while of searching, it seems that printing it gray +...
3
2008-11-29T01:46:53Z
327,072
<p>Here's an example code (Python 2.6, Linux):</p> <pre><code>#!/usr/bin/env python from itertools import cycle import curses, contextlib, time @contextlib.contextmanager def curses_screen(): """Contextmanager's version of curses.wrapper().""" try: stdscr=curses.initscr() curses.noecho() ...
4
2008-11-29T02:38:50Z
[ "python", "linux", "curses", "bold" ]
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other
327,142
<p>I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. <...
3
2008-11-29T04:01:45Z
327,237
<p>Well, if they have the same project and application names, then the databases and tables will be the same. Your django_session table which holds the session information is the same for both sites. You have to use different project names that will go in different MySQL (or whatever) databases.</p>
0
2008-11-29T05:56:53Z
[ "python", "django", "admin" ]
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other
327,142
<p>I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. <...
3
2008-11-29T04:01:45Z
327,296
<p>The session information is stored in the database, so if you're sharing the database with both running instances, logging off one location will log you off both. If your circumstance requires you to share the database, the easiest workaround is probably to create a second user account with admin privileges.</p>
0
2008-11-29T07:06:58Z
[ "python", "django", "admin" ]
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other
327,142
<p>I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. <...
3
2008-11-29T04:01:45Z
327,307
<p>Set the <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#session-cookie-domain">SESSION&#x5F;COOKIE&#x5F;DOMAIN</a> option. You need to set the domain for each of your sites so the cookies don't override each other.</p> <p>You can also use SESSION&#x5F;COOKIE&#x5F;NAME to make the cookie names d...
7
2008-11-29T07:27:35Z
[ "python", "django", "admin" ]
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other
327,142
<p>I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. <...
3
2008-11-29T04:01:45Z
327,398
<p>Let me guess, is this running on your localhost? and you have each site assigned to a different port? i.e. localhost:8000, localhost:8001 ..?</p> <p>I've had the same problem! (although I wasn't running Apache per se)</p> <p>When you login to the admin site, you get a cookie in your browser that's associated with ...
0
2008-11-29T10:08:50Z
[ "python", "django", "admin" ]
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other
327,142
<p>I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. <...
3
2008-11-29T04:01:45Z
1,007,356
<p>I ran into a similar issue with a live &amp; staging site hosted on the same Apache server (on CentOS). I added unique SESSION_COOKIE_NAME values to each site's settings (in local_settings.py, create one if you don't have one and import it in your settings.py), set the SESSION_COOKIE_DOMAIN for the live site and set...
0
2009-06-17T14:23:25Z
[ "python", "django", "admin" ]
in python, is there a one line pythonic way to get a list of keys from a dictionary in sorted order?
327,191
<p>The list sort method is a modifier function that returns None.</p> <p>So if I want to iterate through all of the keys in a dictionary I cannot do:</p> <pre> for k in somedictionary.keys().sort(): dosomething() </pre> <p>instead, i must:</p> <pre> keys = somedictionary.keys() keys.sort() for k in keys: do...
2
2008-11-29T05:03:14Z
327,195
<p>Can I answer my own question?</p> <p>I have just discovered the handy function "sorted" which does exactly what I was looking for.</p> <pre> for k in sorted(somedictionary.keys()): dosomething() </pre> <p>It shows up in <a href="http://stackoverflow.com/questions/157424/python-25-dictionary-2-key-sort">http:/...
6
2008-11-29T05:06:35Z
[ "python", "iterator", "syntactic-sugar" ]
in python, is there a one line pythonic way to get a list of keys from a dictionary in sorted order?
327,191
<p>The list sort method is a modifier function that returns None.</p> <p>So if I want to iterate through all of the keys in a dictionary I cannot do:</p> <pre> for k in somedictionary.keys().sort(): dosomething() </pre> <p>instead, i must:</p> <pre> keys = somedictionary.keys() keys.sort() for k in keys: do...
2
2008-11-29T05:03:14Z
327,210
<pre><code>for k in sorted(somedictionary.keys()): doSomething(k) </code></pre> <p>Note that you can also get all of the keys and values sorted by keys like this:</p> <pre><code>for k, v in sorted(somedictionary.iteritems()): doSomething(k, v) </code></pre>
17
2008-11-29T05:20:37Z
[ "python", "iterator", "syntactic-sugar" ]
in python, is there a one line pythonic way to get a list of keys from a dictionary in sorted order?
327,191
<p>The list sort method is a modifier function that returns None.</p> <p>So if I want to iterate through all of the keys in a dictionary I cannot do:</p> <pre> for k in somedictionary.keys().sort(): dosomething() </pre> <p>instead, i must:</p> <pre> keys = somedictionary.keys() keys.sort() for k in keys: do...
2
2008-11-29T05:03:14Z
856,272
<p>Actually, .keys() is not necessary:</p> <pre><code>for k in sorted(somedictionary): doSomething(k) </code></pre> <p>or </p> <pre><code>[doSomethinc(k) for k in sorted(somedict)] </code></pre>
6
2009-05-13T05:54:38Z
[ "python", "iterator", "syntactic-sugar" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
327,254
<p>You could try to use same dictionary, only one level deep.</p> <pre><code>topDictionary[word1+delimiter+word2+delimiter+word3] </code></pre> <p>delimiter could be plain " ". (or use (word1,word2,word3))</p> <p>This would be easiest to implement. I believe you will see a little improvement, if it is not enough... ...
1
2008-11-29T06:21:59Z
[ "python", "memory", "data-structures" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
327,285
<p>A couple attempts:</p> <p>I figure you're doing something similar to this:</p> <pre><code>from __future__ import with_statement import time from collections import deque, defaultdict # Just used to generate some triples of words def triplegen(words="/usr/share/dict/words"): d=deque() with open(words) as ...
3
2008-11-29T06:59:32Z
[ "python", "memory", "data-structures" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
327,295
<p>Some measurements. I took 10MB of free e-book text and computed trigram frequencies, producing a 24MB file. Storing it in different simple Python data structures took this much space in kB, measured as RSS from running ps, where d is a dict, keys and freqs are lists, and a,b,c,freq are the fields of a trigram record...
26
2008-11-29T07:06:58Z
[ "python", "memory", "data-structures" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
327,299
<p>You could put all words in a dictionary. key would be word, and value is number (index).</p> <p>Then you use it like this:</p> <pre><code>Word1=indexDict[word1] Word2=indexDict[word2] Word3=indexDict[word3] topDictionary[Word1][Word2][Word3] </code></pre> <p>Insert in indexDict with:</p> <pre><code>if word not ...
-1
2008-11-29T07:11:47Z
[ "python", "memory", "data-structures" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
327,313
<p>Use tuples.<br /> Tuples can be keys to dictionaries, so you don't need to nest dictionaries.</p> <pre><code>d = {} d[ word1, word2, word3 ] = 1 </code></pre> <p>Also as a plus, you could use defaultdict </p> <ul> <li>so that elements that don't have entries always return 0</li> <li>and so that u can say <code>...
8
2008-11-29T07:36:31Z
[ "python", "memory", "data-structures" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
327,459
<p>Ok, so you are basically trying to store a sparse 3D space. The kind of access patterns you want to this space is crucial for the choice of algorithm and data structure. Considering your data source, do you want to feed this to a grid? If you don't need O(1) access:</p> <p>In order to get memory efficiency you want...
1
2008-11-29T11:44:40Z
[ "python", "memory", "data-structures" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
327,464
<p>In this case, <a href="http://www.zope.org/Products/StandaloneZODB" rel="nofollow">ZODB</a>¹ BTrees might be helpful, since they are much less memory-hungry. Use a BTrees.OOBtree (Object keys to Object values) or BTrees.OIBTree (Object keys to Integer values), and use 3-word tuples as your key.</p> <p>Something li...
4
2008-11-29T11:50:18Z
[ "python", "memory", "data-structures" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
327,479
<p>Are you implementing Markovian text generation?</p> <p>If your chains map 2 words to the probabilities of the third I'd use a dictionary mapping K-tuples to the 3rd-word histogram. A trivial (but memory-hungry) way to implement the histogram would be to use a list with repeats, and then <code>random.choice</code> g...
2
2008-11-29T12:14:17Z
[ "python", "memory", "data-structures" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
327,481
<p>If memory is simply not big enough, <a href="http://www.jcea.es/programacion/pybsddb.htm" rel="nofollow">pybsddb</a> can help store a disk-persistent map.</p>
0
2008-11-29T12:18:27Z
[ "python", "memory", "data-structures" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
327,697
<p>You could use a numpy multidimensional array. You'll need to use numbers rather than strings to index into the array, but that can be solved by using a single dict to map words to numbers.</p> <pre><code>import numpy w = {'word1':1, 'word2':2, 'word3':3, 'word4':4} a = numpy.zeros( (4,4,4) ) </code></pre> <p>Then ...
0
2008-11-29T16:52:46Z
[ "python", "memory", "data-structures" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
327,924
<p>Here's a tree structure that uses the bisect library to maintain a sorted list of words. Each lookup in <strong>O</strong>(log2(n)).</p> <pre><code>import bisect class WordList( object ): """Leaf-level is list of words and counts.""" def __init__( self ): self.words= [ ('\xff-None-',0) ] def c...
1
2008-11-29T19:48:04Z
[ "python", "memory", "data-structures" ]
Memory Efficient Alternatives to Python Dictionaries
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][w...
32
2008-11-29T05:33:26Z
331,384
<p>Scipy has sparse matrices, so if you can make the first two words a tuple, you can do something like this:</p> <pre><code>import numpy as N from scipy import sparse word_index = {} count = sparse.lil_matrix((word_count*word_count, word_count), dtype=N.int) for word1, word2, word3 in triple_list: w1 = word_ind...
1
2008-12-01T16:42:46Z
[ "python", "memory", "data-structures" ]
Why is the Python readline module not available on OS X?
327,251
<p>The documentation of the Python <a href="http://www.python.org/doc/2.5.2/lib/module-readline.html" rel="nofollow"><code>readline</code></a> module says "Availability: Unix". However, it doesn't appear to be available on OS X, although other modules marked as Unix are available. Here is what I'm using:</p> <pre> $ u...
4
2008-11-29T06:18:49Z
327,262
<p>It's not shipped in OS X because of licensing issues (restrictions brought to you by the GPL).</p> <p>Macports python should be fine if you have the readline package installed.</p>
3
2008-11-29T06:29:39Z
[ "python", "osx", "readline" ]
Why is the Python readline module not available on OS X?
327,251
<p>The documentation of the Python <a href="http://www.python.org/doc/2.5.2/lib/module-readline.html" rel="nofollow"><code>readline</code></a> module says "Availability: Unix". However, it doesn't appear to be available on OS X, although other modules marked as Unix are available. Here is what I'm using:</p> <pre> $ u...
4
2008-11-29T06:18:49Z
327,292
<p>Have you tried to install the <code>py-readline</code> (or <code>py25-readline</code> for Python 2.5) port?</p> <p>Also, in the snippet above, you are NOT using the MacPort python, but rather the Apple Python.</p> <p>The MacPort version should be located in the <code>/opt/local</code> directory structure. You shou...
6
2008-11-29T07:05:00Z
[ "python", "osx", "readline" ]
Why is the Python readline module not available on OS X?
327,251
<p>The documentation of the Python <a href="http://www.python.org/doc/2.5.2/lib/module-readline.html" rel="nofollow"><code>readline</code></a> module says "Availability: Unix". However, it doesn't appear to be available on OS X, although other modules marked as Unix are available. Here is what I'm using:</p> <pre> $ u...
4
2008-11-29T06:18:49Z
1,114,882
<p>You should be able to get readline support on Mac's native Python. Apparently it's implemented via BSD's editline, and you have to start it up slightly differently. I just tested this on a Mac, and it works fine (OS X 10.5.7). See <code>man python</code> for more details, the section "Interactive Input Editing and H...
3
2009-07-11T23:05:09Z
[ "python", "osx", "readline" ]
Why is the Python readline module not available on OS X?
327,251
<p>The documentation of the Python <a href="http://www.python.org/doc/2.5.2/lib/module-readline.html" rel="nofollow"><code>readline</code></a> module says "Availability: Unix". However, it doesn't appear to be available on OS X, although other modules marked as Unix are available. Here is what I'm using:</p> <pre> $ u...
4
2008-11-29T06:18:49Z
38,943,793
<p>Try <code>rlwrap</code>. It should work with any version of python and in general any shell.</p> <p>Install via <code>brew install rlwrap</code> on Mac OS X</p> <p>usage as <code>rlwrap python</code>. It stores history as well.</p>
0
2016-08-14T15:38:39Z
[ "python", "osx", "readline" ]
How are Python's Built In Dictionaries Implemented
327,311
<p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
146
2008-11-29T07:35:31Z
327,317
<p>It is a hash table. You can read about it some in the <a href="http://wiki.python.org/moin/DictionaryKeys" rel="nofollow">python wiki</a>. Otherwise, the code is well-written and should be easy to understand.</p>
4
2008-11-29T07:40:18Z
[ "python", "data-structures", "dictionary" ]
How are Python's Built In Dictionaries Implemented
327,311
<p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
146
2008-11-29T07:35:31Z
327,378
<p><a href="http://pybites.blogspot.com/2008/10/pure-python-dictionary-implementation.html">Pure Python Dictionary Implementation</a></p> <blockquote> <p>For those curious about how CPython's dict implementation works, I've written a Python implementation using the same algorithms.</p> </blockquote>
8
2008-11-29T09:22:46Z
[ "python", "data-structures", "dictionary" ]
How are Python's Built In Dictionaries Implemented
327,311
<p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
146
2008-11-29T07:35:31Z
334,953
<p>Here's a link to the <a href="http://svn.python.org/view/python/trunk/Objects/dictobject.c?rev=66801&amp;view=auto" title="dict implementation">actual implementation</a> in the python SVN repository. That should be the most definite answer.</p>
8
2008-12-02T18:29:16Z
[ "python", "data-structures", "dictionary" ]
How are Python's Built In Dictionaries Implemented
327,311
<p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
146
2008-11-29T07:35:31Z
2,996,689
<p>Python Dictionaries use <a href="http://en.wikipedia.org/wiki/Hash_table#Open_addressing">Open addressing</a> (<a href="http://books.google.co.in/books?id=gJrmszNHQV4C&amp;lpg=PP1&amp;hl=sv&amp;pg=PA298#v=onepage&amp;q&amp;f=false">reference inside Beautiful code</a>)</p> <p><strong>NB!</strong> <em>Open addressing...
37
2010-06-08T11:00:37Z
[ "python", "data-structures", "dictionary" ]
How are Python's Built In Dictionaries Implemented
327,311
<p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
146
2008-11-29T07:35:31Z
8,682,049
<p>At PyCon 2010, Brandon Craig Rhodes gave an <a href="http://www.youtube.com/watch?v=C4Kc8xzcA68">excellent talk</a> about the Python dictionary. It provides a great overview of the dictionary implementation with examples and visuals. If you have 45 minutes (or even just 15), I would recommend watching the talk befor...
27
2011-12-30T17:15:04Z
[ "python", "data-structures", "dictionary" ]
How are Python's Built In Dictionaries Implemented
327,311
<p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
146
2008-11-29T07:35:31Z
9,022,835
<p>Here is everything about Python dicts that I was able to put together (probably more than anyone would like to know; but the answer is comprehensive). </p> <ul> <li>Python dictionaries are implemented as <strong>hash tables</strong>.</li> <li>Hash tables must allow for <strong>hash collisions</strong> i.e. even if ...
241
2012-01-26T17:52:00Z
[ "python", "data-structures", "dictionary" ]
storing unbound python functions in a class object
327,483
<p>I'm trying to do the following in python:</p> <p>In a file called foo.py:</p> <pre><code># simple function that does something: def myFunction(a,b,c): print "call to myFunction:",a,b,c # class used to store some data: class data: fn = None # assign function to the class for storage. data.fn = myFunction </co...
11
2008-11-29T12:21:47Z
327,488
<pre><code>data.fn = staticmethod(myFunction) </code></pre> <p>should do the trick.</p>
15
2008-11-29T12:28:33Z
[ "python", "function" ]
storing unbound python functions in a class object
327,483
<p>I'm trying to do the following in python:</p> <p>In a file called foo.py:</p> <pre><code># simple function that does something: def myFunction(a,b,c): print "call to myFunction:",a,b,c # class used to store some data: class data: fn = None # assign function to the class for storage. data.fn = myFunction </co...
11
2008-11-29T12:21:47Z
327,491
<p>This seems pointless to me. Why not just call myFunction when you need it?</p> <p>In general, in Python, we use modules for this kind of namespacing (contrast this with Java where you just have no choice). And of course, myFunction is already bound to the module namespace when you define it.</p> <p><a href="http:/...
0
2008-11-29T12:34:01Z
[ "python", "function" ]
storing unbound python functions in a class object
327,483
<p>I'm trying to do the following in python:</p> <p>In a file called foo.py:</p> <pre><code># simple function that does something: def myFunction(a,b,c): print "call to myFunction:",a,b,c # class used to store some data: class data: fn = None # assign function to the class for storage. data.fn = myFunction </co...
11
2008-11-29T12:21:47Z
327,530
<p>What you can do is:</p> <pre><code>d = foo.data() d.fn = myFunction d.fn(1,2,3) </code></pre> <p>Which may not be exactly what you want, but does work.</p>
0
2008-11-29T13:38:20Z
[ "python", "function" ]
storing unbound python functions in a class object
327,483
<p>I'm trying to do the following in python:</p> <p>In a file called foo.py:</p> <pre><code># simple function that does something: def myFunction(a,b,c): print "call to myFunction:",a,b,c # class used to store some data: class data: fn = None # assign function to the class for storage. data.fn = myFunction </co...
11
2008-11-29T12:21:47Z
328,700
<p>Thanks to Andre for the answer - so simple!</p> <p>For those of you who care, perhaps I should have included the entire context of the problem. Here it is anyway:</p> <p>In my application, users are able to write plugins in python. They must define a function with a well-defined parameter list, but I didn't want t...
0
2008-11-30T10:21:24Z
[ "python", "function" ]
Storing and updating lists in Python dictionaries: why does this happen?
327,534
<p>I have a list of data that looks like the following:</p> <pre><code>// timestep,x_position,y_position 0,4,7 0,2,7 0,9,5 0,6,7 1,2,5 1,4,7 1,9,0 1,6,8 </code></pre> <p>... and I want to make this look like:</p> <pre><code>0, (4,7), (2,7), (9,5), (6,7) 1, (2,5), (4,7), (9,0), (6.8) </code></pre> <p>My plan was to ...
19
2008-11-29T13:40:05Z
327,548
<p>Let's look at</p> <pre><code>d[t].append(c) </code></pre> <p>What is the value of <code>d[t]</code>? Try it.</p> <pre><code>d = {} t = 0 d[t] </code></pre> <p>What do you get? Oh. There's nothing in <code>d</code> that has a key of <code>t</code>.</p> <p>Now try this.</p> <pre><code>d[t] = [] d[t] </code></...
57
2008-11-29T13:46:42Z
[ "python", "dictionary", "list" ]
Storing and updating lists in Python dictionaries: why does this happen?
327,534
<p>I have a list of data that looks like the following:</p> <pre><code>// timestep,x_position,y_position 0,4,7 0,2,7 0,9,5 0,6,7 1,2,5 1,4,7 1,9,0 1,6,8 </code></pre> <p>... and I want to make this look like:</p> <pre><code>0, (4,7), (2,7), (9,5), (6,7) 1, (2,5), (4,7), (9,0), (6.8) </code></pre> <p>My plan was to ...
19
2008-11-29T13:40:05Z
327,558
<pre><code>dict=[] //it's not a dict, it's a list, the dictionary is dict={} elem=[1,2,3] dict.append(elem) </code></pre> <p>you can access the single element in this way:</p> <pre><code>print dict[0] // 0 is the index </code></pre> <p>the output will be:</p> <pre><code>[1, 2, 3] </code></pre>
1
2008-11-29T13:53:34Z
[ "python", "dictionary", "list" ]
Storing and updating lists in Python dictionaries: why does this happen?
327,534
<p>I have a list of data that looks like the following:</p> <pre><code>// timestep,x_position,y_position 0,4,7 0,2,7 0,9,5 0,6,7 1,2,5 1,4,7 1,9,0 1,6,8 </code></pre> <p>... and I want to make this look like:</p> <pre><code>0, (4,7), (2,7), (9,5), (6,7) 1, (2,5), (4,7), (9,0), (6.8) </code></pre> <p>My plan was to ...
19
2008-11-29T13:40:05Z
327,575
<p>I think you want to use setdefault. It's a bit weird to use but does exactly what you need.</p> <pre><code>d.setdefault(t, []).append(c) </code></pre> <p>The <code>.setdefault</code> method will return the element (in our case, a list) that's bound to the dict's key <code>t</code> if that key exists. If it doesn't...
9
2008-11-29T14:28:09Z
[ "python", "dictionary", "list" ]
Storing and updating lists in Python dictionaries: why does this happen?
327,534
<p>I have a list of data that looks like the following:</p> <pre><code>// timestep,x_position,y_position 0,4,7 0,2,7 0,9,5 0,6,7 1,2,5 1,4,7 1,9,0 1,6,8 </code></pre> <p>... and I want to make this look like:</p> <pre><code>0, (4,7), (2,7), (9,5), (6,7) 1, (2,5), (4,7), (9,0), (6.8) </code></pre> <p>My plan was to ...
19
2008-11-29T13:40:05Z
332,525
<p>In the case your data is not already sorted by desired criteria, here's the code that might help to group the data:</p> <pre><code>#!/usr/bin/env python """ $ cat data_shuffled.txt 0,2,7 1,4,7 0,4,7 1,9,0 1,2,5 0,6,7 1,6,8 0,9,5 """ from itertools import groupby from operator import itemgetter # load the data...
1
2008-12-01T22:54:25Z
[ "python", "dictionary", "list" ]
Suggestion to implement a text Menu without switch case
327,597
<p>I'm giving my first steps on Python. I saw that we don't have switch case statement, so I would you guys implement a text Menu in python?</p> <p>Thanks</p>
2
2008-11-29T15:01:28Z
327,601
<p>You can use if...elif. If you have to choose a number, it would be like this:</p> <pre><code>n = chosenOption() if(n == 0): doSomething() elif(n == 1): doAnyOtherThing() else: doDefaultThing() </code></pre>
2
2008-11-29T15:06:14Z
[ "python" ]
Suggestion to implement a text Menu without switch case
327,597
<p>I'm giving my first steps on Python. I saw that we don't have switch case statement, so I would you guys implement a text Menu in python?</p> <p>Thanks</p>
2
2008-11-29T15:01:28Z
327,611
<p>Have a look at this <a href="http://www.network-theory.co.uk/docs/pytut/ifStatements.html" rel="nofollow">topic</a> from "An Introduction to Python" book. Switch statement is substituted by an if..elif..elif sequence.</p>
2
2008-11-29T15:15:34Z
[ "python" ]
Suggestion to implement a text Menu without switch case
327,597
<p>I'm giving my first steps on Python. I saw that we don't have switch case statement, so I would you guys implement a text Menu in python?</p> <p>Thanks</p>
2
2008-11-29T15:01:28Z
327,612
<p>Generally if elif will be fine, but if you have lots of cases, please consider using a dict.</p> <pre><code>actions = {1: doSomething, 2: doSomethingElse} actions.get(n, doDefaultThing)() </code></pre>
5
2008-11-29T15:15:46Z
[ "python" ]
Suggestion to implement a text Menu without switch case
327,597
<p>I'm giving my first steps on Python. I saw that we don't have switch case statement, so I would you guys implement a text Menu in python?</p> <p>Thanks</p>
2
2008-11-29T15:01:28Z
327,735
<p>To your first question I agree with Ali A.</p> <p>To your second question :</p> <p>import sys<br> sys.exit(1)</p>
0
2008-11-29T17:27:51Z
[ "python" ]
Suggestion to implement a text Menu without switch case
327,597
<p>I'm giving my first steps on Python. I saw that we don't have switch case statement, so I would you guys implement a text Menu in python?</p> <p>Thanks</p>
2
2008-11-29T15:01:28Z
327,741
<p>You might do something like this:</p> <pre><code>def action1(): pass # put a function here def action2(): pass # blah blah def action3(): pass # and so on def no_such_action(): pass # print a message indicating there's no such action def main(): actions = {"foo": action1, "bar": action2, "ba...
12
2008-11-29T17:32:04Z
[ "python" ]
Suggestion to implement a text Menu without switch case
327,597
<p>I'm giving my first steps on Python. I saw that we don't have switch case statement, so I would you guys implement a text Menu in python?</p> <p>Thanks</p>
2
2008-11-29T15:01:28Z
9,634,208
<p>I came here looking for the same thing and ended up writing my own: <a href="https://github.com/gerrywastaken/menu.py" rel="nofollow">https://github.com/gerrywastaken/menu.py</a></p> <p>You call it like so:</p> <pre><code>import menu message = "Your question goes here" options = { 'f': ['[F]irst Option Name',...
0
2012-03-09T12:41:43Z
[ "python" ]
Read the last lineof the file
327,776
<p>Imagine I have a file with </p> <p>Xpto,50,30,60 Xpto,a,v,c Xpto,1,9,0 Xpto,30,30,60</p> <p>that txt file can be appended a lot of times and when I open the file I want only to get the values of the last line of the txt file... How can i do that on python? reading the last line?</p> <p>Thanks</p>
3
2008-11-29T18:03:03Z
327,784
<p>Not sure about a python specific implementation, but in a more language agnostic fashion, what you would want to do is skip (seek) to the end of the file, and then read each character in backwards order until you reach the line feed character that your file is using, usually a character with value 13. just read for...
-1
2008-11-29T18:06:24Z
[ "python" ]
Read the last lineof the file
327,776
<p>Imagine I have a file with </p> <p>Xpto,50,30,60 Xpto,a,v,c Xpto,1,9,0 Xpto,30,30,60</p> <p>that txt file can be appended a lot of times and when I open the file I want only to get the values of the last line of the txt file... How can i do that on python? reading the last line?</p> <p>Thanks</p>
3
2008-11-29T18:03:03Z
327,825
<p>I think my answer from the <a href="http://stackoverflow.com/questions/260273/most-efficient-way-to-search-the-last-x-lines-of-a-file-in-python">last time this came up</a> was sadly overlooked. :-)</p> <blockquote> <p>If you're on a unix box, <code>os.popen("tail -10 " + filepath).readlines()</code> will prob...
9
2008-11-29T18:34:42Z
[ "python" ]
Read the last lineof the file
327,776
<p>Imagine I have a file with </p> <p>Xpto,50,30,60 Xpto,a,v,c Xpto,1,9,0 Xpto,30,30,60</p> <p>that txt file can be appended a lot of times and when I open the file I want only to get the values of the last line of the txt file... How can i do that on python? reading the last line?</p> <p>Thanks</p>
3
2008-11-29T18:03:03Z
327,980
<p><code>f.seek( pos ,2)</code> seeks to 'pos' relative to the end of the file. try a reasonable value for pos then readlines() and get the last line.</p> <p>You have to account for when 'pos' is not a good guess, i.e. suppose you choose 300, but the last line is 600 chars long! in that case, just try again with a rea...
1
2008-11-29T20:36:00Z
[ "python" ]
Read the last lineof the file
327,776
<p>Imagine I have a file with </p> <p>Xpto,50,30,60 Xpto,a,v,c Xpto,1,9,0 Xpto,30,30,60</p> <p>that txt file can be appended a lot of times and when I open the file I want only to get the values of the last line of the txt file... How can i do that on python? reading the last line?</p> <p>Thanks</p>
3
2008-11-29T18:03:03Z
10,180,739
<p>Um why not just seek to the end of the file and read til you hit a newline?.</p> <pre><code>i=0 while(1): f.seek(i, 2) c = f.read(1) if(c=='\n'): break </code></pre>
0
2012-04-16T19:56:06Z
[ "python" ]
Django equivalent for count and group by
327,807
<p>I have a model that looks like this:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=60) class Item(models.Model): name = models.CharField(max_length=60) category = models.ForeignKey(Category) </code></pre> <p>I want select count (just the count) of items for each categ...
82
2008-11-29T18:19:28Z
327,987
<p>(<strong>Update</strong>: Full ORM aggregation support is now included in <a href="http://docs.djangoproject.com/en/dev/releases/1.1/#aggregate-support">Django 1.1</a>. True to the below warning about using private APIs, the method documented here no longer works in post-1.1 versions of Django. I haven't dug in to ...
56
2008-11-29T20:44:21Z
[ "python", "django" ]
Django equivalent for count and group by
327,807
<p>I have a model that looks like this:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=60) class Item(models.Model): name = models.CharField(max_length=60) category = models.ForeignKey(Category) </code></pre> <p>I want select count (just the count) of items for each categ...
82
2008-11-29T18:19:28Z
328,040
<p>How's this? (Other than slow.)</p> <pre><code>counts= [ (c, Item.filter( category=c.id ).count()) for c in Category.objects.all() ] </code></pre> <p>It has the advantage of being short, even if it does fetch a lot of rows.</p> <p><hr /></p> <p>Edit.</p> <p>The one query version. BTW, this is often <em>faster<...
2
2008-11-29T21:31:53Z
[ "python", "django" ]
Django equivalent for count and group by
327,807
<p>I have a model that looks like this:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=60) class Item(models.Model): name = models.CharField(max_length=60) category = models.ForeignKey(Category) </code></pre> <p>I want select count (just the count) of items for each categ...
82
2008-11-29T18:19:28Z
1,317,837
<p>Here, as I just discovered, is how to do this with the Django 1.1 aggregation API:</p> <pre><code>from django.db.models import Count theanswer = Item.objects.values('category').annotate(Count('category')) </code></pre>
120
2009-08-23T05:21:09Z
[ "python", "django" ]
Django equivalent for count and group by
327,807
<p>I have a model that looks like this:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=60) class Item(models.Model): name = models.CharField(max_length=60) category = models.ForeignKey(Category) </code></pre> <p>I want select count (just the count) of items for each categ...
82
2008-11-29T18:19:28Z
1,341,667
<p>Since I was a little confused about how grouping in Django 1.1 works I thought I'd elaborate here on how exactly you go about using it. First, to repeat what Michael said:</p> <blockquote> <p>Here, as I just discovered, is how to do this with the Django 1.1 aggregation API:</p> <pre><code>from django.db.models i...
51
2009-08-27T15:02:17Z
[ "python", "django" ]
how to draw lines on a picture background in pygame
327,896
<p>I would like to draw lines (of arbitrary position and length) onto a surface in pygame, which itself is an image loaded from a file on disk.</p> <p>Can anyone point me to some example code that does this?</p>
1
2008-11-29T19:31:42Z
327,908
<p>Help on module pygame.draw in pygame:</p> <p>NAME pygame.draw - pygame module for drawing shapes</p> <p>FILE d:\program files\python25\lib\site-packages\pygame\draw.pyd</p> <p>FUNCTIONS aaline(...) pygame.draw.aaline(Surface, color, startpos, endpos, blend=1): return Rect draw fine ant...
0
2008-11-29T19:38:14Z
[ "python", "drawing", "pygame" ]
how to draw lines on a picture background in pygame
327,896
<p>I would like to draw lines (of arbitrary position and length) onto a surface in pygame, which itself is an image loaded from a file on disk.</p> <p>Can anyone point me to some example code that does this?</p>
1
2008-11-29T19:31:42Z
328,002
<p>This should do what you're asking for:</p> <pre><code># load the image image = pygame.image.load("some_image.png") # draw a yellow line on the image pygame.draw.line(image, (255, 255, 0), (0, 0), (100, 100)) </code></pre> <p>Typically you don't draw to the original image, since you'll have to reload the image to ...
2
2008-11-29T20:59:44Z
[ "python", "drawing", "pygame" ]
How do I modify the last line of a file?
327,985
<p>The last line of my file is:</p> <blockquote> <p>29-dez,40,</p> </blockquote> <p>How can I modify that line so that it reads:</p> <blockquote> <p>29-Dez,40,90,100,50</p> </blockquote> <p>Note: I don't want to write a new line. I want to take the same line and put new values after <code>29-Dez,40,</code></p> ...
3
2008-11-29T20:41:28Z
327,992
<p>Don't work with files directly, make a data structure that fits your needs in form of a class and make read from/write to file methods.</p>
0
2008-11-29T20:46:52Z
[ "python", "file" ]
How do I modify the last line of a file?
327,985
<p>The last line of my file is:</p> <blockquote> <p>29-dez,40,</p> </blockquote> <p>How can I modify that line so that it reads:</p> <blockquote> <p>29-Dez,40,90,100,50</p> </blockquote> <p>Note: I don't want to write a new line. I want to take the same line and put new values after <code>29-Dez,40,</code></p> ...
3
2008-11-29T20:41:28Z
328,007
<p>Unless the file is huge, you'll probably find it easier to read the entire file into a data structure (which might just be a list of lines), and then modify the data structure in memory, and finally write it back to the file.</p> <p>On the other hand maybe your file <em>is</em> really huge - multiple GBs at least. ...
4
2008-11-29T21:05:31Z
[ "python", "file" ]
How do I modify the last line of a file?
327,985
<p>The last line of my file is:</p> <blockquote> <p>29-dez,40,</p> </blockquote> <p>How can I modify that line so that it reads:</p> <blockquote> <p>29-Dez,40,90,100,50</p> </blockquote> <p>Note: I don't want to write a new line. I want to take the same line and put new values after <code>29-Dez,40,</code></p> ...
3
2008-11-29T20:41:28Z
328,196
<p>To expand on what <a href="http://stackoverflow.com/questions/327985/need-help-to-write-in-the-last-line-of-the-file#328007">Doug said</a>, in order to read the file contents into a data structure you can use the <a href="http://www.python.org/doc/2.5.2/lib/bltin-file-objects.html" rel="nofollow">readlines() method<...
1
2008-11-29T23:41:59Z
[ "python", "file" ]
How do I modify the last line of a file?
327,985
<p>The last line of my file is:</p> <blockquote> <p>29-dez,40,</p> </blockquote> <p>How can I modify that line so that it reads:</p> <blockquote> <p>29-Dez,40,90,100,50</p> </blockquote> <p>Note: I don't want to write a new line. I want to take the same line and put new values after <code>29-Dez,40,</code></p> ...
3
2008-11-29T20:41:28Z
339,388
<p>I recently wrote a script to do something very similar to this. It would traverse a project, find all module dependencies and add any missing import statements. I won't clutter this post up with the entire script, but I'll show how I went about modifying my files.</p> <pre><code>import os from mmap import mmap d...
0
2008-12-04T01:52:50Z
[ "python", "file" ]
wxpython: Updating a dict or other appropriate data type from wx.lib.sheet.CSheet object
328,003
<p>If I have a notebook with three spreadsheet widgets, what is the best way to have changes to the spreadsheet update a dictionary (or maybe an sqlite file?). Do all wx grid objects come with a built in dictionary related to the SetNumberRows and SetNumberCols? Basically I am looking for guidance on how to work with...
3
2008-11-29T21:00:12Z
328,078
<p>Use a <a href="http://docs.wxwidgets.org/stable/wx_wxgrid.html" rel="nofollow">wxGrid</a> with a <a href="http://docs.wxwidgets.org/stable/wx_wxgridtablebase.html" rel="nofollow">wxGridTableBase</a> instead</p> <p>Here is a simple example:</p> <pre><code>import wx, wx.grid class GridData(wx.grid.PyGridTableBase):...
4
2008-11-29T22:14:09Z
[ "python", "wxpython", "spreadsheet", "wx" ]
Create a List that contain each Line of a File
328,059
<p>I'm trying to open a file and create a list with each line read from the file.</p> <pre><code> i=0 List=[""] for Line in inFile: List[i]=Line.split(",") i+=1 print List </code></pre> <p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of ...
13
2008-11-29T21:55:53Z
328,066
<p>I am not sure about Python but most languages have push/append function for arrays.</p>
-5
2008-11-29T22:01:33Z
[ "python" ]
Create a List that contain each Line of a File
328,059
<p>I'm trying to open a file and create a list with each line read from the file.</p> <pre><code> i=0 List=[""] for Line in inFile: List[i]=Line.split(",") i+=1 print List </code></pre> <p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of ...
13
2008-11-29T21:55:53Z
328,068
<p>It's a lot easier than that:</p> <pre><code>List = open("filename.txt").readlines() </code></pre> <p>This returns a list of each line in the file.</p>
38
2008-11-29T22:03:34Z
[ "python" ]
Create a List that contain each Line of a File
328,059
<p>I'm trying to open a file and create a list with each line read from the file.</p> <pre><code> i=0 List=[""] for Line in inFile: List[i]=Line.split(",") i+=1 print List </code></pre> <p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of ...
13
2008-11-29T21:55:53Z
328,070
<pre><code>my_list = [line.split(',') for line in open("filename.txt")] </code></pre>
6
2008-11-29T22:06:14Z
[ "python" ]
Create a List that contain each Line of a File
328,059
<p>I'm trying to open a file and create a list with each line read from the file.</p> <pre><code> i=0 List=[""] for Line in inFile: List[i]=Line.split(",") i+=1 print List </code></pre> <p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of ...
13
2008-11-29T21:55:53Z
328,072
<p>A file is <em>almost</em> a list of lines. You can trivially use it in a <strong>for</strong> loop.</p> <pre><code>myFile= open( "SomeFile.txt", "r" ) for x in myFile: print x myFile.close() </code></pre> <p>Or, if you want an actual list of lines, simply create a list from the file.</p> <pre><code>myFile= o...
1
2008-11-29T22:06:39Z
[ "python" ]
Create a List that contain each Line of a File
328,059
<p>I'm trying to open a file and create a list with each line read from the file.</p> <pre><code> i=0 List=[""] for Line in inFile: List[i]=Line.split(",") i+=1 print List </code></pre> <p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of ...
13
2008-11-29T21:55:53Z
328,073
<p>f.readlines() returns a list that contains each line as an item in the list</p> <p>if you want eachline to be split(",") you can use list comprehensions</p> <pre><code>[ list.split(",") for line in file ] </code></pre>
1
2008-11-29T22:07:14Z
[ "python" ]
Create a List that contain each Line of a File
328,059
<p>I'm trying to open a file and create a list with each line read from the file.</p> <pre><code> i=0 List=[""] for Line in inFile: List[i]=Line.split(",") i+=1 print List </code></pre> <p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of ...
13
2008-11-29T21:55:53Z
328,074
<p>Please read <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>. You're swaying pretty far from python conventions.</p> <p>If you want a list of lists of each line split by comma, I'd do this:</p> <pre><code>l = [] for line in in_file: l.append(line.split(',')) </code></pre> <p>You'll ...
2
2008-11-29T22:07:40Z
[ "python" ]
Create a List that contain each Line of a File
328,059
<p>I'm trying to open a file and create a list with each line read from the file.</p> <pre><code> i=0 List=[""] for Line in inFile: List[i]=Line.split(",") i+=1 print List </code></pre> <p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of ...
13
2008-11-29T21:55:53Z
31,923,407
<p>I did it this way</p> <pre><code>lines_list = open('file.txt').read().splitlines() </code></pre> <p>Every line comes with its end of line characters (\n\r); this way the characters are removed.</p>
10
2015-08-10T15:22:21Z
[ "python" ]
How to make a surface with a transparent background in pygame
328,061
<p>Can someone give me some example code that creates a surface with a transparent background in pygame?</p>
18
2008-11-29T21:58:40Z
328,067
<p>This should do it:</p> <pre><code>image = pygame.Surface([640,480], pygame.SRCALPHA, 32) image = image.convert_alpha() </code></pre> <p>Make sure that the color depth (32) stays explicitly set else this will not work.</p>
20
2008-11-29T22:02:45Z
[ "python", "transparency", "pygame" ]
How to make a surface with a transparent background in pygame
328,061
<p>Can someone give me some example code that creates a surface with a transparent background in pygame?</p>
18
2008-11-29T21:58:40Z
353,739
<p>You can also give it a colorkey, much like GIF file transparency. This is the most common way to make sprites. The original bitmap has the artwork, and has a certain color as background that will not be drawn, which is the colorkey:</p> <pre><code>surf.set_colorkey((255,0,255)) // Sets the colorkey to that hideous ...
8
2008-12-09T18:24:22Z
[ "python", "transparency", "pygame" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
328,110
<p>Check if the cross product of <code>b-a</code> and <code>c-a</code> is<code>0</code>: that means all the points are collinear. If they are, check if <code>c</code>'s coordinates are between <code>a</code>'s and <code>b</code>'s. Use either the x or the y coordinates, as long as <code>a</code> and <code>b</code> are ...
24
2008-11-29T22:40:05Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
328,122
<p>Check if the <strong>cross product</strong> of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned.</p> <p>But, as you want to know if c is between a and b, you also have to check that the <strong>dot product</strong> of (b-a) and (c-a) is <em>positive</em> and is <em>less</e...
84
2008-11-29T22:46:45Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
328,126
<p>The scalar product between (c-a) and (b-a) must be equal to the product of their lengths (this means that the vectors (c-a) and (b-a) are aligned and with the same direction). Moreover, the length of (c-a) must be less than or equal to that of (b-a). Pseudocode:</p> <pre><code># epsilon = small constant def isBetw...
1
2008-11-29T22:51:43Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
328,142
<p>Here's another approach: </p> <ul> <li>Lets assume the two points be A (x1,y1) and B (x2,y2)</li> <li>The equation of the line passing through those points is (x-x1)/(y-y1)=(x2-x1)/(y2-y1) .. (just making equating the slopes)</li> </ul> <p>Point C (x3,y3) will lie between A &amp; B if:</p> <ul> <li>x3,y3 satisfi...
4
2008-11-29T23:05:55Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
328,154
<p>Using a more geometric approach, calculate the following distances:</p> <pre><code>ab = sqrt((a.x-b.x)**2 + (a.y-b.y)**2) ac = sqrt((a.x-c.x)**2 + (a.y-c.y)**2) bc = sqrt((b.x-c.x)**2 + (b.y-c.y)**2) </code></pre> <p>and test whether <strong>ac+bc</strong> equals <strong>ab</strong>:</p> <pre><code>is_on_segment ...
3
2008-11-29T23:14:32Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
328,193
<p>Here's how I'd do it:</p> <pre><code>def distance(a,b): return sqrt((a.x - b.x)**2 + (a.y - b.y)**2) def is_between(a,c,b): return distance(a,c) + distance(c,b) == distance(a,b) </code></pre>
26
2008-11-29T23:39:34Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
328,268
<p>Here's how I did it at school. I forgot why it is not a good idea.</p> <p>EDIT: </p> <p>@Darius Bacon: <a href="http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment#328110">cites a "Beautiful Code" book</a> which contains an explanation why the below...
1
2008-11-30T00:45:56Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
328,337
<p>The length of the segment is not important, thus using a square root is not required and should be avoided since we could lose some precision.</p> <pre><code>class Point: def __init__(self, x, y): self.x = x self.y = y class Segment: def __init__(self, a, b): self.a = a self...
6
2008-11-30T01:58:59Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
328,647
<p>Ok, lots of mentions of linear algebra (cross product of vectors) and this works in a real (ie continuous or floating point) space but the question specifically stated that the two points were expressed as <strong>integers</strong> and thus a cross product is not the correct solution although it can give an approxim...
3
2008-11-30T08:56:44Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
329,347
<p>how about just ensuring that the slope is the same and the point is between the others?</p> <p>given points (x1, y1) and (x2, y2) ( with x2 > x1) and candidate point (a,b)</p> <p>if (b-y1) / (a-x1) = (y2-y2) / (x2-x1) And x1 &lt; a &lt; x2 </p> <p>Then (a,b) must be on line between (x1,y1) and (x2, y2)</p>
0
2008-11-30T20:52:30Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
7,913,523
<p>Any point on the line segment (<strong>a</strong>, <strong>b</strong>) (where <strong>a</strong> and <strong>b</strong> are vectors) can be expressed as a <em>linear combination</em> of the two vectors <strong>a</strong> and <strong>b</strong>:</p> <p>In other words, if <strong>c</strong> lies on the line segment (...
0
2011-10-27T08:42:26Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
9,224,700
<p>c# From <a href="http://www.faqs.org/faqs/graphics/algorithms-faq/" rel="nofollow">http://www.faqs.org/faqs/graphics/algorithms-faq/</a> -> Subject 1.02: How do I find the distance from a point to a line?</p> <pre><code>Boolean Contains(PointF from, PointF to, PointF pt, double epsilon) { doubl...
0
2012-02-10T08:16:16Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
11,588,038
<p>I needed this for javascript for use in an html5 canvas for detecting if the users cursor was over or near a certain line. So I modified the answer given by Darius Bacon into coffeescript:</p> <pre><code>is_on = (a,b,c) -&gt; # "Return true if point c intersects the line segment from a to b." # (or the dege...
2
2012-07-20T23:08:11Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
13,323,946
<p>Here's a different way to go about it, with code given in C++. Given two points, l1 and l2 it's trivial to express the line segment between them as</p> <pre><code>l1 + A(l2 - l1) </code></pre> <p>where 0 &lt;= A &lt;= 1. This is known as the vector representation of a line if you're interested any more beyond just...
2
2012-11-10T16:48:59Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
19,633,299
<p>Here is some Java code that worked for me:</p> <pre><code>boolean liesOnSegment(Coordinate a, Coordinate b, Coordinate c) { double dotProduct = (c.x - a.x) * (c.x - b.x) + (c.y - a.y) * (c.y - b.y); if (dotProduct &lt; 0) return true; return false; } </code></pre>
1
2013-10-28T11:15:30Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
21,453,970
<p>An answer in C# using a Vector2D class</p> <pre><code>public static bool IsOnSegment(this Segment2D @this, Point2D c, double tolerance) { var distanceSquared = tolerance*tolerance; // Start of segment to test point vector var v = new Vector2D( @this.P0, c ).To3D(); // Segment vector var s =...
0
2014-01-30T10:34:14Z
[ "python", "math", "geometry" ]
How can you determine a point is between two other points on a line segment?
328,107
<p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p> <p>How can you determine if another point c is on the line segment defined by a and b?</p> <p>I use python most, but examples in any language would be helpful.</p>
67
2008-11-29T22:37:13Z
29,301,940
<p>You can use the wedge and dot product:</p> <pre><code>def dot(v,w): return v.x*w.x + v.y*w.y def wedge(v,w): return v.x*w.y - v.y*w.x def is_between(a,b,c): v = a - b w = b - c return wedge(v,w) == 0 and dot(v,w) &gt; 0 </code></pre>
0
2015-03-27T13:34:06Z
[ "python", "math", "geometry" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Be...
128
2008-11-30T02:28:04Z
328,374
<p><a href="http://pypi.python.org/pypi/webstemmer/0.5.0" rel="nofollow">http://pypi.python.org/pypi/webstemmer/0.5.0</a></p> <p><a href="http://atropine.sourceforge.net/documentation.html" rel="nofollow">http://atropine.sourceforge.net/documentation.html</a></p> <p><hr /></p> <p>alternatively, i think you can drive...
4
2008-11-30T02:57:12Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Be...
128
2008-11-30T02:28:04Z
328,389
<p><a href="http://www.aaronsw.com/2002/html2text/">html2text</a> is a Python program that does a pretty good job at this.</p>
69
2008-11-30T03:23:58Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Be...
128
2008-11-30T02:28:04Z
328,969
<p>PyParsing does a great job. Paul McGuire has several scrips that are easy to adopt for various uses on the pyparsing wiki. (<a href="http://pyparsing.wikispaces.com/Examples">http://pyparsing.wikispaces.com/Examples</a>) One reason for investing a little time with pyparsing is that he has also written a very brief ...
6
2008-11-30T15:46:19Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Be...
128
2008-11-30T02:28:04Z
1,463,802
<p>You can use html2text method in the stripogram library also.</p> <pre><code>from stripogram import html2text text = html2text(your_html_string) </code></pre> <p>To install stripogram run sudo easy_install stripogram</p>
8
2009-09-23T03:21:58Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Be...
128
2008-11-30T02:28:04Z
3,987,802
<p>Found myself facing just the same problem today. I wrote a very simple HTML parser to strip incoming content of all markups, returning the remaining text with only a minimum of formatting.</p> <pre><code>from HTMLParser import HTMLParser from re import sub from sys import stderr from traceback import print_exc cla...
46
2010-10-21T13:14:38Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Be...
128
2008-11-30T02:28:04Z
8,201,491
<p><strong>NOTE:</strong> NTLK no longer supports <code>clean_html</code> function</p> <p>Original answer below.</p> <hr> <p>Use <a href="https://pypi.python.org/pypi/nltk">NLTK</a> </p> <p>I wasted my 4-5 hours fixing the issues with html2text. Luckily i could encounter NLTK.<br> It works magically. </p> <pr...
88
2011-11-20T12:34:09Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Be...
128
2008-11-30T02:28:04Z
9,357,137
<p>Instead of the HTMLParser module, check out htmllib. It has a similar interface, but does more of the work for you. (It is pretty ancient, so it's not much help in terms of getting rid of javascript and css. You could make a derived class, but and add methods with names like start_script and end_style (see the py...
4
2012-02-20T06:39:50Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Be...
128
2008-11-30T02:28:04Z
10,650,566
<p>This isn't exactly a Python solution, but it will convert text Javascript would generate into text, which I think is important (E.G. google.com). The browser Links (not Lynx) has a Javascript engine, and will convert source to text with the -dump option.</p> <p>So you could do something like:</p> <pre><code>fname ...
4
2012-05-18T10:02:26Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Be...
128
2008-11-30T02:28:04Z
13,633,210
<p>There is Pattern library for data mining.</p> <p><a href="http://www.clips.ua.ac.be/pages/pattern-web">http://www.clips.ua.ac.be/pages/pattern-web</a></p> <p>You can even decide what tags to keep:</p> <pre><code>s = URL('http://www.clips.ua.ac.be').download() s = plaintext(s, keep={'h1':[], 'h2':[], 'strong':[], ...
6
2012-11-29T19:28:38Z
[ "python", "html", "text", "html-content-extraction" ]