title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Casting an int to a string in Python
3,944,876
25
2010-10-15T18:08:49Z
3,944,897
57
2010-10-15T18:10:59Z
[ "python", "string", "integer", "concatenation" ]
I want to be able to generate a number of text files with the names fileX.txt where X is some integer: ``` for i in range(key): filename = "ME" + i + ".txt" //Error here! Can't concat a string and int filenum = filename filenum = open(filename , 'w') ``` Does anyone else know how to do the filename = "ME"...
``` x = 1 y = "foo" + str(x) ``` Please read the Python documentation: <http://docs.python.org/>
Why is executemany slow in Python MySQLdb?
3,945,642
12
2010-10-15T19:55:27Z
3,945,860
18
2010-10-15T20:25:58Z
[ "python", "sql", "mysql", "performance" ]
I am developing a program in Python that accesses a MySQL database using MySQLdb. In certain situations, I have to run an INSERT or REPLACE command on many rows. I am currently doing it like this: ``` db.execute("REPLACE INTO " + table + " (" + ",".join(cols) + ") VALUES" + ",".join(["(" + ",".join(["%s"] * len(co...
Try lowercasing the word 'values' in your query - this appears to be a bug/regression in MySQL-python 1.2.3. MySQL-python's implementation of executemany() matches the VALUES clause with a regular expression and then just clones the list of values for each row of data, so you end up executing exactly the same query as...
Find a specific tag with BeautifulSoup
3,945,750
7
2010-10-15T20:11:02Z
3,945,764
14
2010-10-15T20:13:04Z
[ "python", "beautifulsoup" ]
I can traverse generic tags easily with BS, but I don't know how to find specific tags. For example, how can I find all occurances of `<div style="width=300px;">`? Is this possible with BS?
The following should work ``` soup = BeautifulSoup(htmlstring) soup.findAll('div', style="width=300px;") ``` There are couple of ways to search for tags. * <http://www.crummy.com/software/BeautifulSoup/documentation.html> For more text to understand and use it * <http://lxml.de/elementsoup.html>
Converting string to tuple and adding to tuple
3,945,856
4
2010-10-15T20:25:13Z
3,945,883
9
2010-10-15T20:29:12Z
[ "python", "string", "tuples" ]
I have a config file like this. ``` [rects] rect1=(2,2,10,10) rect2=(12,8,2,10) ``` I need to loop through the values and convert them to tuples. I then need to make a tuple of the tuples like ``` ((2,2,10,10), (12,8,2,10)) ```
To turn the strings into tuples of ints (which is, I assume, what you want), you can use a regex like this: ``` x = "(1,2,3)" t = tuple(int(v) for v in re.findall("[0-9]+", x)) ``` And you can use, say, [configparser](http://docs.python.org/library/configparser.html) to parse the config file.
Converting string to tuple and adding to tuple
3,945,856
4
2010-10-15T20:25:13Z
3,946,174
10
2010-10-15T21:11:54Z
[ "python", "string", "tuples" ]
I have a config file like this. ``` [rects] rect1=(2,2,10,10) rect2=(12,8,2,10) ``` I need to loop through the values and convert them to tuples. I then need to make a tuple of the tuples like ``` ((2,2,10,10), (12,8,2,10)) ```
Instead of using a regex or int/string functions, you could also use the `ast` module's `literal_eval` function, which only evaluates strings that are valid Python literals. This function is safe (according to the docs). <http://docs.python.org/library/ast.html#ast.literal_eval> ``` import ast ast.literal_eval("(1,2,3...
Passing self into a constructor in python
3,945,924
6
2010-10-15T20:35:01Z
3,945,938
11
2010-10-15T20:36:46Z
[ "python", "this", "self" ]
I recently was working on a little python project and came to a situation where I wanted to pass `self` into the constructor of another object. I'm not sure why, but I had to look up whether this was legal in python. I've done this many times in C++ and Java but I don't remember ever having to do this with python. Is ...
Yes it is legal, and yes it is pythonic. I find myself using this pattern when you have an object and a container object where the contained objects need to know about their parent.
What to consider before subclassing list?
3,945,940
12
2010-10-15T20:37:00Z
3,945,953
8
2010-10-15T20:39:26Z
[ "python", "list", "subclassing" ]
I was recently going over a coding problem I was having and someone looking at the code said that subclassing list was bad (my problem was unrelated to that class). He said that you shouldn't do it and that it came with a bunch of bad side effects. Is this true? I'm asking if list is generally bad to subclass and if s...
I think the first question I'd ask myself is, "Is my new object really a list?". Does it walk like a list, talk like a list? Or is is something else? If it is a list, then all the standard list methods should all make sense. If the standard list methods don't make sense, then your object should contain a list, not be...
What to consider before subclassing list?
3,945,940
12
2010-10-15T20:37:00Z
3,946,067
12
2010-10-15T20:57:04Z
[ "python", "list", "subclassing" ]
I was recently going over a coding problem I was having and someone looking at the code said that subclassing list was bad (my problem was unrelated to that class). He said that you shouldn't do it and that it came with a bunch of bad side effects. Is this true? I'm asking if list is generally bad to subclass and if s...
The [abstract base classes](http://docs.python.org/glossary.html#term-abstract-base-class) provided in the [`collections`](http://docs.python.org/library/collections.html#abcs-abstract-base-classes) module, particularly `MutableSequence`, can be useful when implementing list-like classes. These are available in Python ...
What to consider before subclassing list?
3,945,940
12
2010-10-15T20:37:00Z
3,946,763
14
2010-10-15T23:02:18Z
[ "python", "list", "subclassing" ]
I was recently going over a coding problem I was having and someone looking at the code said that subclassing list was bad (my problem was unrelated to that class). He said that you shouldn't do it and that it came with a bunch of bad side effects. Is this true? I'm asking if list is generally bad to subclass and if s...
**There are no benefits to subclassing `list`.** None of the methods will use any methods you override, so you can have unexpected bugs. Further, it's very often confusing doing things like `self.append` instead of `self.foos.append` or especially `self[4]` rather than `self.foos[4]` to access your data. You can make s...
How do I update an instance of a Django Model with request.POST if POST is a nested array?
3,946,036
4
2010-10-15T20:51:43Z
3,946,186
17
2010-10-15T21:12:39Z
[ "python", "django", "post", "django-models", "request" ]
I have a form that submits the following data: ``` question[priority] = "3" question[effort] = "5" question[question] = "A question" ``` That data is submitted to the URL /questions/1/save where `1` is the `question.id`. What I'd love to do is get question #1 and update it based on the POST data. I've got some of it ...
You can use a [ModelForm](http://docs.djangoproject.com/en/dev/topics/forms/modelforms/) to accomplish this. First define the ModelForm: ``` from django import forms class QuestionForm(forms.ModelForm): class Meta: model = Question ``` Then, in your view: ``` question = Question.objects.get(pk=id) if re...
Python equivalent to Java's BitSet
3,946,086
16
2010-10-15T20:59:46Z
3,946,103
12
2010-10-15T21:02:45Z
[ "java", "python", "bitset" ]
Is there a Python class or module that implements a structure that is similar to the BitSet?
There's nothing in the standard library. Try: <http://pypi.python.org/pypi/bitarray>
Migrating from Stata to Python
3,946,219
9
2010-10-15T21:16:45Z
3,946,774
7
2010-10-15T23:05:33Z
[ "python", "statistics", "numpy", "stata" ]
Some coworkers who have been struggling with Stata 11 are asking for my help to try to automate their laborious work. They mainly use 3 commands in Stata: > tsset (sets a time series analysis) as in: `tsset year_column, yearly` > varsoc (Obtain lag-order selection statistics for VARs) as in: `varsoc column_a column...
I believe both [scikits.timeseries](http://pytseries.sourceforge.net/) and [econpy / pytrix](http://code.google.com/p/econpy/) implement vector autoregression methods, but I haven't put either through their paces.
Randomise order of if-else execution in Python
3,946,488
3
2010-10-15T22:04:29Z
3,946,512
11
2010-10-15T22:10:45Z
[ "python", "random" ]
This might sound like a strange question, but bear with me... I have a dictionary in Python with values like so: ``` 'B': 23.6 'D': 0.6 'F': 35.9 'H': 35.9 ``` I need to do an if-else with these values to do different things depending which one is > 30. The code I have at the moment is along the lines of: ``` if an...
You can make a sequence of key/value pairs: ``` pairs = angles.iteritems() ``` Filter it to remove elements <= 30: ``` filtered = [(name, value) for name, value in pairs if value > 30] ``` check to see if there are any options ``` if filtered: ``` and then pick one: ``` from random import choice name, va...
Does python urllib2 automatically uncompress gzip data fetched from webpage?
3,947,120
56
2010-10-16T00:45:48Z
3,947,241
123
2010-10-16T01:21:48Z
[ "python", "gzip", "urllib2" ]
I'm using ``` data=urllib2.urlopen(url).read() ``` I want to know: 1. How can I tell if the data at a URL is gzipped? 2. Does urllib2 automatically uncompress the data if it is gzipped? Will the data always be a string?
> 1. How can I tell if the data at a URL is gzipped? This checks if the content is gzipped and decompresses it: ``` from StringIO import StringIO import gzip request = urllib2.Request('http://example.com/') request.add_header('Accept-encoding', 'gzip') response = urllib2.urlopen(request) if response.info().get('Cont...
Does python urllib2 automatically uncompress gzip data fetched from webpage?
3,947,120
56
2010-10-16T00:45:48Z
3,947,262
7
2010-10-16T01:28:21Z
[ "python", "gzip", "urllib2" ]
I'm using ``` data=urllib2.urlopen(url).read() ``` I want to know: 1. How can I tell if the data at a URL is gzipped? 2. Does urllib2 automatically uncompress the data if it is gzipped? Will the data always be a string?
If you are talking about a simple `.gz` file, no, urllib2 will not decode it, you will get the unchanged `.gz` file as output. If you are talking about automatic HTTP-level compression using `Content-Encoding: gzip` or `deflate`, then that has to be deliberately requested by the client using an `Accept-Encoding` heade...
Python script to loop through all files in directory, delete any that are less than 200 kB in size
3,947,313
29
2010-10-16T01:46:42Z
3,947,323
58
2010-10-16T01:52:30Z
[ "python" ]
I want to delete all files in a folder that are less than 200 kB in size. Just want to be sure here, when i do a ls -la on my macbook, the file size says 171 or 143, I am assuming this is kb correct?
This does directory and all subdirectories: ``` import os, os.path for root, _, files in os.walk(dirtocheck): for f in files: fullpath = os.path.join(root, f) if os.path.getsize(fullpath) < 200 * 1024: os.remove(fullpath) ``` Or: ``` import os, os.path fileiter = (os.path.join(root,...
Python script to loop through all files in directory, delete any that are less than 200 kB in size
3,947,313
29
2010-10-16T01:46:42Z
3,947,353
32
2010-10-16T02:03:20Z
[ "python" ]
I want to delete all files in a folder that are less than 200 kB in size. Just want to be sure here, when i do a ls -la on my macbook, the file size says 171 or 143, I am assuming this is kb correct?
you can also use `find` ``` find /path -type f -size -200k -delete ```
Python script to loop through all files in directory, delete any that are less than 200 kB in size
3,947,313
29
2010-10-16T01:46:42Z
12,355,420
27
2012-09-10T16:05:21Z
[ "python" ]
I want to delete all files in a folder that are less than 200 kB in size. Just want to be sure here, when i do a ls -la on my macbook, the file size says 171 or 143, I am assuming this is kb correct?
You could also use ``` import os files_in_dir = os.listdir(path_to_dir) for file_in_dir in files_in_dir: #do the check you need on each file ```
Spliting a long tuple into smaller tuples
3,947,337
8
2010-10-16T01:56:53Z
3,947,354
7
2010-10-16T02:03:53Z
[ "python", "list", "split", "tuples" ]
I have a long tuple like ``` (2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10) ``` and i am trying to split it into a tuple of tuples like ``` ((2, 2, 10, 10), (344, 344, 45, 43), (2, 2, 10, 10), (12, 8, 2, 10)) ``` I am new to python and am not very good with tuples o(2, 2, 10, 10, 344, 344, 45, 43, 2, ...
Well there is a certain idiom for that: ``` def grouper(n, iterable): args = [iter(iterable)] * n return zip(*args) t = (2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10) print grouper(4, t) ``` But its kind of complicated to explain. A slightly more general version of this is listed in [the iterto...
Python - removing items from lists
3,947,654
8
2010-10-16T04:16:08Z
3,947,666
10
2010-10-16T04:22:10Z
[ "python", "list-comprehension" ]
``` # I have 3 lists: L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] L2 = [4, 7, 8] L3 = [5, 2, 9] # I want to create another that is L1 minus L2's memebers and L3's memebers, so: L4 = (L1 - L2) - L3 # Of course this isn't going to work ``` I'm wondering, what is the "correct" way to do this. I can do it many different ways, but P...
Here are some tries: ``` L4 = [ n for n in L1 if (n not in L2) and (n not in L3) ] # parens for clarity tmpset = set( L2 + L3 ) L4 = [ n for n in L1 if n not in tmpset ] ``` Now that I have had a moment to think, I realize that the `L2 + L3` thing creates a temporary list that immediately gets thrown away. So an ev...
Python indentation when adding looping statements to existing code
3,948,257
2
2010-10-16T09:07:35Z
3,948,270
10
2010-10-16T09:09:12Z
[ "python", "indentation", "python-idle" ]
In Python, what do you do when you write 100 lines of code and forget to add a bunch of loop statements somewhere? I mean, if you add a while statement somewhere, you've to now indent all the lines below it. It's not like you can just put braces and be done with it. Go to every single line and add tabs/spaces. What if...
I think every serious editor or IDE supports the option to select multiple lines and press tab to indent or Shift-Tab to unindent all that lines.
How to keep all my django applications in specific folder
3,948,356
19
2010-10-16T09:42:14Z
3,948,368
11
2010-10-16T09:45:28Z
[ "python", "django", "django-apps" ]
I have a Django project, let's say "project1". Typical folder structure for applications is: ``` /project1/ /app1/ /app2/ ... __init__.py manage.py settings.py urls.py ``` What should I do if I want to hold all of my applications in some separate folder, ...
You can do this very easily, but you need to change the `settings.py` to look like this: ``` INSTALLED_APPS = ( 'apps.app1', 'apps.app2', # ... ) ``` And your `urls.py` to look like this: ``` urlpatterns = patterns('', (r'^app1/',include('apps.app1')), (r'^app2/',include('apps.app2')), )...
How to keep all my django applications in specific folder
3,948,356
19
2010-10-16T09:42:14Z
3,948,821
33
2010-10-16T12:09:02Z
[ "python", "django", "django-apps" ]
I have a Django project, let's say "project1". Typical folder structure for applications is: ``` /project1/ /app1/ /app2/ ... __init__.py manage.py settings.py urls.py ``` What should I do if I want to hold all of my applications in some separate folder, ...
You can add your `apps` folder to your python path by inserting the following in your `settings.py`: ``` import os import sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps')) ``` Then you can use all the apps in this folder just in the same way as they were in your proj...
Is is possible to read a file from S3 in Google App Engine using boto?
3,948,391
7
2010-10-16T09:52:44Z
3,957,908
7
2010-10-18T09:32:11Z
[ "python", "google-app-engine", "amazon-s3", "amazon-web-services", "boto" ]
I want to manipulate a pickled python object stored in S3 in Google App Engine's sandbox. I use the suggestion in boto's [documentation](http://code.google.com/p/boto/wiki/LookupKey): ``` from boto.s3.connection import S3Connection from boto.s3.key import Key conn = S3Connection(config.key, config.secret_key) bucket...
You don't need to write to a file or a StringIO at all. You can call `key.get_contents_as_string()` to return the key's contents as a string. The docs for key are [here](http://boto.cloudhackers.com/ref/s3.html#module-boto.s3.key).
Prevent function overriding in Python
3,948,873
5
2010-10-16T12:25:00Z
3,948,937
9
2010-10-16T12:43:30Z
[ "python" ]
Is there any way I can prevent a child class from overriding a method in the base class? My guess is that there is not, but I'm coming from the .NET world, and I'm trying to make my API as robust as possible, so any input is greatly appreciated. ``` class Parent: def do_something(self): '''This is where s...
You are right: what you are attempting is contrary to Python's structure and its culture. Document your API, and educate your users how to use it. It's their program, so if they still want to override your function, who are you to prevent them?
Python if statement: False vs. 0.0
3,948,877
5
2010-10-16T12:25:30Z
3,948,887
11
2010-10-16T12:29:14Z
[ "python", "if-statement" ]
Is it possible to: ``` for k,v in kwargs.items() if v == None or v == '' or v == 1.0 or v == False: del kwargs[k] ``` without deleting the key if v == 0.0? (False seems to equal 0.0), and without deleting the keys who equal True.
You should use `v is False` instead of `v == False`. The same applies for your comparison to `None`. See [PEP 8 - Style Guide for Python](http://www.python.org/dev/peps/pep-0008/): > Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators.
Python if statement: False vs. 0.0
3,948,877
5
2010-10-16T12:25:30Z
3,949,048
10
2010-10-16T13:21:02Z
[ "python", "if-statement" ]
Is it possible to: ``` for k,v in kwargs.items() if v == None or v == '' or v == 1.0 or v == False: del kwargs[k] ``` without deleting the key if v == 0.0? (False seems to equal 0.0), and without deleting the keys who equal True.
Or you can put it like this : ``` if v in (None, '', 1.0) or v is False: ```
Why store sessions on the server instead of inside a cookie?
3,948,975
7
2010-10-16T12:57:37Z
3,949,032
14
2010-10-16T13:16:29Z
[ "python", "session", "cookies", "flask" ]
I have been using Flask for some time now and I am really enjoying the framework. One thing that I fail to understand is that in almost all other places they talk about storing the session on the server and the session id on the client, which would then identify the session. However after using flask, I dont feel the n...
Even if your data is encrypted, the user could still roll back their cookie to a previous state (unless you start encoding one-time IDs etc) e.g. cookie says the user has 100 credits, user spends 100 credits, they get a new cookie saying they have 0 credits. They could then restore their previous cookie (with 100 cred...
Calculating Pearson correlation and significance in Python
3,949,226
79
2010-10-16T14:15:27Z
3,949,282
107
2010-10-16T14:29:57Z
[ "python", "numpy", "statistics", "scipy" ]
I am looking for a function that takes as input two lists, and returns the [Pearson correlation](http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient), and the significance of the correlation.
You can have a look at scipy: <http://docs.scipy.org/doc/scipy/reference/stats.html> ``` from pydoc import help from scipy.stats.stats import pearsonr help(pearsonr) >>> Help on function pearsonr in module scipy.stats.stats: pearsonr(x, y) Calculates a Pearson correlation coefficient and the p-value for testing no...
Calculating Pearson correlation and significance in Python
3,949,226
79
2010-10-16T14:15:27Z
3,949,533
10
2010-10-16T15:39:51Z
[ "python", "numpy", "statistics", "scipy" ]
I am looking for a function that takes as input two lists, and returns the [Pearson correlation](http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient), and the significance of the correlation.
Just for completeness, you can call R's statistical functions from Python using the rpy Python package. Probably overkill if all you want is the Pearson stat, but if you then want to go on and do lots of stats things that you can't find in the Python packages in other answers here, rpy might be the way to go. www.r-pr...
Calculating Pearson correlation and significance in Python
3,949,226
79
2010-10-16T14:15:27Z
5,713,856
24
2011-04-19T08:52:33Z
[ "python", "numpy", "statistics", "scipy" ]
I am looking for a function that takes as input two lists, and returns the [Pearson correlation](http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient), and the significance of the correlation.
If you don't feel like installing scipy, I've used this quick hack, slightly modified from [Programming Collective Intelligence](http://oreilly.com/catalog/9780596529321): (Edited for correctness.) ``` from itertools import imap def pearsonr(x, y): # Assume len(x) == len(y) n = len(x) sum_x = float(sum(x)) s...
Calculating Pearson correlation and significance in Python
3,949,226
79
2010-10-16T14:15:27Z
7,939,259
17
2011-10-29T13:42:11Z
[ "python", "numpy", "statistics", "scipy" ]
I am looking for a function that takes as input two lists, and returns the [Pearson correlation](http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient), and the significance of the correlation.
The following code is a straight-up interpretation of [the definition](http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#Definition): ``` import math def average(x): assert len(x) > 0 return float(sum(x)) / len(x) def pearson_def(x, y): assert len(x) == len(y) n = len(x) ...
Calculating Pearson correlation and significance in Python
3,949,226
79
2010-10-16T14:15:27Z
16,026,737
47
2013-04-16T00:17:58Z
[ "python", "numpy", "statistics", "scipy" ]
I am looking for a function that takes as input two lists, and returns the [Pearson correlation](http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient), and the significance of the correlation.
The Pearson correlation can be calculated with numpy's [`corrcoef`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html). ``` import numpy numpy.corrcoef(list1, list2)[0, 1] ```
Calculating Pearson correlation and significance in Python
3,949,226
79
2010-10-16T14:15:27Z
17,389,980
8
2013-06-30T11:39:34Z
[ "python", "numpy", "statistics", "scipy" ]
I am looking for a function that takes as input two lists, and returns the [Pearson correlation](http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient), and the significance of the correlation.
Rather than rely on numpy/scipy, I think my answer should be the easiest to code and **understand the steps** in calculating the Pearson Correlation Coefficient (PCC) . ``` import math # calculates the mean def mean(x): sum = 0.0 for i in x: sum += i return sum / len(x) # calculates the sample ...
How is set() implemented?
3,949,310
57
2010-10-16T14:39:00Z
3,949,350
48
2010-10-16T14:47:43Z
[ "python", "data-structures", "set", "cpython" ]
I've seen people say that `set` objects in python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure does it use? What other implications does that implementation have? Every answer here was really enlightening, but I can only accept one, so I'll go with the c...
According to [this thread](http://groups.google.com/group/comp.lang.python/browse_thread/thread/e3e9dfdb5cbe33c8/83361c0f975add77?lnk=raot&pli=1): > Indeed, CPython's sets are implemented as something like dictionaries > with dummy values (the keys being the members of the set), with some > optimization(s) that exploi...
How is set() implemented?
3,949,310
57
2010-10-16T14:39:00Z
3,949,389
11
2010-10-16T14:57:26Z
[ "python", "data-structures", "set", "cpython" ]
I've seen people say that `set` objects in python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure does it use? What other implications does that implementation have? Every answer here was really enlightening, but I can only accept one, so I'll go with the c...
I think its a common mistake, `set` lookup (or hashtable for that matter) are not O(1). [from the Wikipedia](http://en.wikipedia.org/wiki/Hash_table#Performance_analysis) > In the simplest model, the hash function is completely unspecified and the table does not resize. For the best possible choice of hash function,...
How is set() implemented?
3,949,310
57
2010-10-16T14:39:00Z
3,949,397
9
2010-10-16T14:59:38Z
[ "python", "data-structures", "set", "cpython" ]
I've seen people say that `set` objects in python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure does it use? What other implications does that implementation have? Every answer here was really enlightening, but I can only accept one, so I'll go with the c...
We all have easy access to [the source](http://svn.python.org/view/python/trunk/Objects/setobject.c?view=markup), where the comment preceding `set_lookkey()` says: ``` /* The basic lookup function used by all operations. This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4. Open addressing is preferred over chaini...
How is set() implemented?
3,949,310
57
2010-10-16T14:39:00Z
3,949,795
47
2010-10-16T16:47:12Z
[ "python", "data-structures", "set", "cpython" ]
I've seen people say that `set` objects in python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure does it use? What other implications does that implementation have? Every answer here was really enlightening, but I can only accept one, so I'll go with the c...
When people say sets have O(1) membership-checking, they are talking about the **average** case. In the **worst** case (when all hashed values collide) membership-checking is O(n). See the [Python wiki on time complexity](http://wiki.python.org/moin/TimeComplexity). The [Wikipedia article](http://en.wikipedia.org/wiki...
Python http download page source
3,949,744
3
2010-10-16T16:33:48Z
3,949,760
10
2010-10-16T16:36:21Z
[ "python", "http" ]
hello there i was wondering if it was possible to connect to a http host (I.e. for example google.com) and download the source of the webpage? Thanks in advance.
> **Using urllib2 to download a page.** *Google will block this request as it will try to block all robots. Add user-agent to the request.* ``` import urllib2 user_agent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3' headers = { 'User-...
How to get the screen size in Tkinter?
3,949,844
9
2010-10-16T17:02:02Z
3,949,983
32
2010-10-16T17:33:27Z
[ "python", "tkinter" ]
I would like to know if it is possible to calculate the screen size using tkinter. I wanted this so that can make the program open up in the center of the screen...
``` import tkinter as tk root = tk.Tk() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() ```
Round with integer division
3,950,372
14
2010-10-16T19:15:39Z
3,950,960
22
2010-10-16T21:53:55Z
[ "python", "rounding", "integer-division" ]
Is there is a simple, pythonic way of rounding to the nearest whole number without using floating point? I'd like to do the following but with integer arithmetic: ``` skip = int(round(1.0 * total / surplus)) ``` ============== @John: Floating point is not reproducible across platforms. If you want your code to pass ...
You can do this quite simply: `(n + d // 2) // d`, where `n` is the dividend and `d` is the divisor. Alternatives like `(((n << 1) // d) + 1) >> 1` or the equivalent `(((n * 2) // d) + 1) // 2` may be SLOWER in recent CPythons, where an `int` is implemented like the old `long`. The simple method does 3 variable acce...
How to find out the current widget size in tkinter?
3,950,687
7
2010-10-16T20:39:03Z
3,950,766
17
2010-10-16T20:58:29Z
[ "python", "tkinter" ]
I'm using *Python* and *Tkinter*, and I need to know the current dimensions (width, height) of a widget. I've tried `somewidget["width"]`, but it returns only a fixed value, and is not updated whenever the widget size changes (e.g. when the window is resized).
Use `somewidget.winfo_width()` and `somewidget.winfo_height()` to get the actual widget size, the `somewidget['width']` property is only a hint given to the geometry manager.
Safe way to uninstall old version of python
3,950,819
9
2010-10-16T21:11:55Z
3,951,177
8
2010-10-16T22:56:25Z
[ "python", "osx", "installation" ]
I want to update my Python framework on Mac and delete the old versions but I am not sure if is safe to ``` rm -fr /Library/Frameworks/Python.framework/Versions/2.4 - 2.5 - 2.6 -3.0 etc. ``` Any suggestion?
Yes, it's safe. The Mac's system python's are in `/System/Library/...`. .dmg's downloaded and installed from python.org are placed in `/Library/...`. Don't delete the /System ones, but the /Library ones are user installed, so they should be safe to delete.
How to change email account details in appcfg.py google appengine SDK
3,951,089
9
2010-10-16T22:29:28Z
3,951,193
31
2010-10-16T23:03:47Z
[ "python", "google-app-engine" ]
I have hosted GAE apps with two different email ids! When i first time used appcfg.py to `update` my app then it prompted me for email id and password but later it doesnot. How to i change the saved email id and password? I tried to use `--email=` flag with appcfg.py, but it dint worked.
Use the `--no_cookies` flag, e.g.: ``` python2.5 /path/to/google_appengine/appcfg.py --no_cookies update myapp ``` From [the documentation](http://code.google.com/appengine/docs/python/tools/uploadinganapp.html): > --no\_cookies > > Do not store the administrator sign-in credentials as a cookie; > prompt for a passw...
How to replace the first occurrence of a regular expression in Python?
3,951,660
16
2010-10-17T01:57:33Z
3,951,684
23
2010-10-17T02:03:45Z
[ "python", "regex", "search", "replace" ]
I want to replace just the first occurrence of a regular expression in a string. Is there a convenient way to do this?
[`re.sub()`](http://docs.python.org/library/re.html#re.sub) has a `count` parameter that indicates how many substitutions to perform. You can just set that to 1: ``` >>> s = "foo foo foofoo foo" >>> re.sub("foo", "bar", s, 1) 'bar foo foofoo foo' >>> s = "baz baz foo baz foo baz" >>> re.sub("foo", "bar", s, 1) 'baz ba...
How do you dynamically identify unknown delimiters in a data file?
3,952,132
8
2010-10-17T05:19:37Z
3,952,193
34
2010-10-17T05:53:00Z
[ "python", "parsing", "csv", "text-files", "textinput" ]
I have three input data files. Each uses a different delimiter for the data contained therein. Data file one looks like this: ``` apples | bananas | oranges | grapes ``` data file two looks like this: ``` quarter, dime, nickel, penny ``` data file three looks like this: ``` horse cow pig chicken goat ``` (the cha...
How about trying Python CSV's standard: <http://docs.python.org/library/csv.html#csv.Sniffer> ``` import csv sniffer = csv.Sniffer() dialect = sniffer.sniff('quarter, dime, nickel, penny') print dialect.delimiter # returns ',' ```
Get available modules
3,952,513
29
2010-10-17T08:13:40Z
3,952,562
8
2010-10-17T08:37:18Z
[ "python" ]
With PHP you have the [`phpinfo()`](http://php.net/manual/en/function.phpinfo.php) which lists installed modules and then from there look up what they do. Is there a way to see what packages/modules are installed to import?
If you use [`ipython`](http://ipython.scipy.org/), which is an improved interactive Python shell (aka "[REPL](http://en.wikipedia.org/wiki/REPL)"), you can type `importÂ` (note the space at the end) followed by a press of the `[TAB]` key to get a list of importable modules. As noted in [this SO post](http://stackoverf...
Get available modules
3,952,513
29
2010-10-17T08:13:40Z
3,952,570
45
2010-10-17T08:40:26Z
[ "python" ]
With PHP you have the [`phpinfo()`](http://php.net/manual/en/function.phpinfo.php) which lists installed modules and then from there look up what they do. Is there a way to see what packages/modules are installed to import?
Type `help()` in the interpreter then ``` To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". ...
python and sqlite - escape input
3,952,543
4
2010-10-17T08:27:55Z
3,952,550
18
2010-10-17T08:30:55Z
[ "python", "sqlite", "pysqlite" ]
Using python with a sqlite DB - whats the method used for escaping the data going out and pulling the data coming out? Using pysqlite2 Google has conflicting suggestions.
Use the second parameter `args` to pass arguments; don't do the escaping yourself. Not only is this easier, it also helps prevent SQL injection attacks. ``` cursor.execute(sql,args) ``` for example, ``` cursor.execute('INSERT INTO foo VALUES (?, ?)', ("It's okay", "No escaping necessary") ```
Extra output none while printing an command line argument
3,953,233
6
2010-10-17T12:36:08Z
3,953,245
12
2010-10-17T12:37:55Z
[ "python", "function" ]
It's my day 1 of learning python. so it's a noob question for many of you. See the following code: ``` #!/usr/bin/env python import sys def hello(name): name = name + '!!!!' print 'hello', name def main(): print hello(sys.argv[1]) if __name__ == '__main__': main() ``` when I run it ``` $ ./Pytho...
Count the number of `print` statements in your code. You'll see that you're printing `"hello alice!!!"` in the `hello` function, *and* printing the result of the `hello` function. Because the `hello` function doesn't return a value (which you'd do with the `return` statement), it ends up returning the object `None`. Yo...
Get a sub-set of a Python dictionary
3,953,371
34
2010-10-17T13:25:25Z
3,953,386
33
2010-10-17T13:28:58Z
[ "python", "dictionary" ]
I have a dictionary: ``` {'key1':1, 'key2':2, 'key3':3} ``` I need to pass a sub-set of that dictionary to third-party code. It only wants a dictionary containing keys `['key1', 'key2', 'key99']` and if it gets another key (eg `'key3'`), it explodes in a nasty mess. The code in question is out of my control so I'm le...
``` In [38]: adict={'key1':1, 'key2':2, 'key3':3} In [41]: dict((k,adict[k]) for k in ('key1','key2','key99') if k in adict) Out[41]: {'key1': 1, 'key2': 2} ``` In Python3 (or Python2.7 or later) you can do it with a [dict-comprehension](http://diveintopython3.org/comprehensions.html#dictionarycomprehension) too: ```...
Get a sub-set of a Python dictionary
3,953,371
34
2010-10-17T13:25:25Z
3,953,389
14
2010-10-17T13:29:20Z
[ "python", "dictionary" ]
I have a dictionary: ``` {'key1':1, 'key2':2, 'key3':3} ``` I need to pass a sub-set of that dictionary to third-party code. It only wants a dictionary containing keys `['key1', 'key2', 'key99']` and if it gets another key (eg `'key3'`), it explodes in a nasty mess. The code in question is out of my control so I'm le...
``` dict(filter(lambda i:i[0] in validkeys, d.iteritems())) ```
Python Fibonacci Generator
3,953,749
9
2010-10-17T15:00:53Z
3,953,760
23
2010-10-17T15:03:18Z
[ "python", "fibonacci", "naming-conventions" ]
I need to make a program that asks for the amount of fibonacci numbers printed and then prints them like 0, 1, 1, 2... but I cant get it to work. My code looks the following: ``` a = int(raw_input('Give amount: ')) def fib(): a, b = 0, 1 while 1: yield a a, b = b, a + b a = fib() a.next() 0 f...
You are giving `a` too many meanings: ``` a = int(raw_input('Give amount: ')) ``` vs. ``` a = fib() ``` You won't run into the problem (as often) if you give your variables more descriptive names (3 different uses of the name `a` in 10 lines of code!): ``` amount = int(raw_input('Give amount: ')) ``` and change `...
Python Fibonacci Generator
3,953,749
9
2010-10-17T15:00:53Z
3,954,407
11
2010-10-17T17:35:00Z
[ "python", "fibonacci", "naming-conventions" ]
I need to make a program that asks for the amount of fibonacci numbers printed and then prints them like 0, 1, 1, 2... but I cant get it to work. My code looks the following: ``` a = int(raw_input('Give amount: ')) def fib(): a, b = 0, 1 while 1: yield a a, b = b, a + b a = fib() a.next() 0 f...
I would use this method: ``` a = int(raw_input('Give amount: ')) def fib(n): a, b = 0, 1 for _ in xrange(n): yield a a, b = b, a + b print list(fib(a)) ```
Python Fibonacci Generator
3,953,749
9
2010-10-17T15:00:53Z
3,955,269
10
2010-10-17T20:58:03Z
[ "python", "fibonacci", "naming-conventions" ]
I need to make a program that asks for the amount of fibonacci numbers printed and then prints them like 0, 1, 1, 2... but I cant get it to work. My code looks the following: ``` a = int(raw_input('Give amount: ')) def fib(): a, b = 0, 1 while 1: yield a a, b = b, a + b a = fib() a.next() 0 f...
Since you are writing a generator, why not use two yields, to save doing the extra shuffle? ``` import itertools as it num_iterations = int(raw_input('How many? ')) def fib(): a,b = 0,1 while True: yield a b = a+b yield b a = a+b for x in it.islice(fib(), num_iterations): ...
How to make heapq evaluate the heap off of a specific attribute?
3,954,530
13
2010-10-17T18:06:26Z
3,954,578
20
2010-10-17T18:19:17Z
[ "python", "data-structures", "heap" ]
I wish to hold a heap of objects, not just numbers. They will have an integer attribute in them that the heap can sort by. The easiest way to use heaps in python is heapq, but how do I tell it to sort by a specific attribute when using heapq?
`heapq` sorts objects the same way `list.sort` does, so just define a method `__cmp__()` within your class definition, which will compare itself to another instance of the same class: ``` def __cmp__(self, other): return cmp(self.intAttribute, other.intAttribute) ``` Works in Python 2.x. In 3.x use: ``` def __l...
How to make heapq evaluate the heap off of a specific attribute?
3,954,530
13
2010-10-17T18:06:26Z
3,954,627
13
2010-10-17T18:28:00Z
[ "python", "data-structures", "heap" ]
I wish to hold a heap of objects, not just numbers. They will have an integer attribute in them that the heap can sort by. The easiest way to use heaps in python is heapq, but how do I tell it to sort by a specific attribute when using heapq?
According to the example from the [documentation](https://docs.python.org/2/library/heapq.html#basic-examples), you can use tuples, and it will sort by the first element of the tuple: ``` >>> h = [] >>> heappush(h, (5, 'write code')) >>> heappush(h, (7, 'release product')) >>> heappush(h, (1, 'write spec')) >>> heappu...
Image analysis in R
3,955,077
15
2010-10-17T20:12:36Z
3,955,193
7
2010-10-17T20:42:39Z
[ "python", "image", "analysis" ]
I would like to know how I would go about performing image analysis in R. My goal is to convert images into matrices (pixel-wise information), extract/quantify color, estimate the presence of shapes and compare images based on such metrics/patterns. I am aware of relevant packages available in Python (suggestions rele...
Also check out the RASTER package on the R-Forge website: <http://r-forge.r-project.org/projects/raster/> It is not released to CRAN yet but it is an excellent package to import, analyse, extract, subset images and convert them to matrices). Spatial analysis is also possible. You can download the package in R via: ...
Image analysis in R
3,955,077
15
2010-10-17T20:12:36Z
3,955,198
9
2010-10-17T20:43:52Z
[ "python", "image", "analysis" ]
I would like to know how I would go about performing image analysis in R. My goal is to convert images into matrices (pixel-wise information), extract/quantify color, estimate the presence of shapes and compare images based on such metrics/patterns. I am aware of relevant packages available in Python (suggestions rele...
I'd start with `EBImage` - check out the [vignette](http://www.bioconductor.org/packages/release/bioc/vignettes/EBImage/inst/doc/EBImage-introduction.pdf) which demonstrates many of the tasks you mention.
Django: Return 'None' from OneToOneField if related object doesn't exist?
3,955,093
19
2010-10-17T20:15:54Z
14,392,042
8
2013-01-18T03:43:08Z
[ "python", "django", "django-models" ]
I've got a Django class like this: ``` class Breakfast(m.Model): # egg = m.OneToOneField(Egg) ... class Egg(m.Model): breakfast = m.OneToOneField(Breakfast, related_name="egg") ``` Is it possible to have `breakfast.egg == None` if there is no `Egg` related to the `Breakfast`? **Edit**: Forgot to mention...
I just ran into this problem, and found an odd solution to it: if you select\_related(), then the attribute will be None if no related row exists, instead of raising an error. ``` >>> print Breakfast.objects.get(pk=1).egg Traceback (most recent call last): ... DoesNotExist: Egg matching query does not exist >>> print...
python circular imports once again (aka what's wrong with this design)
3,955,790
41
2010-10-17T23:30:47Z
3,956,038
77
2010-10-18T01:10:20Z
[ "python", "design", "dependencies", "class-design", "python-import" ]
Let's consider python (3.x) scripts: main.py: ``` from test.team import team from test.user import user if __name__ == '__main__': u = user() t = team() u.setTeam(t) t.setLeader(u) ``` test/user.py: ``` from test.team import team class user: def setTeam(self, t): if issubclass(t, team....
Circular imports are not inherently a bad thing. It's natural for the `team` code to rely on `user` whilst the `user` does something with `team`. The worse practice here is `from module import member`. The `team` module is trying to get the `user` class at import-time, and the `user` module is trying to get the `team`...
How to determine bottlenecks in code, besides visual inspection?
3,956,112
8
2010-10-18T01:39:01Z
3,956,115
14
2010-10-18T01:40:05Z
[ "python", "performance" ]
When visual inspection fails, how do you determine where the slowest points in your code are? Where are the bottlenecks that are ruining your runtime?
> Profile your code. The data obtained is irrefutable in determining the performance bottlenecks. * <http://blip.tv/pycon-us-videos-2009-2010-2011/introduction-to-python-profiling-1966784> and the following allows you to visualize the profile data * <http://www.vrplumber.com/programming/runsnakerun/> > Bunch of pe...
Python: Convert this list into dictionary
3,956,206
2
2010-10-18T02:10:07Z
3,956,223
15
2010-10-18T02:15:41Z
[ "python", "list", "dictionary", "formatting" ]
I've got a problem , and do not know how to code in python. I've got a `list[10, 10, 10, 20, 20, 20, 30]` I want it be in a dictionary like this ``` {"10": 1, "20": 3, "30" : 1} ``` How could I achieve this?
``` from collections import Counter a = [10, 10, 10, 20, 20, 20, 30] c = Counter(a) # Counter({10: 3, 20: 3, 30: 1}) ``` If you really want to convert the keys to strings, that's a separate step: ``` dict((str(k), v) for k, v in c.iteritems()) ``` This class is new to Python 2.7; for earlier versions, use this imple...
Minimax explained for an idiot
3,956,258
9
2010-10-18T02:26:59Z
3,956,356
15
2010-10-18T03:01:07Z
[ "python", "minimax", "tic-tac-toe" ]
I've wasted my entire day trying to use the minimax algorithm to make an unbeatable tictactoe AI. I missed something along the way (brain fried). I'm not looking for code here, just a better explanation of where I went wrong. ### Here is my current code (the minimax method always returns 0 for some reason): ``` from...
**Step 1: Build your game tree** Starting from the current board generate all possible moves your opponent can make. Then for each of those generate all the possible moves you can make. For Tic-Tac-Toe simply continue until no one can play. In other games you'll generally stop after a given time or depth. This looks ...
What is the PHP equivalent to Python's Try: ... Except:
3,956,278
4
2010-10-18T02:34:50Z
3,956,288
7
2010-10-18T02:36:23Z
[ "php", "python", "exception", "try-catch" ]
I am a strong Python programmer, but not quite there when it comes to PHP. I need to try something, and if that doesn't work out, do something else. --- **This is what it would look like in Python:** ``` try: print "stuf" except: print "something else" ``` What would this be in PHP?
<http://php.net/manual/en/language.exceptions.php> ``` try { print 'stuff'; } catch (Exception $e) { var_dump($e); } ``` Note: this only works for exceptions, not errors. See <http://www.php.net/manual/en/function.set-error-handler.php> for that.
Escaping unicode strings for MySQL in Python (avoiding exceptions.UnicodeEncodeError)
3,956,906
4
2010-10-18T06:04:27Z
3,956,993
11
2010-10-18T06:29:57Z
[ "python", "mysql", "twisted" ]
I am using Twisted to asynchronously access our database in Python. My code looks like this: ``` from twisted.enterprise import adbapi from MySQLdb import _mysql as mysql ... txn.execute(""" INSERT INTO users_accounts_data_snapshots (accountid, programid, fieldid, value, timestamp, jobid) VALUES ('%s', '%s',...
Do not format strings like this. It is a massive security hole. It is not possible to do the quoting correctly by yourself. Do not try. Use the second parameter to 'execute'. Simply put, instead of `txn.execute("... %s, %s ..." % ("xxx", "yyy"))`, do `txn.execute("... %s, %s ...", ("xxx", "yyy"))`. Notice the comma in...
What does a audio frame contain?
3,957,025
8
2010-10-18T06:38:34Z
3,957,097
7
2010-10-18T06:59:53Z
[ "python", "wav" ]
Im doing some research on how to compare sound files(wave). Basically i want to compare stored soundfiles (wav) with sound from a microphone. So in the end i would like to pre-store some voice commands of my own and then when Im running my app I would like to compare the pre-stored files with input from the microphone....
A simple byte-by-byte comparison has almost no chance of a successful match, even with some tolerance thrown in. Voice-pattern recognition is a very complex and subtle problem that is still the subject of much research.
What does a audio frame contain?
3,957,025
8
2010-10-18T06:38:34Z
3,957,230
25
2010-10-18T07:26:37Z
[ "python", "wav" ]
Im doing some research on how to compare sound files(wave). Basically i want to compare stored soundfiles (wav) with sound from a microphone. So in the end i would like to pre-store some voice commands of my own and then when Im running my app I would like to compare the pre-stored files with input from the microphone....
An audio frame, or sample, contains amplitude (loudness) information at that particular point in time. To produce sound, tens of thousands of frames are played in sequence to produce frequencies. In the case of CD quality audio or uncompressed wave audio, there are around 44,100 frames/samples per second. Each of thos...
how itertools.tee works, can type 'itertools.tee' be duplicated in order to save it's "status"?
3,957,270
2
2010-10-18T07:34:32Z
3,957,420
8
2010-10-18T08:04:53Z
[ "python", "iterator", "duplicates", "tee" ]
All, pls see below test code about itertools.tee: ``` li = [x for x in range(10)] ite = iter(li) ================================================== it = itertools.tee(ite, 5) >>> type(ite) <type 'listiterator'> >>> type(it) <type 'tuple'> >>> type(it[0]) <type 'itertools.tee'> >...
`tee` takes over the original iterator; once you tee an iterator, discard the original iterator since the tee owns it (unless you really know what you're doing). You can make a copy of a tee with the `copy` module: ``` import copy, itertools it = [1,2,3,4] a, b = itertools.tee(it) c = copy.copy(a) ``` ... or by call...
Loading a large dictionary using python pickle
3,957,765
7
2010-10-18T09:12:09Z
3,957,912
10
2010-10-18T09:33:51Z
[ "python", "pickle", "inverted-index" ]
I have a full inverted index in form of nested python dictionary. Its structure is : ``` {word : { doc_name : [location_list] } } ``` For example let the dictionary be called index, then for a word " spam ", entry would look like : ``` { spam : { doc1.txt : [102,300,399], doc5.txt : [200,587] } } ``` I used this st...
Try the protocol argument when using `cPickle.dump`/`cPickle.dumps`. From `cPickle.Pickler.__doc__`: > Pickler(file, protocol=0) -- Create a pickler. > > This takes a file-like object for writing a pickle data stream. > The optional proto argument tells the pickler to use the given > protocol; supported protocols are ...
Determine if a Python list is 95% the same?
3,957,856
12
2010-10-18T09:24:33Z
3,957,969
16
2010-10-18T09:39:37Z
[ "python", "algorithm", "list" ]
[This question](http://stackoverflow.com/questions/3787908/python-determine-if-all-items-of-a-list-are-the-same-item) asks how to determine if every element in a list is the same. How would I go about determining if 95% of the elements in a list are the same in a reasonably efficient way? For example: ``` >>> ninety_f...
``` >>> from collections import Counter >>> lst = [1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] >>> _, freq = Counter(lst).most_common(1)[0] >>> len(lst)*.95 <= freq True ```
Determine if a Python list is 95% the same?
3,957,856
12
2010-10-18T09:24:33Z
3,957,979
15
2010-10-18T09:41:03Z
[ "python", "algorithm", "list" ]
[This question](http://stackoverflow.com/questions/3787908/python-determine-if-all-items-of-a-list-are-the-same-item) asks how to determine if every element in a list is the same. How would I go about determining if 95% of the elements in a list are the same in a reasonably efficient way? For example: ``` >>> ninety_f...
Actually, there's an easy linear solution for similar problem, only with 50% constraint instead of 95%. [Check this question](http://stackoverflow.com/questions/3740371/finding-the-max-repeated-element-in-an-array), it's just a few lines of code. It will work for you as well, only in the end you check that selected el...
Non biased return a list of n random positive numbers (>=0) so that their sum == total_sum
3,959,021
11
2010-10-18T12:17:22Z
3,959,050
13
2010-10-18T12:19:47Z
[ "python", "algorithm" ]
I'm either looking for an algorithm or a suggestion to improve my code to generate a list of random numbers that their sum equals some arbitrary number. With my code below, it'll always be biased as the first numbers will tend to be higher. Is there a way to have the number selection more efficient? ``` #!/usr/bin/py...
Why not just generate the right number of uniformly distributed random numbers, tot them up and scale ? EDIT: To be a bit clearer: you want N numbers which sum to S ? So generate N uniformly distributed random numbers on the interval [0,1) or whatever your RNG produces. Add them up, they will total s (say) whereas you...
Non biased return a list of n random positive numbers (>=0) so that their sum == total_sum
3,959,021
11
2010-10-18T12:17:22Z
3,959,233
8
2010-10-18T12:43:04Z
[ "python", "algorithm" ]
I'm either looking for an algorithm or a suggestion to improve my code to generate a list of random numbers that their sum equals some arbitrary number. With my code below, it'll always be biased as the first numbers will tend to be higher. Is there a way to have the number selection more efficient? ``` #!/usr/bin/py...
Here's how I would do it: 1. Generate n-1 random numbers, all in the range [0,`max`] 2. Sort those numbers 3. For each pair made up of the i-th and (i+1)-th number in sorted list, create an interval (i,i+1) and compute its length. The last interval will start at the last number and end at `max` and the first interval ...
How can I make Python/Sphinx document object attributes only declared in __init__?
3,959,615
8
2010-10-18T13:25:50Z
3,960,105
7
2010-10-18T14:20:13Z
[ "python", "documentation", "attributes", "python-sphinx", "docstring" ]
I have Python classes with object attributes which are only declared as part of running the constructor, like so: ``` class Foo(object): def __init__(self, base): self.basepath = base temp = [] for run in os.listdir(self.basepath): if self.foo(run): temp.append(...
> I've tried searching for a standard way to ensure that these "dynamically declared" attributes can be found (and preferably docstring'd) by the parser, but no luck so far. Any suggestions? They cannot ever be "detected" by any parser. Python has `setattr`. The complete set of attributes is never "detectable", in an...
Using PIP in a virtual environment, how do I install MySQL-python
3,960,305
17
2010-10-18T14:46:27Z
3,960,502
32
2010-10-18T15:07:20Z
[ "python", "ubuntu", "virtualenv", "pip", "mysql-python" ]
When I'm in my virtual environment, I attempt to run: ``` pip install MySQL-python ``` This didn't work, so I tried downloading the package and installing it by running: ``` python setup.py install ``` This returns the following error: ``` % python setup.py install ...
The reason this was occurring is because I need to install the python-dev package (which I stupidly assumed had already been installed). ``` % sudo apt-get install python-dev ``` followed by ``` % pip install MySQL-python ```
Does Python have a module to convert CSS styles to inline styles for emails?
3,960,721
5
2010-10-18T15:34:30Z
5,173,388
11
2011-03-02T20:59:39Z
[ "python", "css" ]
I know this exists in other languages, but I want it for Python to I can send emails that'll show up in GMail, etc.
I had to do the same thing a while back and put the module I made for it up on GitHub <https://github.com/rennat/pynliner>
Python timeit problem
3,960,834
5
2010-10-18T15:49:00Z
3,960,896
16
2010-10-18T15:55:47Z
[ "python", "timeit" ]
I'm trying to use the timeit module but I don't know how. I have a main: ``` from Foo import Foo if __name__ == '__main__': ... foo = Foo(arg1, arg2) t = Timer("foo.runAlgorithm()") print t.timeit(2) ``` and my Class Foo has a method named as runAlgorithm() the error is this: > NameError: global name 'foo...
Instead of using the necessary [`setup` parameter](http://docs.python.org/library/timeit.html#timeit.Timer) for setting up the timeit environment, you can simply pass the method (or anything that is callable): ``` t = Timer(foo.runAlgorithm) ``` From the documentation: > Changed in version 2.6: The stmt and setup pa...
Passing an Array/List into Python
3,961,007
17
2010-10-18T16:08:47Z
3,961,058
23
2010-10-18T16:13:40Z
[ "python", "parameter-passing", "argument-unpacking" ]
I've been looking at passing arrays, or lists, as Python tends to call them, into a function. I read something about using \*args, such as: ``` def someFunc(*args) for x in args print x ``` But not sure if this is right/wrong. Nothing seems to work as I want. I'm used to be able to pass arrays into PHP f...
When you define your function using this syntax: ``` def someFunc(*args) for x in args print x ``` You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this: ``` def someFunc(myList = [], *args) for x in m...
Passing an Array/List into Python
3,961,007
17
2010-10-18T16:08:47Z
3,961,064
7
2010-10-18T16:14:18Z
[ "python", "parameter-passing", "argument-unpacking" ]
I've been looking at passing arrays, or lists, as Python tends to call them, into a function. I read something about using \*args, such as: ``` def someFunc(*args) for x in args print x ``` But not sure if this is right/wrong. Nothing seems to work as I want. I'm used to be able to pass arrays into PHP f...
Python lists (which are not just arrays because their size can be changed on the fly) are normal Python objects and can be passed in to functions as any variable. The \* syntax is used for unpacking lists, which is probably not something you want to do now.
easy_install does not work in Windows 7
3,961,047
4
2010-10-18T16:12:53Z
3,961,095
9
2010-10-18T16:17:40Z
[ "python", "pyqt4" ]
I have Python 2.6.4 installed in C:\Python26. I have PyQt4 installed from here: <http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/PyQt-Py2.6-gpl-4.7.7-1.exe> I have added this path to %PATH%: ``` C:\Python26;C:\Python26\Scripts ``` When I type this command in cmd.exe however: ``` easy_install cheetah ```...
I think it lives here: `c:\python\scripts\easy_install.exe` --- Later: okay, have you installed `easy_install`? Download the appropriate Windows installer for your python version [here](http://pypi.python.org/pypi/setuptools#windows). (If you have no `scripts` directory, then you probably have not installed `easy_ins...
Get Line Number of certain phrase in file Python
3,961,265
20
2010-10-18T16:41:28Z
3,961,374
45
2010-10-18T16:53:47Z
[ "python", "file" ]
I need to get the line number of a phrase in a text file. The phrase could be: ``` the dog barked ``` I need to open the file, search it for that phrase and print the line number. I'm using Python 2.6 on Windows XP --- **This Is What I Have:** ``` o = open("C:/file.txt") j = o.read() if "the dog barked" in j: ...
``` lookup = 'the dog barked' with open(filename) as myFile: for num, line in enumerate(myFile, 1): if lookup in line: print 'found at line:', num ```
GTK and PYGTK difference
3,961,397
16
2010-10-18T16:55:50Z
3,961,585
15
2010-10-18T17:19:32Z
[ "python", "gtk", "pygtk" ]
many programmers import both gtk and pygtk in this way: ``` import gtk import pygtk ``` I have created a simple program using only gtk and it works: ``` import gtk window = gtk.Window() window.set_size_request(800, 700) window.set_position(gtk.WIN_POS_CENTER) window.connect("destroy", gtk.main_quit) button = gtk.B...
`pygtk` is provided by `python-gobject`. `gtk` is provided by `python-gtk2`. `pygtk` provides the `pygtk.require` function which allows you to require that a certain version of gtk (or better) is installed. For example ``` import pygtk pygtk.require('2.0') ``` importing `gtk` only is possible, but your program may n...
In Python, how to display current time in readable format
3,961,581
37
2010-10-18T17:19:06Z
3,961,596
17
2010-10-18T17:21:07Z
[ "python", "datetime", "time" ]
How can I display the current time as: ``` 12:18PM EST on Oct 18, 2010 ``` in Python. Thanks.
All you need is [in the documentation](http://docs.python.org/library/time.html). ``` import time time.strftime('%X %x %Z') '16:08:12 05/08/03 AEST' ```
In Python, how to display current time in readable format
3,961,581
37
2010-10-18T17:19:06Z
3,961,739
46
2010-10-18T17:36:55Z
[ "python", "datetime", "time" ]
How can I display the current time as: ``` 12:18PM EST on Oct 18, 2010 ``` in Python. Thanks.
First the quick and dirty way, and second the precise way (recognizing daylight's savings or not). ``` import time time.ctime() # 'Mon Oct 18 13:35:29 2010' time.strftime('%l:%M%p %Z on %b %d, %Y') # ' 1:36PM EDT on Oct 18, 2010' time.strftime('%l:%M%p %z on %b %d, %Y') # ' 1:36PM EST on Oct 18, 2010' ```
Unable to print variables in Python when using def function
3,962,163
2
2010-10-18T18:25:56Z
3,962,205
7
2010-10-18T18:33:05Z
[ "python" ]
I am trying to implement a simple neural net. I want to print the initial pattern, weights, activation. I then want it to print the learning process (i.e. every pattern it goes through as it learns). I am as yet unable to do this - it returns the initial and final pattern (whn I put print p in appropriate places), but ...
You have a problem with the line: ``` weights = [[[0]*n]*n] ``` When you use`*`, you multiply object references. You are using the same n-len array of zeroes every time. This will cause: ``` >>> weights[0][1][0] = 8 >>> weights [[[8, 0, 0], [8, 0, 0], [8, 0, 0]]] ``` The first item of all the sublists is 8, because...
How to display an image from web?
3,962,180
5
2010-10-18T18:29:03Z
3,962,377
14
2010-10-18T18:56:12Z
[ "python", "gtk", "pygtk" ]
I have written this simple script in python: ``` import gtk window = gtk.Window() window.set_size_request(800, 700) window.show() gtk.main() ``` now I want to load in this window an image from web ( and not from my PC ) like this: <http://www.dailygalaxy.com/photos/uncategorized/2007/05/05/planet_x.jpg> How can I...
This downloads the image from a url, but writes the data into a [gtk.gdk.Pixbuf](http://www.pygtk.org/docs/pygtk/class-gdkpixbuf.html) instead of to a file: ``` import pygtk pygtk.require('2.0') import gtk import urllib2 class MainWin: def destroy(self, widget, data=None): print "destroy signal occurred"...
Python: removing a TKinter frame
3,962,247
3
2010-10-18T18:38:12Z
3,962,726
8
2010-10-18T19:41:02Z
[ "python", "tkinter" ]
I want to remove a frame from my interface when a specific button is clicked. This is the invoked callback function ``` def removeMyself(self): del self ``` However, it doesn't remove itself. I'm probably just deleting the object in python without updating the interface ? thanks Update ``` self.itemFrame = tk...
To remove, call either `frm.pack_forget()` or `frm.grid_forget()` depending on whether the frame was packed or grided. Then call `frm.destroy()` if you aren't going to use it again, or hold onto the reference and repack or regrid when you want to show it again.
How to display all words that contain these characters?
3,962,846
2
2010-10-18T19:55:46Z
3,962,876
7
2010-10-18T19:59:25Z
[ "python" ]
I have a text file and I want to display all words that contains both z and x characters. How can I do that ?
Assuming you have the entire file as one large string in memory, and that the definition of a word is "a contiguous sequence of letters", then you could do something like this: ``` import re for word in re.findall(r"\w+", mystring): if 'x' in word and 'z' in word: print word ```
How to display all words that contain these characters?
3,962,846
2
2010-10-18T19:55:46Z
3,962,943
9
2010-10-18T20:06:16Z
[ "python" ]
I have a text file and I want to display all words that contains both z and x characters. How can I do that ?
If you don't want to have 2 problems: ``` for word in file('myfile.txt').read().split(): if 'x' in word and 'z' in word: print word ```
Accept lowercase or uppercase letter in Python
3,963,161
4
2010-10-18T20:35:42Z
3,963,170
12
2010-10-18T20:37:06Z
[ "python" ]
Working on a menu display where the letter "m" takes the user back to the main menu. How can I have it so that it works regardless if the letter "m" is uppercase or lowercase? ``` elif choice == "m": ```
One of ``` elif choice in ("m", "M"): ``` ``` elif choice in "mM": # false positive if choice == '' ``` ``` elif choice == 'm' or choice == 'M': ``` ``` elif choice.lower() == 'm': ``` **In terms of maintainability,** the 4th alternative is better when you want to extend to case-insensitive c...
Accept lowercase or uppercase letter in Python
3,963,161
4
2010-10-18T20:35:42Z
3,963,172
7
2010-10-18T20:37:08Z
[ "python" ]
Working on a menu display where the letter "m" takes the user back to the main menu. How can I have it so that it works regardless if the letter "m" is uppercase or lowercase? ``` elif choice == "m": ```
``` elif choice.lower() == "m": ```
Select between two dates with Django
3,963,201
56
2010-10-18T20:41:30Z
3,963,237
12
2010-10-18T20:45:14Z
[ "python", "django" ]
I am looking to make a query that selects between dates with Django. I know how to do this with raw SQL pretty easily, but how could this be achieved using the Django ORM? This is where I want to add the between dates of 30 days in my query: ``` start_date = datetime.datetime.now() + datetime.timedelta(-30) context[...
[`__range`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#range)
Select between two dates with Django
3,963,201
56
2010-10-18T20:41:30Z
3,963,247
124
2010-10-18T20:46:35Z
[ "python", "django" ]
I am looking to make a query that selects between dates with Django. I know how to do this with raw SQL pretty easily, but how could this be achieved using the Django ORM? This is where I want to add the between dates of 30 days in my query: ``` start_date = datetime.datetime.now() + datetime.timedelta(-30) context[...
Use the [`__range`](https://docs.djangoproject.com/en/1.7/ref/models/querysets/#range) operator: ``` ...filter(current_issue__isnull=True, created_at__range=(start_date, end_date)) ```
Convert File to HEX String Python
3,964,245
16
2010-10-18T23:21:49Z
3,964,285
27
2010-10-18T23:29:04Z
[ "python", "string", "file", "hex" ]
How would I convert a file to a HEX string using Python? I have searched all over Google for this, but can't seem to find anything useful.
``` import binascii filename = 'test.dat' with open(filename, 'rb') as f: content = f.read() print(binascii.hexlify(content)) ```
Find all files in directory with extension .txt in Python
3,964,681
696
2010-10-19T01:09:13Z
3,964,689
119
2010-10-19T01:11:34Z
[ "python", "file-io" ]
How can I find all files in directory with the extension `.txt` in python?
Use [glob](http://docs.python.org/library/glob.html). ``` >>> import glob >>> glob.glob('./*.txt') ['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt'] ```
Find all files in directory with extension .txt in Python
3,964,681
696
2010-10-19T01:09:13Z
3,964,690
74
2010-10-19T01:11:52Z
[ "python", "file-io" ]
How can I find all files in directory with the extension `.txt` in python?
Something like that should do the job ```` ``` for root, dirs, files in os.walk(directory): for file in files: if file.endswith('.txt'): print file ``` ````
Find all files in directory with extension .txt in Python
3,964,681
696
2010-10-19T01:09:13Z
3,964,691
989
2010-10-19T01:12:00Z
[ "python", "file-io" ]
How can I find all files in directory with the extension `.txt` in python?
You can use [`glob`](https://docs.python.org/2/library/glob.html): ``` import glob, os os.chdir("/mydir") for file in glob.glob("*.txt"): print(file) ``` or simply [`os.listdir`](https://docs.python.org/2/library/os.html#os.listdir): ``` import os for file in os.listdir("/mydir"): if file.endswith(".txt"): ...
Find all files in directory with extension .txt in Python
3,964,681
696
2010-10-19T01:09:13Z
3,964,696
52
2010-10-19T01:13:02Z
[ "python", "file-io" ]
How can I find all files in directory with the extension `.txt` in python?
Something like this will work: ``` >>> import os >>> path = '/usr/share/cups/charmaps' >>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')] >>> text_files ['euc-cn.txt', 'euc-jp.txt', 'euc-kr.txt', 'euc-tw.txt', ... 'windows-950.txt'] ```
Find all files in directory with extension .txt in Python
3,964,681
696
2010-10-19T01:09:13Z
3,964,752
14
2010-10-19T01:27:09Z
[ "python", "file-io" ]
How can I find all files in directory with the extension `.txt` in python?
I like [os.walk()](http://docs.python.org/library/os.html): ``` import os, os.path for root, dirs, files in os.walk(dir): for f in files: fullpath = os.path.join(root, f) if os.path.splitext(fullpath)[1] == '.txt': print fullpath ``` Or with generators: ``` import os, os.path fileit...