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
iter, values, item in dictionary does not work
20,444,340
9
2013-12-07T17:32:13Z
20,444,345
22
2013-12-07T17:32:42Z
[ "python", "dictionary" ]
Having this python code ``` edges = [(0, [3]), (1, [0]), (2, [1, 6]), (3, [2]), (4, [2]), (5, [4]), (6, [5, 8]), (7, [9]), (8, [7]), (9, [6])] graph = {0: [3], 1: [0], 2: [1, 6], 3: [2], 4: [2], 5: [4], 6: [5, 8], 7: [9], 8: [7], 9: [6]} cycles = {} while graph: current = graph.iteritems().next() cycle = [curr...
You are using Python 3; use `dict.items()` instead. The Python 2 `dict.iter*` methods have been renamed in Python 3, where `dict.items()` returns a dictionary view instead of a list by default now. Dictionary views act as iterables in the same way `dict.iteritems()` do in Python 2. From the [Python 3 What's New docum...
Pandas compiled from source: default pickle behavior changed
20,444,593
12
2013-12-07T17:55:05Z
20,455,090
17
2013-12-08T15:25:44Z
[ "python", "pandas", "pickle" ]
I've just compiled and installed pandas from source (cloned github repo, `>>> setup.py install`). It happened that the default behavior of module `pickle` for object serialization/deserialization changed being likely partially overridden by pandas internal modules. I have quite some data classes serialized via "stand...
Master has just been updated by this [issue](https://github.com/pydata/pandas/pull/5661). This file be read simply by: ``` result = pd.read_pickle('pickle_L1cor_s1.pic') ``` The objects that are pickled are pandas <= 0.12 versioned. This need a custom unpickler, which the 0.13/master (releasing shortly) handles. 0....
Infinite range in my python prime finder?
20,446,006
3
2013-12-07T20:05:54Z
20,446,027
7
2013-12-07T20:08:24Z
[ "python", "primes" ]
I am trying to get an infinite range in my python prime number finder! here is my code! ``` import math print "Welcome to Prime Finder!" option = raw_input("continue(y/n)") if option == "y": for num in range(1,(infinite number)): if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)): print n...
You can import [itertools](http://docs.python.org/2.7/library/itertools.html) and use `count` function ``` import itertools for num in itertools.count(1): print num ``` > count(1) --> 1 2 3 4 5 ... > > count(10) --> 10 11 12 13 14 ... > > count(1, 2) --> 1 3 5 7 9 ... The first argument is the starting point.
Django South Error: AttributeError: 'DateTimeField' object has no attribute 'model'`
20,446,724
17
2013-12-07T21:14:35Z
20,458,553
29
2013-12-08T20:20:35Z
[ "python", "django", "postgresql", "django-models", "django-south" ]
So I'm trying to migrate a table by adding two columns to it. A `startDate` and an `endDate`. Using `south` for Django, this should be a simple migrate. I have loads of other tables with dateTimes in them as well, but for some reason I'm getting and issue here and I don't see it. The stack trace is stating: ``` Attri...
I had to upgrade my version of `south` for `django` to version `0.8.4`. Had to run the following command: ``` sudo easy_install -U South ``` Or, if using `pip`: ``` pip install South --upgrade ``` After that, my migration worked as expected.
How to hide or disable the mouse pointer in Tkinter?
20,446,782
5
2013-12-07T21:19:43Z
23,801,402
7
2014-05-22T08:19:33Z
[ "python", "tkinter", "mouse" ]
I have a fullscreen Tkinter Python application which does not need the mouse -- a simplified version is below. It opens fullscreen and activates a text widget upon pressing `F1`. ``` import Tkinter as tk class App(): def __init__(self): self.root = tk.Tk() self.root.attributes('-fullscreen', True)...
I guess, `root.config(cursor="none")` should work.
Get diagonal without using numpy in Python
20,447,210
5
2013-12-07T21:59:01Z
20,447,298
16
2013-12-07T22:08:18Z
[ "python", "matrix" ]
I'm trying to get the diagonal from a matrix in Python without using numpy (i really cant use numpy). Do someone here knows how to do it? Example of what i want to get: ``` get_diagonal ([[1,2,3,4],[5,6,7,8],[9,10,11,12]], 1, 1, 1) Result: [1, 6, 11] ``` Or like: ``` get_diagonal ([[1,2,3,4],[5,6,7,8],[9,10,11,12]]...
To get the leading diagonal you could do ``` diag = [ mat[i][i] for i in range(len(mat)) ] ``` or even ``` diag = [ row[i] for i,row in enumerate(mat) ] ``` And play similar games for other diagonals. For example, for the counter-diagonal (top-right to bottom-left) you would do something like: ``` diag = [ row[-i-...
How can I read inputs as integers in Python?
20,449,427
71
2013-12-08T03:08:15Z
20,449,433
87
2013-12-08T03:08:57Z
[ "python", "python-2.7", "python-3.x", "int" ]
Why does this code not input integers? Everything on the web says to use `raw_input()`, but I read on Stack Overflow (on a thread that did not deal with integer input) that `raw_input()` was renamed to `input()` in Python 3.x. ``` play = True while play: x = input("Enter a number: ") y = input("Enter a numbe...
**Python 2.x** There were two functions to get user input, called [`input`](https://docs.python.org/2/library/functions.html#input) and [`raw_input`](https://docs.python.org/2/library/functions.html#raw_input). The difference between them is, `raw_input` doesn't evaluate the data and returns as it is, in string form. ...
How can I read inputs as integers in Python?
20,449,427
71
2013-12-08T03:08:15Z
20,449,435
8
2013-12-08T03:09:10Z
[ "python", "python-2.7", "python-3.x", "int" ]
Why does this code not input integers? Everything on the web says to use `raw_input()`, but I read on Stack Overflow (on a thread that did not deal with integer input) that `raw_input()` was renamed to `input()` in Python 3.x. ``` play = True while play: x = input("Enter a number: ") y = input("Enter a numbe...
`input()` (Python 3) and `raw_input()` (Python 2) *always* return strings. Convert the result to integer explicitly with `int()`. ``` x = int(input("Enter a number: ")) y = int(input("Enter a number: ")) ``` Pro tip: semi-colons are not needed in Python.
How can I read inputs as integers in Python?
20,449,427
71
2013-12-08T03:08:15Z
20,449,436
10
2013-12-08T03:09:11Z
[ "python", "python-2.7", "python-3.x", "int" ]
Why does this code not input integers? Everything on the web says to use `raw_input()`, but I read on Stack Overflow (on a thread that did not deal with integer input) that `raw_input()` was renamed to `input()` in Python 3.x. ``` play = True while play: x = input("Enter a number: ") y = input("Enter a numbe...
In Python 3.x, `raw_input` was renamed to `input` and the Python 2.x `input` was removed. This means that, just like `raw_input`, [`input`](http://docs.python.org/3.2/library/functions.html#input) in Python 3.x always returns a string object. To fix the problem, you need to explicitly make those inputs into integers ...
Python Compressing A Series of JSON Objects While Maintaining Serial Reading?
20,449,625
5
2013-12-08T03:42:33Z
20,449,656
16
2013-12-08T03:47:14Z
[ "python", "json", "file-io", "compression", "zlib" ]
I have a bunch of *json objects* that I need to compress as it's eating too much disk space, approximately `20 gigs` worth for a few million of them. Ideally what I'd like to do is compress each individually and then when I need to read them, just iteratively load and decompress each one. I tried doing this by creatin...
Just use a [`gzip.GzipFile()` object](http://docs.python.org/2/library/gzip.html#gzip.GzipFile) and treat it like a regular file; write JSON objects line by line, and read them line by line. The object takes care of compression transparently, and will buffer reads, decompressing chucks as needed. ``` import gzip impo...
Pushing to an existing AWS Elastic Beanstalk application from the command line
20,450,454
7
2013-12-08T06:06:29Z
20,458,619
7
2013-12-08T20:26:00Z
[ "python", "amazon-web-services", "elastic-beanstalk" ]
I've used the web dashboard of Elastic Beanstalk to make an application and an environment. I know I can update that using the dashboard and uploading a zip file of my application, but I would rather use the command line to upload my application. Apparently the correct tool for this is `eb`, the CLI for Elastic Beanst...
To begin using `git aws.push` for your application you will have to initialize your git repository with AWS Beanstalk metadata. I'm assuming you are using git for version control (*if you are not, you will have to initialize your project with `git init` first*). ``` $ cd angrywhopper $ git init #optional $ eb init ......
Does Slicing `a` (e.g. `a[1:] == a[:-1]`) create copies of the `a`?
20,450,671
11
2013-12-08T06:44:43Z
20,450,714
11
2013-12-08T06:52:22Z
[ "python", "cpython", "memory-efficient", "python-internals" ]
A friend of mine showed me the following Python code: ``` a[1:] == a[:-1] ``` Which returns True iff all the items in `a` are identical. I argued the code is hard to understand from first sight, and moreover - it is inefficient in memory usage, because two copies of `a` will be created for the comparison. I've used...
The documentation is unclear because slicing different objects does different things. [In the case of a list, slicing does make a (shallow) copy](http://hg.python.org/cpython/file/03afd2d7d395/Objects/listobject.c#l467)1. Note that [this is a feature of python lists independent of python implementation](http://docs.pyt...
Python Call Parent Method Multiple Inheritance
20,450,911
9
2013-12-08T07:23:07Z
20,450,978
7
2013-12-08T07:33:43Z
[ "python", "class", "inheritance", "multiple-inheritance" ]
So, i have a situation like this. ``` class A(object): def foo(self, call_from): print "foo from A, call from %s" % call_from class B(object): def foo(self, call_from): print "foo from B, call from %s" % call_from class C(object): def foo(self, call_from): print "foo from C, cal...
Add `super()` call's in other classes as well except `C`. Since D's MRO is ``` >>> D.__mro__ (<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <type 'object'>) ``` You don't need super call in `C`. **Code:** ``` class A(object): def foo(self, call_from): print "foo...
Why should I use ints instead of floats?
20,452,189
2
2013-12-08T10:11:58Z
20,452,230
7
2013-12-08T10:16:28Z
[ "python", "python-3.x", "floating-point", "int" ]
I'm preparing for a class lesson (I'm teaching) and I'm trying to predict any possible questions from the students and I ran into one that I can't answer: If we have floats, why do we ever use ints at all? What's the point? I know (or at least I think) that floats take more memory because they have more accuracy, but...
Floating point numbers are approximations in many cases. Some integers (and decimals) can be exactly represented by a `float`, but most can't. See [Floating Point Arithmetic: Issues and Limitations](http://docs.python.org/3/tutorial/floatingpoint.html). ``` >>> a = 1000000000000000000000000000 >>> a+1 == a False >>> a...
Why should I use ints instead of floats?
20,452,189
2
2013-12-08T10:11:58Z
20,452,305
7
2013-12-08T10:26:37Z
[ "python", "python-3.x", "floating-point", "int" ]
I'm preparing for a class lesson (I'm teaching) and I'm trying to predict any possible questions from the students and I ran into one that I can't answer: If we have floats, why do we ever use ints at all? What's the point? I know (or at least I think) that floats take more memory because they have more accuracy, but...
It's important to use data types that are the best fit for the task they are used for. A data type may not fit in different ways. For instance, a single byte is a bad fit for a population count because you cannot count more than 255 individuals. On the other hand a float is a bad fit because many possible floating poin...
How exactly does addStretch work in QBoxLayout?
20,452,754
8
2013-12-08T11:13:28Z
20,457,936
9
2013-12-08T19:28:45Z
[ "python", "layout", "pyqt", "boxlayout" ]
I'm doing a PyQt4 tutorial about box layouts. But I dont understand how `addStretch` works. * If i use `vbox.addStretch(1)` and `hbox.addStretch(1)`, the two buttons appear down-right. Why? * if i comment `vbox.addStretch(1)` and `hbox.addStretch(1)` out, the two buttons appear in the center of my window, and they're ...
The [addStretch](https://qt-project.org/doc/qt-4.8/qboxlayout.html#addStretch) method adds a [QSpacerItem](https://qt-project.org/doc/qt-4.8/qspaceritem.html) to the end of a box layout. A QSpacerItem is an adjustable blank space. 1. Using `vbox.addStretch(1)` will add a zero-width spacer-item that expands vertical...
How to remove gaps between bars in Matplotlib bar chart
20,454,120
6
2013-12-08T13:45:12Z
20,454,355
9
2013-12-08T14:11:14Z
[ "python", "matplotlib" ]
I'm making a bar chart in Matplotlib with a call like this: ``` xs.bar(bar_lefts, bar_heights, facecolor='black', edgecolor='black') ``` I get a barchart that looks like this: ![Bar chart with gaps](http://i.stack.imgur.com/W4DXU.png) What I'd like is one with no white gap between consecutive bars, e.g. more like t...
Add `width=1.0` as a keyword argument to `bar()`. E.g. `xs.bar(bar_lefts, bar_heights, width=1.0, facecolor='black', edgecolor='black')`. This will fill the bars gaps vertically.
How to use a different version of python during NPM install?
20,454,199
131
2013-12-08T13:54:45Z
20,454,306
44
2013-12-08T14:04:33Z
[ "python", "node.js", "centos", "npm" ]
Salam (means Hello) :) I have terminal access to a VPS running centos 5.9 and default python 2.4.3 installed. I also installed python 2.7.3 via these commands: (I used `make altinstall` instead of `make install`) ``` wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz tar -xf Python-2.7.3.tgz cd Python-2.7.3...
set python to python2.7 before running npm install Linux: ``` export PYTHON=python2.7 ``` Windows: ``` set PYTHON=python2.7 ```
How to use a different version of python during NPM install?
20,454,199
131
2013-12-08T13:54:45Z
22,433,804
286
2014-03-16T06:40:18Z
[ "python", "node.js", "centos", "npm" ]
Salam (means Hello) :) I have terminal access to a VPS running centos 5.9 and default python 2.4.3 installed. I also installed python 2.7.3 via these commands: (I used `make altinstall` instead of `make install`) ``` wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz tar -xf Python-2.7.3.tgz cd Python-2.7.3...
You can use `--python` option to npm like so: ``` npm install --python=python2.7 ``` or set it to be used always: ``` npm config set python python2.7 ``` Npm will in turn pass this option to node-gyp when needed. (note: I'm the one who opened an issue on Github to have this included in the docs, as there were so m...
How to use a different version of python during NPM install?
20,454,199
131
2013-12-08T13:54:45Z
32,027,975
20
2015-08-15T18:32:53Z
[ "python", "node.js", "centos", "npm" ]
Salam (means Hello) :) I have terminal access to a VPS running centos 5.9 and default python 2.4.3 installed. I also installed python 2.7.3 via these commands: (I used `make altinstall` instead of `make install`) ``` wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz tar -xf Python-2.7.3.tgz cd Python-2.7.3...
For Windows users something like this should work: ``` PS C:\angular> npm install --python=C:\Python27\python.exe ```
The right way to round pandas.DataFrame?
20,455,163
7
2013-12-08T15:32:21Z
20,455,277
11
2013-12-08T15:41:48Z
[ "python", "pandas", "rounding" ]
I want round `pandas.DataFrame`. Here is what i have tried so far: ``` import pandas as pd data = pd.DataFrame([1.4,2.5,3.8,4.4,5.6],[6.2,7.6,8.8,9.1,0]) print(round(data)) ``` But when i run this code, i get the following error: ``` Traceback (most recent call last): File "C:\Users\*****\Documents\*****\******\*...
first, you may want to change the definition of your data frame, something like: ``` data = pd.DataFrame([[1.4,2.5,3.8,4.4,5.6],[6.2,7.6,8.8,9.1,0]]).T ``` which results this: ``` 0 1 0 1.4 6.2 1 2.5 7.6 2 3.8 8.8 3 4.4 9.1 4 5.6 0.0 ``` or: ``` data = pd.DataFrame({'A':[1.4,2.5,3.8,4.4,5.6],'B':...
Sum up all the integers in range()
20,455,977
2
2013-12-08T16:47:19Z
20,456,070
11
2013-12-08T16:55:31Z
[ "python", "python-3.x" ]
I need to write a program that sums up all the integers which can be divided by 3 in the range of 100 to 2000. I'm not even sure where to start, so far I've got this tiny piece of code written which isn't correct. ``` for x in range(100, 2001, 3): print(x+x) ``` Any help is much appreciated!
Since you know the first number in this range that is divisible by 3 is 102, you can do the following: **Solution:** ``` >>> sum(range(102, 2001, 3)) 664650 ``` **To make it into a robust function:** ``` def sum_range_divisible(start, end, divisor): while start % divisor != 0: start += 1 return sum(...
Python - how to round down to 2 decimals
20,457,038
6
2013-12-08T18:13:41Z
20,457,115
9
2013-12-08T18:20:41Z
[ "python", "rounding" ]
I am getting a lot of decimals in the output of this code (Fahrenheit to Celsius converter). My code currently looks like this: ``` def main(): printC(formeln(typeHere())) def typeHere(): global Fahrenheit try: Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n")) ...
You can use the [round](http://docs.python.org/2/library/functions.html#round) function, which takes as first argument the number and the second argument is the precision. In your case, it would be: ``` answer = str(round(answer, 2)) ```
Flask logging with Foreman
20,457,567
7
2013-12-08T18:59:37Z
20,457,814
11
2013-12-08T19:20:00Z
[ "python", "heroku", "flask", "foreman", "procfile" ]
I'm trying to set up a Heroku-ready Flask app, but I can't figure out how to turn on logging. Without Foreman, I could create a helloworld app as described in the [Flask tutorial](http://flask.pocoo.org/): ``` from flask import Flask app = Flask(__name__) @app.route("/") def hello(): app.logger.debug('A value fo...
The default logging configuration for Flask apps is different in debug vs. production mode. In your first example you are in debug mode. In this case Flask defines a logging handlers that logs all messages with level `logging.DEBUG` or higher to `stderr`. The second example is not in debug mode. When debug mode is no...
How to use 2to3 properly for python?
20,458,011
2
2013-12-08T19:35:20Z
20,458,067
8
2013-12-08T19:39:30Z
[ "python", "python-2.7", "python-3.3", "2to3" ]
I have some code in python 2.7 and I want to convert it all into python 3.3 code. I know 2to3 can be used but I am not sure exactly how to use it. Thanks for any help
As it is written on [2to3 docs](http://docs.python.org/2/library/2to3.html), to translate an entire project from one directory tree to another, use: ``` $ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode ```
Convert Pandas dataframe to Sparse Numpy Matrix directly
20,459,536
10
2013-12-08T21:45:49Z
20,459,839
15
2013-12-08T22:12:41Z
[ "python", "numpy", "pandas", "scipy" ]
I am creating a matrix from a Pandas dataframe as follows: ``` dense_matrix = np.array(df.as_matrix(columns = None), dtype=bool).astype(np.int) ``` And then into a sparse matrix with: ``` sparse_matrix = scipy.sparse.csr_matrix(dense_matrix) ``` Is there any way to go from a df straight to a sparse matrix? Thanks ...
`df.values` is a numpy array, and accessing values that way is always faster than `np.array`. ``` scipy.sparse.csr_matrix(df.values) ``` You might need to take the transpose first, like `df.values.T`. In DataFrames, the columns are axis 0.
Python's pycrypto library for random number generation vs os.urandom
20,460,061
7
2013-12-08T22:33:12Z
20,469,525
7
2013-12-09T11:30:41Z
[ "python", "random", "pycrypto" ]
I was trying to understand and figure out if I should use `os.urandom()` or `Crypto.Random.new()` for cryptographically secure pseudo-random numbers. The following website seems to suggest to use `os.urandom()`: <https://github.com/mozilla/PyHawk/pull/13> but I don't really see why and the other websites I found onl...
I go for `os.urandom`. On all (recent) Python implementations I checked, it does the correct thing by simply opening an *unbuffered* connection to `/dev/urandom` or the equivalent device on other non-Linux platforms. On the other hand, PyCrypto's `Crypto.Random` is a very complex wrapper based on Fortuna. Such complex...
Flask-SQLAlchemy Constructor
20,460,339
9
2013-12-08T23:01:16Z
20,462,185
20
2013-12-09T02:39:24Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy" ]
in the Flask-SQLAlchemy tutorial, a constructor for the User model is defined: ``` from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, prim...
In most cases not defining a constructor in your model class gives you the correct behavior. Flask-SQLAlchemy's base model class (which is also SQLAlchemy's declarative base class) defines a constructor that just takes `**kwargs` and stores all the arguments given, so it isn't really necessary to define a constructor....
How to convert pandas index in a dataframe to a column?
20,461,165
79
2013-12-09T00:34:16Z
20,461,206
132
2013-12-09T00:39:17Z
[ "python", "pandas" ]
This seems rather obvious, but I can't seem to figure out how do I convert an index of data frame to a column? For example: ``` df= gi ptt_loc 0 384444683 593 1 384444684 594 2 384444686 596 ``` To, ``` df= index1 gi ptt_loc 0 0 384444683 593 1 1 3...
either: ``` df['index1'] = df.index ``` or, [`.reset_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html#pandas.DataFrame.reset_index): ``` df.reset_index(level=0, inplace=True) ``` --- so, if you have a multi-index frame with 3 levels of index, like: ``` >>> df ...
How to convert pandas index in a dataframe to a column?
20,461,165
79
2013-12-09T00:34:16Z
31,075,478
13
2015-06-26T14:13:58Z
[ "python", "pandas" ]
This seems rather obvious, but I can't seem to figure out how do I convert an index of data frame to a column? For example: ``` df= gi ptt_loc 0 384444683 593 1 384444684 594 2 384444686 596 ``` To, ``` df= index1 gi ptt_loc 0 0 384444683 593 1 1 3...
For MultiIndex you can extract its subindex using ``` df['si_name'] = R.index.get_level_values('si_name') ``` where `si_name` is the name of the subindex.
I'm having a lot of trouble installing xlrd 0.9.2 for python
20,461,790
4
2013-12-09T01:53:10Z
20,462,003
15
2013-12-09T02:18:23Z
[ "python", "installation", "xlrd" ]
Can someone give me a guide for morons? I am somewhat out of my depth here. So far I have downloaded xlrd 0.9.2 and tried to follow the readme, but neither I nor ctrl-f can find the installer mentioned.
download The current version of xlrd can be found here: <https://pypi.python.org/pypi/xlrd> extract the folder somewhere go to the folder you extracted to ... find setup.py open command window (start -> run-> cmd) cd into the directory with setup.py type: `python setup.py install` you may need setup tools (which...
str.startswith with a list of strings to test for
20,461,847
25
2013-12-09T02:00:07Z
20,461,857
60
2013-12-09T02:01:34Z
[ "python", "string", "list" ]
I'm trying to avoid using so many if statements and comparisons and simply use a list, but not sure how to use it with `str.startswith`: ``` if link.lower().startswith("js/") or link.lower().startswith("catalog/") or link.lower().startswith("script/") or link.lower().startswith("scripts/") or link.lower().startswith("...
`str.startswith` allows you to supply a tuple of strings to test for: ``` if link.lower().startswith(("js", "catalog", "script", "katalog")): ``` From the [docs](http://docs.python.org/3/library/stdtypes.html#str.startswith): > `str.startswith(prefix[, start[, end]])` > > Return `True` if string starts with the `pre...
How do I solve overfitting in random forest of Python sklearn?
20,463,281
7
2013-12-09T04:40:18Z
22,546,016
14
2014-03-20T21:58:14Z
[ "python", "machine-learning", "scikit-learn", "decision-tree", "random-forest" ]
I am using RandomForestClassifier implemented in python sklearn package to build a binary classification model. The below is the results of cross validations: ``` Fold 1 : Train: 164 Test: 40 Train Accuracy: 0.914634146341 Test Accuracy: 0.55 Fold 2 : Train: 163 Test: 41 Train Accuracy: 0.871165644172 Test Accuracy...
I would agree with @Falcon w.r.t. the dataset size. It's likely that the main problem is the small size of the dataset. If possible, the best thing you can do is get more data, the more data (generally) the less likely it is to overfit, as random patterns that appear predictive start to get drowned out as the dataset s...
Save the edit when running a Sublime Text 3 plugin
20,466,014
8
2013-12-09T08:15:15Z
20,808,586
11
2013-12-27T22:21:15Z
[ "python", "sublimetext3", "sublime-text-plugin" ]
For understanding what I'm trying to achieve : printing delayed text in another view... I'm trying to make this sublime text 3 plugin run properly I want to call multiple method of my class using the edit passed in parameter of my run method as so : ``` # sample code, nothing real class MyCommandClass(sublime_plugin....
Solution found, to pass an argument to another view and use the edit : ``` class MainCommand(sublime_plugin.WindowCommand): def run(self): newFile = self.window.new_file() newFile.run_command("second",{ "arg" : "this is an argument"}); class SecondCommand(sublime_plugin.TextCommand): def run(s...
How to setup up Django translation in the correct way?
20,467,626
8
2013-12-09T09:55:27Z
20,893,799
14
2014-01-02T23:22:28Z
[ "python", "django", "django-i18n" ]
I've got an issue with translations not working on Django 1.6!. I've added to my settings.py ``` LANGUAGE_CODE = 'en-us' ugettext = lambda s: s LANGUAGES = ( ('en', ugettext('English')), ('de', ugettext('German')), ) ``` Also added middlewares: ``` MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonM...
Add the `LOCALE_PATHS` to `settings.py` and set it as bellow: Note that `LOCALE_PATHS` must be a tuple(look at the comma at the end of the path) ``` import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) ``` Now based on `LOCALE_PATHS`, The `locale` ...
Which is the efficient way to convert a float into an int in python?
20,470,493
12
2013-12-09T12:17:30Z
20,470,547
17
2013-12-09T12:20:32Z
[ "python", "performance", "int" ]
I've been using `n = int(n)` to convert a `float` into an `int`. Recently, I came across another way to do the same thing : `n = n // 1` Which is the most efficient way, and why?
Test it with `timeit`: ``` $ bin/python -mtimeit -n10000000 -s 'n = 1.345' 'int(n)' 10000000 loops, best of 3: 0.234 usec per loop $ bin/python -mtimeit -n10000000 -s 'n = 1.345' 'n // 1' 10000000 loops, best of 3: 0.218 usec per loop ``` So floor division is only a faster by a small margin. Note that these values ar...
python script for RaspberryPi to connect wifi automatically
20,470,626
3
2013-12-09T12:24:53Z
21,164,401
11
2014-01-16T14:23:59Z
[ "python", "wifi", "raspberry-pi" ]
I want to operate a WiFi dongle with RaspberryPi, (it's like a CPU without built-in WiFi). I need to write a python script which automatically scan for WiFi networks and a connection need to be automatically established with known SSID and password. This mean that I need to provide the password for the WiFi network fr...
[wifi](https://wifi.readthedocs.org/en/latest/) is a python library for scanning and connecting to wifi networks on linux. You can use it to scan and connect to wireless networks. It doesn't have any built-in support for connecting automatically to a network, but you could easily write a script to do that. Here's an e...
Django Rest Framework File Upload
20,473,572
31
2013-12-09T14:53:21Z
20,473,684
16
2013-12-09T14:58:56Z
[ "python", "django", "angularjs", "django-rest-framework" ]
I am using Django Rest Framework and AngularJs to upload a file. My view file looks like this. ``` class ProductList(APIView): authentication_classes = (authentication.TokenAuthentication,) def get(self,request): if request.user.is_authenticated(): userCompanyId = request.user.get_profile(...
Use the [FileUploadParser](http://django-rest-framework.org/api-guide/parsers#fileuploadparser), it's all in the request. Use a put method instead, you'll find an example in the docs :) ``` class FileUploadView(views.APIView): parser_classes = (FileUploadParser,) def put(self, request, filename, format=None):...
Django Rest Framework File Upload
20,473,572
31
2013-12-09T14:53:21Z
27,305,713
30
2014-12-04T22:54:07Z
[ "python", "django", "angularjs", "django-rest-framework" ]
I am using Django Rest Framework and AngularJs to upload a file. My view file looks like this. ``` class ProductList(APIView): authentication_classes = (authentication.TokenAuthentication,) def get(self,request): if request.user.is_authenticated(): userCompanyId = request.user.get_profile(...
I'm using the same stack and was also looking for an example of file upload, but my case is simpler since I use the ModelViewSet instead of APIView. The key turned out to be the pre\_save hook. I ended up using it together with the angular-file-upload module like so: ``` # Django class ExperimentViewSet(ModelViewSet):...
Django Rest Framework File Upload
20,473,572
31
2013-12-09T14:53:21Z
28,697,633
10
2015-02-24T13:54:11Z
[ "python", "django", "angularjs", "django-rest-framework" ]
I am using Django Rest Framework and AngularJs to upload a file. My view file looks like this. ``` class ProductList(APIView): authentication_classes = (authentication.TokenAuthentication,) def get(self,request): if request.user.is_authenticated(): userCompanyId = request.user.get_profile(...
Finally I am able to upload image using Django. Here is my working code views.py ``` class FileUploadView(APIView): parser_classes = (FileUploadParser, ) def post(self, request, format='jpg'): up_file = request.FILES['file'] destination = open('/Users/Username/' + up_file.name, 'wb+') ...
Floating Point Numbers
20,473,968
9
2013-12-09T15:12:47Z
20,474,165
11
2013-12-09T15:22:48Z
[ "python", "floating-point" ]
So I am reading this PDF tutorial called: "Learning Python Fourth Edition". Now I got to a part which I dont understand because I am pretty much a beginner in Python. I am talking about this part: ![enter image description here](http://i.stack.imgur.com/eKzMd.png) Now I dont get the explaining of the first example. I...
This isn't a Python issue but an issue with the nature of floating point numbers. Turns out that computers are bad at representing numbers. Who knew? I recommend reading [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/02Numerics/Double/pa...
Extract points/coordinates from Python shapely polygon
20,474,549
9
2013-12-09T15:40:34Z
20,476,150
15
2013-12-09T16:56:05Z
[ "python", "polygons", "shapely" ]
How do you get/extract the points that define a `shapely` polygon? Thanks! **Example of a shapely polygon** ``` from shapely.geometry import Polygon # Create polygon from lists of points x = [list of x vals] y = [list of y vals] polygon = Polygon(x,y) ```
So, I discovered the trick is to use a combination of the `Polygon` class methods to achieve this. If you want geodesic coordinates, you then need to transform these back to WGS84 (via `pyproj`, `matplotlib`'s `basemap`, or something). ``` from shapely.geometry import Polygon #Create polygon from lists of points x =...
Python Requests library redirect new url
20,475,552
14
2013-12-09T16:27:34Z
20,475,639
8
2013-12-09T16:31:47Z
[ "python", "http", "redirect", "python-requests" ]
I've been looking through the Python Requests documentation but I cannot see any functionality for what I am trying to achieve. In my script I am setting `allow_redirects=True`. I would like to know if the page has been redirected to something else, what is the new URL. For example, if the start URL was: `www.google...
the documentation has this blurb <http://docs.python-requests.org/en/latest/user/quickstart/#redirection-and-history> ``` r = requests.get('http://www.github.com') r.url #returns https://www.github.com instead of the http page you asked for ```
Python Requests library redirect new url
20,475,552
14
2013-12-09T16:27:34Z
20,475,712
40
2013-12-09T16:35:31Z
[ "python", "http", "redirect", "python-requests" ]
I've been looking through the Python Requests documentation but I cannot see any functionality for what I am trying to achieve. In my script I am setting `allow_redirects=True`. I would like to know if the page has been redirected to something else, what is the new URL. For example, if the start URL was: `www.google...
You are looking for the [request history](http://docs.python-requests.org/en/latest/user/quickstart/#redirection-and-history). The `response.history` attribute is a list of responses that led to the final URL, which can be found in `response.url`. ``` response = requests.get(someurl) if response.history: print "R...
Checking if a float is an integer in Python
20,476,617
2
2013-12-09T17:18:07Z
20,476,894
11
2013-12-09T17:33:39Z
[ "python", "floating-point", "int" ]
I'm drawing a graph on a canvas and inserting canvas text objects to label the x and y axis intervals. here is my code. ``` def update(): scalex1=graph.create_text(356,355-87,text='%.1f'%scalex,anchor=NW) scalex2=graph.create_text(412,355-87,text='%.1f'% (scalex*2),anchor=NW) scalex3=graph.create_text(471...
There is [`is_integer`](http://docs.python.org/2/library/stdtypes.html#float.is_integer) function in python float type: ``` >>> float(1.0).is_integer() True >>> float(1.001).is_integer() False >>> ```
Get top biggest values from each column of the pandas.DataFrame
20,477,190
6
2013-12-09T17:48:56Z
20,477,862
7
2013-12-09T18:25:43Z
[ "python", "pandas", "dataframe" ]
Here is my `pandas.DataFrame`: ``` import pandas as pd data = pd.DataFrame({ 'first': [40, 32, 56, 12, 89], 'second': [13, 45, 76, 19, 45], 'third': [98, 56, 87, 12, 67] }, index = ['first', 'second', 'third', 'fourth', 'fifth']) ``` I want to create a new `DataFrame` that will contain top 3 values from each co...
Create a function to return the top three values of a series: ``` def sorted(s, num): tmp = s.order(ascending=False)[:num] tmp.index = range(num) return tmp ``` Apply it to your data set: ``` In [1]: data.apply(lambda x: sorted(x, 3)) Out[1]: first second third 0 89 76 98 1 56 ...
Pycharm: "unresolved reference" error on the IDE when opening a working project
20,479,696
29
2013-12-09T20:07:13Z
20,479,761
49
2013-12-09T20:10:42Z
[ "python", "pycharm" ]
**Intro** I have a Python project on a git repository. Everything works ok for most of the team members, we can sync the code and edit it without any problem with Pycharm on different platforms (Windows, Linux) **The problem** On one of the computers we are getting "Unresolved reference" all over the code on almost ...
The key is to mark your source directory as a source root. Try the following: * In the Project view, right-click on the Python source directory * In the dialog menu select **Mark Directory As** > **Source Root** The folder should now appear blue instead of beige, to indicate it is a Python source folder. You can als...
ValueError: unsupported format character '
20,480,018
5
2013-12-09T20:24:15Z
20,480,095
10
2013-12-09T20:28:47Z
[ "python" ]
I got most of the following code from here: [Generating pdf-latex with python script](http://stackoverflow.com/questions/8085520/generating-pdf-latex-with-python-script) ``` #!/usr/bin/env python from __future__ import division from functions import * import shlex #from Utilities import * import os import argparse i...
*Any* `%` in `content` is seen as a formatting placeholder. Double any that are not a placeholder: ``` content=r'''\documentclass{article} \usepackage{graphicx,amsmath} \begin{document} \noindent\rotatebox{180}{\vbox{%% %(equation)s }%% } \end{document} ''' ``` Otherwise the `%` at the end of the `\noindent\...
What more do I need to do to have Django's @login_required decorator work?
20,480,177
4
2013-12-09T20:33:42Z
20,480,226
9
2013-12-09T20:35:35Z
[ "python", "django", "django-authentication" ]
I am trying to use Django's account system, including the @login\_required decorator. My settings.py file includes `django.contrib.auth` and I have done a syncdb. ``` Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/login/?next=/ Using the URLconf defined in dashboard.urls, Djang...
Set the [LOGIN\_URL](https://docs.djangoproject.com/en/dev/ref/settings/#login-url) in your settings. The default value is `'/accounts/login/'` The decorator also takes an optional `login_url` argument: ``` @login_required(login_url='/accounts/login/') ``` And, from the [docs](https://docs.djangoproject.com/en/1.5/t...
Getting top 3 rows that have biggest sum of columns in `pandas.DataFrame`?
20,480,238
5
2013-12-09T20:36:18Z
20,480,508
7
2013-12-09T20:50:33Z
[ "python", "pandas", "dataframe" ]
Here is my `pandas.DataFrame`: ``` day1 day2 day3 Apple 40 13 98 Orange 32 45 56 Banana 56 76 87 Pineapple 12 19 12 Grape 89 45 67 ``` I want to create a new `DataFrame` that will contains top 3 fruits that have biggest sum of three days. Sum of `appl...
Here's how you get the indices for the top 3 days by sum: ``` In [1]: df.sum(axis=1).order(ascending=False).head(3) Out[1]: Banana 219 Grape 201 Apple 151 ``` And you can use that index to reference your original datset: ``` In [2]: idx = df.sum(axis=1).order(ascending=False).head(3).index In [3]: df.ix[...
Pandas add one day to column
20,480,897
10
2013-12-09T21:12:20Z
20,481,080
10
2013-12-09T21:22:39Z
[ "python", "pandas" ]
I need to add 1 day to each date I want to get the begining date of the following month eg 2014-01-2014 for the 1st item in the dataframe. Tried: ``` montdist['date'] + pd.DateOffset(1) ``` Which gives me: ``` TypeError: cannot use a non-absolute DateOffset in datetime/timedelta operations [<DateOffset>] ``` Have a...
Make it a DatetimeIndex first: ``` pd.DatetimeIndex(montdist['date']) + pd.DateOffset(1) ``` *Note: I think there is a feature request that this could work with date columns...* In action: ``` In [11]: df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B']) In [12]: df['date'] = pd.to_datetime(['21-11-2013', '22-1...
Pandas add one day to column
20,480,897
10
2013-12-09T21:12:20Z
20,496,583
7
2013-12-10T14:03:59Z
[ "python", "pandas" ]
I need to add 1 day to each date I want to get the begining date of the following month eg 2014-01-2014 for the 1st item in the dataframe. Tried: ``` montdist['date'] + pd.DateOffset(1) ``` Which gives me: ``` TypeError: cannot use a non-absolute DateOffset in datetime/timedelta operations [<DateOffset>] ``` Have a...
Try to use timedelta(): ``` mondist['shifted_date']=mondist.date + datetime.timedelta(days=1) ```
Scrapy : How to pass list of arguments through command prompt to spider?
20,482,526
3
2013-12-09T22:50:10Z
20,486,769
9
2013-12-10T05:21:20Z
[ "python", "web-scraping", "scrapy" ]
Creating a scraper for fantasy team. Looking for a way to pass a list of the players names as arguments, and then for each player\_name in player\_list run the parsing code. I currently have something like this ``` class statsspider(BaseSpider): name = 'statsspider' def __init__ (self, domain=None, player_list=""): ...
Shell arguments are string-based. You need to parse arg in your code. command line: ``` scrapy crawl statsspider -a player_list=xyz,abc ``` python code: ``` self.player_list = player_list.split(',') ```
TypeError: 'range' object does not support item assignment
20,484,195
5
2013-12-10T01:13:04Z
20,484,205
10
2013-12-10T01:14:29Z
[ "python" ]
I was looking at some python 2.x code and attempted to translate it to py 3.x but I'm stuck on this section. Could anyone clarify what is wrong? ``` import random emails = { "x": "[REDACTED]@hotmail.com", "x2": "[REDACTED]@hotmail.com", "x3": "[REDACTED]@hotmail.com" } people = emails.keys() #generate a...
In python3 `range` is a generator object - it does not return a list. Convert it to a list before shuffling. ``` allocations = list(range(len(people))) ```
Pymysql Insert Into not working
20,485,332
18
2013-12-10T03:14:34Z
20,485,375
44
2013-12-10T03:17:55Z
[ "python", "mysql", "eclipse", "python-2.7", "pymysql" ]
I'm running this from PyDev in Eclipse... ``` import pymysql conn = pymysql.connect(host='localhost', port=3306, user='userid', passwd='password', db='fan') cur = conn.cursor() print "writing to db" cur.execute("INSERT INTO cbs_transactions(leagueID) VALUES ('test val')") print "wrote to db" ``` The result is, at the...
Did you commit it? `conn.commit()`
Pymysql Insert Into not working
20,485,332
18
2013-12-10T03:14:34Z
22,680,882
31
2014-03-27T07:28:11Z
[ "python", "mysql", "eclipse", "python-2.7", "pymysql" ]
I'm running this from PyDev in Eclipse... ``` import pymysql conn = pymysql.connect(host='localhost', port=3306, user='userid', passwd='password', db='fan') cur = conn.cursor() print "writing to db" cur.execute("INSERT INTO cbs_transactions(leagueID) VALUES ('test val')") print "wrote to db" ``` The result is, at the...
PyMySQL disable autocommit by default, you can add `autocommit=True` to `connect`: ``` conn = pymysql.connect( host='localhost', user='user', passwd='passwd', db='db', autocommit=True ) ``` or call `conn.commit()` after your query
Selenium with pyvirtualdisplay unable to locate element
20,485,360
3
2013-12-10T03:16:43Z
20,499,923
7
2013-12-10T16:31:38Z
[ "python", "ubuntu", "selenium", "pyvirtualdisplay" ]
I have a working script that logs into a site using selenium like this: **script.py** ``` from pyvirtualdisplay import Display from selenium import webdriver display = Display(visible=0, size=(1024, 768)) display.start() browser = webdriver.Firefox() actions = webdriver.ActionChains(browser) browser.get('some_url_I...
If there is some dynamic content on the website you need to wait some time until you can retrieve the wished element. Try to following code examples: **Check Configuration** * Did you install a backend for `pyvirtualdisplay` like `xvfb` and `xephyr`? If not, try: `sudo apt-get install xvfb xserver-xephyr` **Fir...
sphinx generate class modules overview
20,487,488
5
2013-12-10T06:17:14Z
20,548,495
7
2013-12-12T16:13:32Z
[ "python", "graph", "python-sphinx" ]
I'd like sphinx to generate a module overview similar to the one generated by doxygen, here is an [example](http://mininet.org/api/classmininet_1_1node_1_1Switch.html) I can't find how sphinx can do that I could use Graphviz to generate some sort of graph, but I can't find a way to get a clickable object in the graph...
Sphinx has a built-in [extension](http://sphinx-doc.org/extensions.html) called [sphinx.ext.inheritance\_diagram](http://sphinx-doc.org/ext/inheritance.html) that uses Graphviz. It defines one directive: `inheritance-diagram`. Here is an example of how you could use it in an .rst file: ``` .. inheritance-diagram:: mym...
Plot GDAL raster using matplotlib Basemap
20,488,765
9
2013-12-10T07:44:50Z
20,499,331
13
2013-12-10T16:06:39Z
[ "python", "matplotlib", "gdal", "matplotlib-basemap" ]
I would like to plot a raster tiff *([download](https://files.myopera.com/mvanhoek/files/albers_5km.tif)-723Kb)* using matplotlib Basemap. My raster's projection coordinates is in meter: ``` In [2]: path = r'albers_5km.tif' raster = gdal.Open(path, gdal.GA_ReadOnly) array = raster.GetRasterBand(20).ReadAsArray() pri...
You can use the following code to convert the coordinates, it automatically takes the projection from your raster as the source and the projection from your Basemap object as the target coordinate system. ### Imports ``` from mpl_toolkits.basemap import Basemap import osr, gdal import matplotlib.pyplot as plt import ...
Dictionary Comprehension in Python 3
20,489,609
3
2013-12-10T08:38:13Z
20,489,629
8
2013-12-10T08:39:01Z
[ "python", "python-3.x" ]
I found the following stack overflow post about dict comprehensions in `Python2.7` and `Python 3+`: [Python: create a dictionary with list comprehension](http://stackoverflow.com/questions/1747817/python-create-a-dictionary-with-list-comprehension) stating that I can apply dictionary comprehensions like this: ``` d = ...
Looping over a dictionary only yields the **keys**. Use `d.items()` to loop over both keys and values: ``` {key: value for key, value in d.items()} ``` The `ValueError` exception you see is *not* a dict comprehension problem, nor is it limited to Python 3; you'd see the same problem in Python 2 or with a regular `for...
How to reset index in a pandas data frame?
20,490,274
46
2013-12-10T09:12:55Z
20,491,748
91
2013-12-10T10:19:52Z
[ "python", "indexing", "pandas", "dataframe" ]
I have a data frame from which I remove some rows. As a result, I get a data frame in which index is something like that: `[1,5,6,10,11]` and I would like to reset it to `[0,1,2,3,4]`. How can I do it? **ADDED** The following seems to work: ``` df = df.reset_index() del df['index'] ``` The following does not work: ...
`reset_index()` is what you're looking for. if you don't want it saved as a column, then ``` df = df.reset_index(drop=True) ```
Optimal way to compute pairwise mutual information using numpy
20,491,028
21
2013-12-10T09:48:59Z
20,505,476
22
2013-12-10T21:20:10Z
[ "python", "performance", "numpy", "scipy", "information-theory" ]
For an *m x n* matrix, what's the optimal (fastest) way to compute the mutual information for all pairs of columns (*n x n*)? By [mutual information](http://en.wikipedia.org/wiki/Mutual_information), I mean: > *I(X, Y) = H(X) + H(Y) - H(X,Y)* where *H(X)* refers to the Shannon entropy of *X*. Currently I'm using `n...
I can't suggest a faster calculation for the outer loop over the n\*(n-1)/2 vectors, but your implementation of `calc_MI(x, y, bins)` can be simplified if you can use scipy version 0.13 or [scikit-learn](http://scikit-learn.org/stable/index.html). In scipy 0.13, the `lambda_` argument was added to [`scipy.stats.chi2_c...
Python scipy chisquare returns different values than R chisquare
20,492,419
4
2013-12-10T10:50:01Z
20,493,984
8
2013-12-10T12:01:37Z
[ "python", "numpy", "scipy", "chi-squared" ]
I am trying to use `scipy.stats.chisquare`. I have built a toy example: ``` In [1]: import scipy.stats as sps In [2]: import numpy as np In [3]: sps.chisquare(np.array([38,27,23,17,11,4]), np.array([98, 100, 80, 85,60,23])) Out[11]: (240.74951271813072, 5.302429887719704e-50) ``` The same example in `R` returns: `...
For this `chisq.test` call python equivalent is [`chi2_contingency`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html): > This function computes the chi-square statistic and p-value for the hypothesis test of independence of the observed frequencies [**in the contingency table**](h...
Solving a graph issue with Python
20,493,932
11
2013-12-10T11:59:51Z
20,647,733
7
2013-12-18T00:54:12Z
[ "python", "algorithm", "graph", "path", "networkx" ]
I have one situation and I would like to approach this problem with Python, but unfortunately I don't have enough knowledge about the graphs. I found one library which seems very suitable for this relatively simple task, `networkx`, but I am having issues doing exact things I want, which should be fairly simple. I hav...
You might be able to use the all\_simple\_paths() function for your problem if you construct your graph differently. Simple paths are those with no repeated nodes. So for your constraints here are some suggestions to build the graph so you can run that algorithm unmodified. * only nodes of specific type can be travers...
Why disable the garbage collector?
20,495,946
12
2013-12-10T13:32:43Z
20,495,977
13
2013-12-10T13:34:14Z
[ "python", "garbage-collection" ]
Pythons [`gc.disable`](http://docs.python.org/3.3/library/gc.html#gc.disable) disables automatic garbage collection. As I understand it, that would have quite some side-effects. Why would anyone want to disable automatic garbage collection, and how could one effectively manage memory without it?
One use for disabling the garbage collector is to get more consistent results when timing the performance of code. [The `timeit` module](http://hg.python.org/cpython/file/a3bdbe220f8a/Lib/timeit.py#l176) does this. ``` def timeit(self, number=default_number): if itertools: it = itertools.repeat(None, numbe...
How do python Set Comprehensions work?
20,496,536
12
2013-12-10T14:01:34Z
20,497,109
7
2013-12-10T14:29:16Z
[ "python", "set", "generator", "set-comprehension" ]
**Q1** - Is the following a `set()` of a `generator expression` or a `set comprehension`? (Or are they same? If so, are `list` & `dict` comprehensions also *corresponding type-cast* on generators?) ``` my_set = {x for x in range(10)} ``` **Q2** - Does the evaluation consider duplicate values & then remove them by app...
**Q1 :** Yes, yes, yes and yes. Or at least they behave like this. It's a little bit different if you're taking a look at the bytecode. Let's disassembly this code (Python 2.7) : ``` def list_comp(l): return [x+1 for x in l] def dict_comp(l): return {x+1:0 for x in l} def set_comp(l): return {x+1 for x i...
Installing NumPy with pip fails on Ubuntu
20,497,339
8
2013-12-10T14:40:59Z
20,497,374
16
2013-12-10T14:42:44Z
[ "python", "ubuntu", "numpy", "pip" ]
When I try: ``` $ sudo pip install numpy ``` on my Ubuntu 12.04 server, I get: ``` ------------------------------------------------------------ /usr/local/bin/pip run on Tue Dec 10 18:25:54 2013 Downloading/unpacking numpy Getting page https://pypi.python.org/simple/numpy/ URLs to search for versions for numpy:...
It seems like your system does not have `gcc`. Install build tools using following command: ``` apt-get install build-essential python-dev ```
Installing NumPy with pip fails on Ubuntu
20,497,339
8
2013-12-10T14:40:59Z
20,497,608
7
2013-12-10T14:54:12Z
[ "python", "ubuntu", "numpy", "pip" ]
When I try: ``` $ sudo pip install numpy ``` on my Ubuntu 12.04 server, I get: ``` ------------------------------------------------------------ /usr/local/bin/pip run on Tue Dec 10 18:25:54 2013 Downloading/unpacking numpy Getting page https://pypi.python.org/simple/numpy/ URLs to search for versions for numpy:...
Some of these packages may not be required (don't have time to check in detail) but in a setup script of mine to install the NumPy stack I install the following Ubuntu packages first: ``` - build-essential - gfortran - libatlas-base-dev - libatlas3gf-base - python-dev - libjpeg-dev - libxml2-dev - libfreetype6-dev - l...
User Authentication in Django Rest Framework + Angular.js web app
20,498,317
50
2013-12-10T15:24:04Z
20,500,498
47
2013-12-10T16:56:56Z
[ "python", "django", "angularjs", "authentication", "django-rest-framework" ]
I'm working on a webapp where users can login to see their online wine cellar. I've got the Django REST models setup, as well as the front-end design in Angular but I'm having trouble putting the pieces together and my main issue is for user authentication. I've read many posts on here and various tutorials but I can...
I imagine there are a lot of ways to do this, let me explain what I do, hopefully it is helpful. This is going to be a long post. I would love to hear how others do this, or better ways of implementing the same approach. You can also check out my seed project on Github, [Angular-Django-Seed](https://github.com/zackargy...
User Authentication in Django Rest Framework + Angular.js web app
20,498,317
50
2013-12-10T15:24:04Z
24,666,564
12
2014-07-10T02:28:13Z
[ "python", "django", "angularjs", "authentication", "django-rest-framework" ]
I'm working on a webapp where users can login to see their online wine cellar. I've got the Django REST models setup, as well as the front-end design in Angular but I'm having trouble putting the pieces together and my main issue is for user authentication. I've read many posts on here and various tutorials but I can...
Check out django-rest-auth and angular-django-registration-auth also <https://github.com/Tivix/angular-django-registration-auth> <https://github.com/Tivix/django-rest-auth> We've tried to solve most common Django auth/registration related things from a backend and angular perspective in these two libraries. Thanks!
Run local python script on remote server
20,499,074
8
2013-12-10T15:55:49Z
22,915,340
18
2014-04-07T14:29:01Z
[ "python", "ssh", "remote-debugging", "scp" ]
I'm debugging some python script that must run on my virtual machine. And, I prefer to edit the scripts locally(outside of virtual machines). So I find it's **tedious** to `scp` modified scripts to virtual machines every time. Can anyone suggests some effective way? Particularly, I'm wondering if it's possible to exec...
It is possible using ssh. Python accepts hyphen(-) as argument to execute the standard input, ``` cat hello.py | ssh [email protected] python - ``` Run **python --help** for more info.
Run local python script on remote server
20,499,074
8
2013-12-10T15:55:49Z
27,412,611
15
2014-12-10T23:13:29Z
[ "python", "ssh", "remote-debugging", "scp" ]
I'm debugging some python script that must run on my virtual machine. And, I prefer to edit the scripts locally(outside of virtual machines). So I find it's **tedious** to `scp` modified scripts to virtual machines every time. Can anyone suggests some effective way? Particularly, I'm wondering if it's possible to exec...
Although this question isn't quite new and an answer was already chosen, I would like to share another nice approach. Using the [paramiko](https://github.com/paramiko/paramiko) library - a pure python implementation of SSH2 - your python script can connect to a remote host via SSH, copy itself (!) to that host and the...
search for element in list and replace it by multiple items
20,499,312
8
2013-12-10T16:05:56Z
20,499,370
11
2013-12-10T16:07:52Z
[ "python" ]
What is the pythonic way to search through the given list `['a', 'b', 'c']` for the element `b` replace it and insert multiple items `b1, b2, b3` so that the list finally reads as `['a', 'b1', 'b2', 'b3', 'c']`
Using slice notation: ``` >>> lst = ['a', 'b', 'c'] >>> i = lst.index('b') # This raises ValueError if there's no 'b' in the list. >>> lst[i:i+1] = 'b1', 'b2', 'b3' >>> lst ['a', 'b1', 'b2', 'b3', 'c'] ``` **NOTE** This changes only the first matching item.
First call to pytz.timezone is slow in virtualenv
20,500,910
9
2013-12-10T17:13:49Z
20,504,407
10
2013-12-10T20:20:59Z
[ "python", "virtualenv", "pytz" ]
I have installed pytz (v2013.8, but it happens in 2013.b, 2011k) in a virtualenv. The first call to ``` pytz.timezone("US/Eastern") ``` takes about 4 seconds. In a regular environment this is essentially instantaneous. Does anyone have a trick to get this to run faster?
I actually came across the answer by playing around and looking at the source code. Since it gets its timezone settings from within the egg and the first call to timezone has to check that all the timezone files exist, the first call could be slow depending on how the os has to find those files. If pytz is installed us...
Idiomatic way to unpack variable length list
20,501,440
8
2013-12-10T17:38:23Z
20,501,810
12
2013-12-10T17:55:33Z
[ "python", "iterable-unpacking" ]
I'm reading a file and unpacking each line like this: ``` for line in filter(fh): a, b, c, d = line.split() ``` However, it's possible that line may have more or fewer columns than the variables I wish to unpack. In the case when there are fewer, I'd like to assign `None` to the dangling variables, and in the case ...
Fix the length of the list, padding with `None`. ``` def fixLength(lst, length): return (lst + [None] * length)[:length] ```
how to save captured image using pygame to disk
20,502,237
5
2013-12-10T18:18:24Z
20,502,651
7
2013-12-10T18:40:32Z
[ "python", "pygame" ]
this is my code, which starts the webcam : ``` import pygame.camera import pygame.image import sys pygame.camera.init() cameras = pygame.camera.list_cameras() print "Using camera %s ..." % cameras[0] webcam = pygame.camera.Camera(cameras[0]) webcam.start() # grab first frame img = webcam.get_image() WIDTH = img...
When you call webcam.get\_image it returns an RGB Surface. So just call pygame.image.save(), the file type is determined by the extension and defaults to TGA. Options are BMP, TGA, PNG, and JPEG. In this case you could append this line to your file. ``` pygame.image.save(img, "image.jpg") ``` Check out <http://www.py...
Python Flask working with wraps
20,503,183
3
2013-12-10T19:09:22Z
20,503,292
7
2013-12-10T19:16:50Z
[ "python", "flask", "python-decorators" ]
Trying to setup a login page with Python and Flask and getting an Error: *(line 33 is the with `@login_required`)* ``` Traceback (most recent call last): File "routes.py", line 33, in <module> @login_required File "/home/pi/FlaskTutorial/local/lib/python2.7/site-packages/flask/app.py", line 1013, in decorator ...
You indented the `return wrap` line too far, now your decorator returns a `None` value. Unindent the last line: ``` def login_required(test): @wraps(test) def wrap(*args, **kwargs): if 'logged_in' in session: return test(*args, **kwargs) else: flash('You need to login fi...
How to monkeypatch python's datetime.datetime.now with py.test?
20,503,373
6
2013-12-10T19:20:53Z
20,503,374
12
2013-12-10T19:20:53Z
[ "python", "datetime", "mocking", "py.test" ]
I need to test functions which uses `datetime.datetime.now()`. What is the easiest way to do this?
You need to monkeypatch datetime.now function. In example below, I'm creating fixture which I can re-use later in other tests: ``` import datetime import pytest FAKE_TIME = datetime.datetime(2020, 12, 25, 17, 05, 55) @pytest.fixture def patch_datetime_now(monkeypatch): class mydatetime: @classmethod ...
How to monkeypatch python's datetime.datetime.now with py.test?
20,503,373
6
2013-12-10T19:20:53Z
28,080,767
7
2015-01-22T03:23:15Z
[ "python", "datetime", "mocking", "py.test" ]
I need to test functions which uses `datetime.datetime.now()`. What is the easiest way to do this?
There is [`freezegun` module](http://stevepulec.com/freezegun/): ``` from datetime import datetime from freezegun import freeze_time # $ pip install freezegun @freeze_time("Jan 14th, 2012") def test_nice_datetime(): assert datetime.now() == datetime(2012, 1, 14) ``` `freeze_time()` could also be used as a contex...
Python C program subprocess hangs at "for line in iter"
20,503,671
12
2013-12-10T19:38:35Z
20,509,641
19
2013-12-11T02:50:02Z
[ "python", "c", "subprocess", "hang" ]
Ok so I'm trying to run a C program from a python script. Currently I'm using a test C program: ``` #include <stdio.h> int main() { while (1) { printf("2000\n"); sleep(1); } return 0; } ``` To simulate the program that I will be using, which takes readings from a sensor constantly. Then I'm trying to read th...
It is a block buffering issue. What follows is an extended for your case version of my answer to [Python: read streaming input from subprocess.communicate()](http://stackoverflow.com/a/17698359/4279) question. ## Fix stdout buffer in C program directly `stdio`-based programs as a rule are line buffered if they are r...
simple/efficient way to expand a pandas dataframe
20,504,881
4
2013-12-10T20:47:38Z
20,504,957
8
2013-12-10T20:52:19Z
[ "python", "pandas" ]
Say i have a list and a pandas dataframe ``` import pandas as pd x = pd.DataFrame({'a': range(2), 'b': range(2)}) y = [1,2,3] ``` I want to get a dataframe that looks roughly like this: ``` a b y 0 0 1 1 1 1 0 0 2 1 1 2 0 0 3 1 1 3 ``` Is there a simple way to do this?
That is called [cartesian product](http://en.wikipedia.org/wiki/Cartesian_product). Convert to dataframe ``` >>> y = pd.DataFrame(y, columns=list('y')) ``` add constant key ``` >>> x['k'] = 1 >>> y['k'] = 1 ``` and merge over it ``` >>> pd.merge(y, x, on='k')[['a', 'b', 'y']] a b y 0 0 0 1 1 1 1 1 2 0 ...
Add a legend in a 3D scatterplot with scatter() in Matplotlib
20,505,105
2
2013-12-10T21:00:43Z
20,505,720
10
2013-12-10T21:31:53Z
[ "python", "matplotlib" ]
I want to create a 3D scatterplot with different datasets in the same plot and a legend with their labels. The problem I am facing is that I cannot properly add the legend and I get a plot with an empty label as the figure in <http://tinypic.com/view.php?pic=4jnm83&s=5#.Uqd-05GP-gQ>. More specifically, I get the error:...
``` scatter1_proxy = matplotlib.lines.Line2D([0],[0], linestyle="none", c=colors[0], marker = 'o') scatter2_proxy = matplotlib.lines.Line2D([0],[0], linestyle="none", c=colors[1], marker = 'v') ax.legend([scatter1_proxy, scatter2_proxy], ['label1', 'label2'], numpoints = 1) ``` The problem is that the legend function ...
Python Tornado: WSGI module missing?
20,505,495
4
2013-12-10T21:21:04Z
20,524,148
12
2013-12-11T16:08:39Z
[ "python", "flask", "tornado" ]
I did a `pip install tornado` but I cannot run the following code because WSGI module is missing?? <http://flask.pocoo.org/docs/deploying/wsgi-standalone/> ``` from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from myapp import app http_server = HTTPSe...
If your file is named tornado.py, it will try to import things from that file instead of the directory on site-packages. This is probably the most common source of "no module named X" ImportErrors. Rename the file and it should work.
Python property vs method when no access to attribute is needed?
20,506,612
8
2013-12-10T22:23:18Z
20,506,966
9
2013-12-10T22:46:22Z
[ "python", "properties" ]
I am reading "Python programming for the absolute beginner" and in there there is this piece of code: ``` @property def mood(self): unhappiness = self.hunger + self.boredom if unhappiness < 5: m = "happy" elif 5 <= unhappiness <= 10: m = "okay" elif 11 <= unhappiness <= 15: m = ...
Properties are not intended for providing access to a private attribute. Properties are intended to give you the option of making zero-argument methods accessible as if they were attributes, so that a given "attribute" can be implemented as either a calculation or an actual attribute, without changing the interface of ...
What's wrong with this solution for Max Counters codility challenge
20,506,849
3
2013-12-10T22:38:37Z
21,261,265
7
2014-01-21T14:44:20Z
[ "python", "arrays", "algorithm" ]
So I've been going through the tests on codility and got bit stuck with the "Max Counters" one (link <https://codility.com/demo/take-sample-test/max_counters>). My first, and obvious solution was the following one: ``` def solution(N, A): counters = N * [0]; for a in A: if 1 <= a <= N: ...
Check this one (python, get's 100 score): The secret is not to update all the counters every time you get the instruction to bump them all up to a new minimum value. This incurs an operation involving every counter on every occasion, and is the difference between a ~60% score and a 100% score. Instead, avoid this hit...
Python: How do I use DictReader twice?
20,507,228
6
2013-12-10T23:04:35Z
20,507,293
7
2013-12-10T23:09:22Z
[ "python", "csv", "dictionary" ]
This feels like a very basic question, but I can't find any mention of it elsewhere. I'm a beginning Python user. When I read in data using DictReader, and then use the dictionary, I'm unable to reference it again. For example, using this code: ``` #!/usr/bin/python import csv import cgi import cgitb cgitb.enable() ...
You just need to seek the file back to the start: ``` with open("blurbs.csv","rb") as f: blurbs = csv.DictReader(f, delimiter="\t") for row in blurbs: print row f.seek(0) for row in blurbs: print row ``` Alternatively you can wrap the dictionary generation into a list of dicts and oper...
writing a pytest function for checking the output on console (stdout) in python?
20,507,601
8
2013-12-10T23:34:20Z
20,507,769
8
2013-12-10T23:46:09Z
[ "python", "printing", "stdout", "py.test" ]
[This link](http://pytest.org/latest/capture.html) gives a description how to use pytest for capturing console outputs. I tried on this following simple code, but I get error ``` import sys import pytest def f(name): print "hello "+ name def test_add(capsys): f("Tom") out,err=capsys.readouterr() asser...
Use the `capfd` fixture. **Example:** ``` def test_foo(capfd): foo() # Writes "Hello World!" to stdout out, err = capfd.readouterr() assert out == "Hello World!" ``` See: <http://pytest.org/latest/fixture.html> for more details And see: `py.test --fixtures` for a list of builtin fixtures. Your example...
Overloading Addition, Subtraction, and Multiplication Operators in Python
20,507,745
6
2013-12-10T23:44:22Z
20,507,800
8
2013-12-10T23:50:36Z
[ "python", "class", "vector", "operators" ]
How do you go about overloading the addition, subtraction, and multiplication operator so we can add, subtract, and multiply two vectors of different or identical sizes? For example, if the vectors are different sizes we must be able to add, subtract, or multiply the two vectors according to the smallest vector size? ...
You [define the `__add__`, `__sub__`, and `__mul__`](http://docs.python.org/2/reference/datamodel.html#emulating-numeric-types) methods for the class, that's how. Each method takes two objects (the operands of `+`/`-`/`*`) as arguments and is expected to return the result of the computation.
Why does manage.py syncdb fail to connect to google cloud sql database?
20,508,494
4
2013-12-11T00:53:04Z
22,511,903
9
2014-03-19T16:15:19Z
[ "python", "google-app-engine", "google-cloud-sql" ]
During a recent update of an app on Google App Engine I was in the process of updating the database with: ``` SETTINGS_MODE='prod' ./manage.py syncdb ``` This worked last time I ran it, but now I am getting the following error: ``` Traceback (most recent call last): File "./manage.py", line 10, in <module> exe...
## Intro I'm going to leave a more detailed answer here for those that have also been tripped up by this, I realise the other one has already been accepted but hopefully this will help someone. We are on Django 1.6 at the time of writing. It basically comes down to this: the [Django <-> CloudSQL docs](https://develop...
python print "hello world" vs "hello world"
20,510,585
3
2013-12-11T04:35:34Z
20,510,610
7
2013-12-11T04:37:37Z
[ "python" ]
``` >>> print "hello world" hello world >>> "hello world" 'hello world' >>> ``` What is the difference? A complete noob question. python hello world example mostly uses ``` print "hello world" ``` Can I strip that `print` and just use `"Hello world"` for giving a python introduction?
The difference is that `print` calls `str` whereas the default action of the REPL (read evaluate print loop) is to call `repr` on the object unless it is `None`. Note that if you aren't working in the interactive interpreter (you're not in the REPL), then you won't see *any* output in the version without `print`. Als...
Python: count frequency of words in a list
20,510,768
10
2013-12-11T04:50:47Z
20,510,883
7
2013-12-11T05:00:45Z
[ "python", "list", "word", "frequency" ]
For a program assignment, I am required to count the frequency of the words from a file. I have been looking for help on this website and others but the methods they show are ones we have not learned in class so I cannot use them. The methods I have found so far use either Counter or dictionaries which we have not lear...
``` words = file("test.txt", "r").read().split() #read the words into a list. uniqWords = sorted(set(words)) #remove duplicate words and sort for word in uniqWords: print words.count(word), word ```
Python: count frequency of words in a list
20,510,768
10
2013-12-11T04:50:47Z
20,510,989
9
2013-12-11T05:09:28Z
[ "python", "list", "word", "frequency" ]
For a program assignment, I am required to count the frequency of the words from a file. I have been looking for help on this website and others but the methods they show are ones we have not learned in class so I cannot use them. The methods I have found so far use either Counter or dictionaries which we have not lear...
You can use ``` from collections import Counter ``` It supports Python 2.7,read more information [here](http://docs.python.org/2/library/collections.html) 1. ``` >>>c = Counter('abracadabra') >>>c.most_common(3) [('a', 5), ('r', 2), ('b', 2)] ``` use dict ``` >>>d={1:'one', 2:'one, 3:'two'} >>>c = Counter(d.val...
Python: count frequency of words in a list
20,510,768
10
2013-12-11T04:50:47Z
20,511,316
29
2013-12-11T05:37:04Z
[ "python", "list", "word", "frequency" ]
For a program assignment, I am required to count the frequency of the words from a file. I have been looking for help on this website and others but the methods they show are ones we have not learned in class so I cannot use them. The methods I have found so far use either Counter or dictionaries which we have not lear...
use this ``` >>> from collections import Counter >>> list1=['apple','egg','apple','banana','egg','apple'] >>> counts = Counter(list1) >>> print(counts) >>>Counter({'apple': 3, 'egg': 2, 'banana': 1}) ```
Colorize Voronoi Diagram
20,515,554
26
2013-12-11T09:39:56Z
20,678,647
28
2013-12-19T10:07:09Z
[ "python", "matplotlib", "scipy", "visualization", "voronoi" ]
I'm trying to colorize a Voronoi Diagram created using [`scipy.spatial.Voronoi`](http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.spatial.Voronoi.html). Here's my code: ``` import numpy as np import matplotlib.pyplot as plt from scipy.spatial import Voronoi, voronoi_plot_2d # make up data points points =...
The Voronoi data structure contains all the necessary information to construct positions for the "points at infinity". Qhull also reports them simply as `-1` indices, so Scipy doesn't compute them for you. <https://gist.github.com/pv/8036995> <http://nbviewer.ipython.org/gist/pv/8037100> ``` import numpy as np impor...
Django - Delete file from amazon S3
20,516,570
3
2013-12-11T10:25:53Z
20,517,159
7
2013-12-11T10:51:53Z
[ "python", "django", "file", "amazon-web-services", "amazon-s3" ]
I have a problem where deleting an object form the admin won't delete the file associated with it. after some research I decided to implement a post\_delete in the model. For some reason I am not able to make the s3 delete the file, even after searching numerous guides and snippets, maybe someone here knows. I use djan...
You need to call [FieldFile's](https://docs.djangoproject.com/en/1.5/ref/models/fields/#django.db.models.fields.files.FieldFile) `delete()` method to remove the file in S3. In your case, add a [`pre_delete`](https://docs.djangoproject.com/en/1.7/ref/signals/#pre-delete) signal where you call it: ``` @receiver(models.s...
TypeError while using django rest framework tutorial
20,519,116
14
2013-12-11T12:26:17Z
22,697,034
43
2014-03-27T19:12:37Z
[ "python", "django", "rest", "typeerror", "django-rest-framework" ]
I am new to using Django Rest framework, i am following this tutorial [Django-Rest-Framework](http://django-rest-framework.org/tutorial/1-serialization) Instead of snippets my model consists of a userprofile as given below: ``` class UserProfile(models.Model): user = models.OneToOneField(User) emp_code = ...
Just to let others know, I kept getting this same error and found that I forgot to include a comma in my `REST_FRAMEWORK`. I had this: ``` 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ), ``` instead of this: ``` 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAut...
Create heatmap using pandas TimeSeries
20,520,246
11
2013-12-11T13:19:21Z
20,523,271
19
2013-12-11T15:34:47Z
[ "python", "datetime", "numpy", "matplotlib", "pandas" ]
I need to create MatplotLib heatmap (pcolormesh) using Pandas DataFrame TimeSeries column (df\_all.ts) as my X-axis. How to convert Pandas TimeSeries column to something which can be used as X-axis in np.meshgrid(x, y) function to create heatmap? The workaround is to create Matplotlib drange using same parameters as i...
I do not know what you mean by heat map for a time series, but for a dataframe you may do as below: ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from itertools import product from string import ascii_uppercase from matplotlib import patheffects m, n = 4, 7 # 4 rows, 7 columns df = pd.Da...
Pythonic way of converting integers to string
20,521,862
2
2013-12-11T14:33:07Z
20,521,892
9
2013-12-11T14:34:32Z
[ "python", "python-2.7" ]
``` >>> foo = 1 >>> type(foo) <type 'int'> >>> type(str(foo)) <type 'str'> >>> type(`foo`) <type 'str'> ``` Which is the more Pythonic way of converting integers to strings? I have always been using the first method but I now find the second method more readable. Is there a practical difference?
[String conversions using backticks](http://docs.python.org/2/reference/expressions.html#string-conversions) are a shorthand notation for calling [`repr()`](http://docs.python.org/2/library/functions.html#repr) on a value. For integers, the resulting output of `str()` and `repr()` *happens* to be the same, but it is *n...
ipython --pylab vs ipython
20,525,459
8
2013-12-11T17:06:56Z
20,528,503
13
2013-12-11T19:44:17Z
[ "python", "matplotlib", "ipython" ]
What does `ipython --pylab` exactly do? Is `ipython --pylab` **exactly** equivalent to: ``` > ipython > from pylab import * ``` If not, what are the differences? Say I launch IPython **without** the `--pylab` arguments, how can I bring it to the same state as if I had started it **with** `--pylab`?
`--pylab[=option]` is almost technically equivalent to `%pylab option` as the difference that you cannot un-pylab a `--pylab` kernel, but you can restart a `%pylab` kernel. `%pylab` is a little more that just `from pylab import *` (see `%pylab?`for a longer explanation), but in short yes it imports a lot of things, bu...
Average of two consecutive elements in the list in Python
20,527,563
3
2013-12-11T18:52:18Z
20,527,601
14
2013-12-11T18:54:42Z
[ "python" ]
I have a list of even number of float numbers: > [2.34, 3.45, 4.56, 1.23, 2.34, 7.89, ...]. My task is to calculate average of 1 and 2 elements, 3 and 4, 5 and 6, etc. What is the short way to do this in Python?
``` data = [2.34, 3.45, 4.56, 1.23, 2.34, 7.89] print [(a + b) / 2 for a, b in zip(data[::2], data[1::2])] ``` Explanation: `data[::2]` is the elements `2.34, 4.56, 2.34` `data[1::2]` is the elements `3.45, 1.23, 7.89` `zip` combines them into 2-tuples: `(2.34, 3.45), (4.56, 1.23), (2.34, 7.89)`