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
How to add header row to a pandas DataFrame
34,091,877
8
2015-12-04T15:35:59Z
34,094,058
8
2015-12-04T17:27:21Z
[ "python", "csv", "pandas", "header" ]
I am reading a csv file into `pandas`. This csv file constists of four columns and some rows, but does not have a header row, which I want to add. I have been trying the following: ``` Cov = pd.read_csv("path/to/file.txt", sep='\t') Frame=pd.DataFrame([Cov], columns = ["Sequence", "Start", "End", "Coverage"]) Frame.to...
Alternatively you could read you csv with `header=None` and then add it with `df.columns`: ``` Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None) Cov.columns = ["Sequence", "Start", "End", "Coverage"] ```
python logistic regression (beginner)
34,093,264
2
2015-12-04T16:44:39Z
34,093,737
7
2015-12-04T17:08:09Z
[ "python", "machine-learning", "scikit-learn", "logistic-regression", "patsy" ]
I'm working on teaching myself a bit of logistic regression using python. I'm trying to apply the lessons in the walkthrough [here](https://github.com/justmarkham/gadsdc1/blob/master/logistic_assignment/kevin_logistic_sklearn.ipynb) to the small dataset in the wikipedia entry[here](https://en.wikipedia.org/wiki/Logisti...
## Solution Just change the model creation line to ``` model = LogisticRegression(C=100000, fit_intercept=False) ``` ## Analysis of the problem By default, sklearn solves **regularized LogisticRegression**, with fitting strength `C=1` (small C-big regularization, big C-small regularization). > This class implement...
Django: Support for string view arguments to url() is deprecated and will be removed in Django 1.10
34,096,424
20
2015-12-04T19:56:59Z
34,096,508
42
2015-12-04T20:02:31Z
[ "python", "django", "url", "deprecated" ]
New python/Django user (and indeed new to SO): When trying to migrate my Django project, I get an error: ``` RemovedInDjango110Warning: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got main.views.home). Pass the callable instead. url(r'^$', 'main.views.home') ``` A...
I have found the answer to my question. It was indeed an import error. For Django 1.10, you now have to import the app's view.py, and then pass the second argument of url() without quotes. Here is my code now in urls.py: ``` from django.conf.urls import url from django.contrib import admin import main.views urlpatter...
Django: Support for string view arguments to url() is deprecated and will be removed in Django 1.10
34,096,424
20
2015-12-04T19:56:59Z
34,096,518
7
2015-12-04T20:02:50Z
[ "python", "django", "url", "deprecated" ]
New python/Django user (and indeed new to SO): When trying to migrate my Django project, I get an error: ``` RemovedInDjango110Warning: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got main.views.home). Pass the callable instead. url(r'^$', 'main.views.home') ``` A...
You should be able to use the following: ``` from django.conf.urls import url from django.contrib import admin from main import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home) ] ``` I'm not absolutely certain what your directory structure looks like, but using a relative impor...
Identifier normalization: Why is the micro sign converted into the Greek letter mu?
34,097,193
16
2015-12-04T20:49:37Z
34,097,194
13
2015-12-04T20:49:37Z
[ "python", "python-3.x", "unicode", "identifier", "python-internals" ]
I just stumbled upon the following odd situation: ``` >>> class Test: µ = 'foo' >>> Test.µ 'foo' >>> getattr(Test, 'µ') Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> getattr(Test, 'µ') AttributeError: type object 'Test' has no attribute 'µ' >>> 'µ'.encode(), dir(Test)[...
There are two different characters involved here. One is the [MICRO SIGN](http://www.fileformat.info/info/unicode/char/00b5/index.htm), which is the one on the keyboard, and the other is [GREEK SMALL LETTER MU](http://www.fileformat.info/info/unicode/char/03bc/index.htm). To understand what’s going on, we should tak...
How can I convert a tensor into a numpy array in TensorFlow?
34,097,281
15
2015-12-04T20:55:54Z
34,097,344
17
2015-12-04T20:59:39Z
[ "python", "numpy", "tensorflow" ]
I know how to convert a numpy array into a tensor object with the function `tf.convert_to_tensor(img.eval())`. My problem is that after I apply some preprocessing to this tensors in terms of brightness, contrast, etc, I would like to view the resulting transformations to evaluate and tweak my parameters. How can I co...
To convert back from tensor to numpy array you can simply run `.eval()` on the transformed tensor.
Why doesn't `x != x.isdigit()` work?
34,100,616
3
2015-12-05T02:38:02Z
34,100,630
8
2015-12-05T02:40:18Z
[ "python", "python-3.x" ]
I need to make a loop that prompts the user to enter a valid string of digits, and has to ask the user until they enter a correct input. I think I have the right idea here but I am not entirely sure how to correct the wrong input. ``` def c(): x = input("Enter a String of Digits") while x != x.isdigit() ...
`str.isdigit()` returns a boolean (True / False), don't compare it with `x` itself, but just use the return value: ``` def c(): x = input("Enter a String of Digits") while not x.isdigit(): x = input("enter correct data string") print("True") c() ``` * SyntaxError fixed: add missing `:` in `while ...
Unexpected output using Pythons' ternary operator in combination with lambda
34,100,732
8
2015-12-05T02:56:00Z
34,218,180
9
2015-12-11T07:26:54Z
[ "python", "boolean", "ternary-operator", "conditional-expressions" ]
I have a specific situation in which I would like to do the following (actually it is more involved than this, but I reduced the problem to the essence): ``` >>> (lambda e: 1)(0) if (lambda e: True)(0) else (lambda e: 2)(0) True ``` which is a difficult way of writing: ``` >>> 1 if True else 2 1 ``` but in reality ...
I think I figured out why the bug is happening, and why your repro is Python 3 specific. [Code objects do equality comparisons by value](https://hg.python.org/cpython/file/3.5/Objects/codeobject.c#l535), rather than by pointer, strangely enough: ``` static PyObject * code_richcompare(PyObject *self, PyObject *other, ...
POS tagging using spaCy
34,102,420
5
2015-12-05T07:25:25Z
34,105,051
8
2015-12-05T12:45:14Z
[ "python", "nlp", "spacy" ]
I am trying to do POS tagging using the spaCy module in Python. Here is my code for the same ``` from spacy.en import English, LOCAL_DATA_DIR import spacy.en import os data_dir = os.environ.get('SPACY_DATA', LOCAL_DATA_DIR) nlp = English(parser=False, tagger=True, entity=False) def print_fine_pos(token): retur...
`TL;DR: You should accept the occasional error.` Details: Spacy's tagger is statistical, meaning that the tags you get are its best estimate based on the data it was shown during training. I would guess those data did not contain the word `dosa`. The tagger had to guess, and guessed wrong. There isn't an easy way to ...
Upgrade pip in Amazon Linux
34,103,119
6
2015-12-05T09:03:57Z
34,584,537
8
2016-01-04T04:06:04Z
[ "python", "amazon-ec2", "pip" ]
I wanted to deploy my Python app on Amazon Linux AMI 2015.09.1, which has Python2.7 (default) and pip (6.1.1). Then, I upgraded the pip using the command: ``` sudo pip install -U pip ``` However, it seemed broken, and showed the message when I tried to install packages: ``` pkg_resources.DistributionNotFound: pip==6...
Try: ``` sudo which pip ``` This may reveal something like 'no pip in ($PATH)'. If that is the case, you can then do: ``` which pip ``` Which will give you a path like `/usr/local/bin/pip`. Copy + paste the path to pip to the sbin folder by running: `sudo cp /usr/local/bin/pip /usr/sbin/` This will allow you to ...
Unpack nested list for arguments to map()
34,110,317
5
2015-12-05T20:11:44Z
34,110,336
7
2015-12-05T20:13:45Z
[ "python", "arguments", "map-function", "argument-unpacking" ]
I'm sure there's a way of doing this, but I haven't been able to find it. Say I have: ``` foo = [ [1, 2], [3, 4], [5, 6] ] def add(num1, num2): return num1 + num2 ``` Then how can I use `map(add, foo)` such that it passes `num1=1`, `num2=2` for the first iteration, i.e., it does `add(1, 2)`, then `ad...
It sounds like you need [`starmap`](https://docs.python.org/3/library/itertools.html#itertools.starmap): ``` >>> import itertools >>> list(itertools.starmap(add, foo)) [3, 7, 11] ``` This unpacks each argument `[a, b]` from the list `foo` for you, passing them to the function `add`. As with all the tools in the `iter...
Why does Python "preemptively" hang when trying to calculate a very large number?
34,113,609
48
2015-12-06T03:14:09Z
34,113,926
12
2015-12-06T04:09:27Z
[ "python", "linux" ]
I've asked [this question](http://stackoverflow.com/questions/34014099/how-do-i-automatically-kill-a-process-that-uses-too-much-memory-with-python) before about killing a process that uses too much memory, and I've got most of a solution worked out. However, there is one problem: calculating massive numbers seems to b...
Use a function. It does seem that Python tries to precompute integer literals (I only have empirical evidence; if anyone has a source please let me know). This would normally be a helpful optimization, since the vast majority of literals in scripts are probably small enough to not incur noticeable delays when precompu...
Why does Python "preemptively" hang when trying to calculate a very large number?
34,113,609
48
2015-12-06T03:14:09Z
34,114,371
51
2015-12-06T05:25:25Z
[ "python", "linux" ]
I've asked [this question](http://stackoverflow.com/questions/34014099/how-do-i-automatically-kill-a-process-that-uses-too-much-memory-with-python) before about killing a process that uses too much memory, and I've got most of a solution worked out. However, there is one problem: calculating massive numbers seems to b...
**TLDR:** Python precomputes constants in the code. If any very large number is calculated with at least one intermediate step, the process *will* be CPU time limited. --- It took quite a bit of searching, but I have discovered evidence that Python 3 **does** precompute constant literals that it finds in the code bef...
Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."
34,114,427
22
2015-12-06T05:36:10Z
34,115,677
19
2015-12-06T08:56:04Z
[ "python", "django" ]
When upgraded to django 1.9 from 1.8 I got this error. I checked answers for similar questions, but I didn't think this is an issue with any 3rd party packages or apps. ``` Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/kishore/.virtualenvs/and...
Try to add this lines to the top of your settings file: ``` import django django.setup() ``` And if this will not help you try to remove third-party applications from your installed apps list one-by-one.
How do I sort a key:list dictionary by values in list?
34,116,081
4
2015-12-06T09:52:50Z
34,116,185
9
2015-12-06T10:06:07Z
[ "python", "sorting", "dictionary" ]
I have a dictionary ``` mydict = {'name':['peter', 'janice', 'andy'], 'age':[10, 30, 15]} ``` How do I sort this dictionary based on key=="name" list? End result should be: ``` mydict = {'name':['andy', 'janice', 'peter'], 'age':[15, 30, 10]} ``` Or is dictionary the wrong approach for such data?
If you manipulate data, often it helps that each column be an observed variable (name, age), and each row be an observation (e.g. a sampled person). More on *tidy data* in this [PDF link](http://www.jstatsoft.org/article/view/v059i10/v59i10.pdf) > Bad programmers worry about the code. Good programmers worry about > da...
Checking a List for a Sequence
34,117,842
10
2015-12-06T13:18:52Z
34,118,255
7
2015-12-06T14:03:01Z
[ "python", "list" ]
I am wanting to check if a list has a specific sequence of elements. I have sorted the list which contains 7 elements, I now want to check of the first 4 are the same as each other and the last 3 are the same as each other. For what I want to achieve to be True the list would be like this: ``` list = ['1','1','1','1'...
You can slice a list. Take the first four elements: ``` >>> L = ['1','1','1','1','2','2','2'] >>> L[:4] ['1', '1', '1', '1'] ``` and the last three: ``` >>> L[-3:] ['2', '2', '2'] ``` A [set](https://docs.python.org/3.4/library/stdtypes.html#set) does not allow duplicates. Therefore: ``` >>> set(L[:4]) {1} ``` ...
Why do i need to create object of `QApplication` and what is the purpose of it in PyQt GUI programming?
34,125,618
6
2015-12-07T02:44:04Z
34,125,797
7
2015-12-07T03:08:55Z
[ "python", "qt", "pyqt5" ]
``` def main(): app = QtWidgets.QApplication(sys.argv) w = QtWidgets.QWidget() w.show() app.exec() ``` This is a very simple Python GUI program with `PyQt5` framework. Actually I'm not familiar with Qt, also a newbie to GUI programming. As in above program, there is a object of `QApplication` has cre...
You don't *need* to create QApplication, but it's a convenience class that does a lot of things for you. I won't explain everything it can possibly do for you -- you'll find that in [the manual](http://doc.qt.io/qt-5/qapplication.html) -- but I can explain two of the things you're doing in your sample code. ``` app =...
How do I exit this while loop?
34,129,037
5
2015-12-07T08:13:10Z
34,129,124
8
2015-12-07T08:20:35Z
[ "python", "loops", "while-loop" ]
I’m having trouble with exiting the following while loop. This is a simple program that prints `hello` if random value is greater than 5. The program runs fine once but when I try to run it again it goes into an infinite loop. ``` from random import * seed() a = randint(0,10) b = randint(0,10) c...
Your while loop might increment the variable count by 0, 1, 2 or 3. This might result in count going from a value below 20 to a value over 20. For example, if count's value is 18 and the following happens: ``` a > 5, count += 1 b > 5, count += 1 c > 5, count += 1 ``` After these operations, count's value would be 18...
Python: Line that does not start with #
34,129,811
10
2015-12-07T09:03:16Z
34,129,925
9
2015-12-07T09:09:54Z
[ "python", "regex" ]
I have a file that contains something like > # comment > # comment > not a comment > > # comment > # comment > not a comment I'm trying to read the file line by line and only capture lines that does not start with #. What is wrong with my code/regex? ``` import re def read_file(): pattern = re.compile("...
An alternative and yet simple approach is to only check if the first `char` of each line you read does not contain `#` character: ``` def read_file(): with open('list') as f: for line in f: if not line.lstrip().startswith('#'): print line ```
Python: Line that does not start with #
34,129,811
10
2015-12-07T09:03:16Z
34,130,001
10
2015-12-07T09:14:49Z
[ "python", "regex" ]
I have a file that contains something like > # comment > # comment > not a comment > > # comment > # comment > not a comment I'm trying to read the file line by line and only capture lines that does not start with #. What is wrong with my code/regex? ``` import re def read_file(): pattern = re.compile("...
[Iron Fist](http://stackoverflow.com/a/34129925/996114) shows the way you should probably do this; however, if you want to know what was wrong with your regex anyway, it should have been this: ``` ^[^#].* ``` Explanation: * `^` - match beginning of line. * `[^#]` - match something that is not `#`. `[^...]` is how yo...
DateField 'str' object has no attribute 'year'
34,131,468
2
2015-12-07T10:33:24Z
34,131,704
8
2015-12-07T10:46:08Z
[ "python", "django" ]
When trying to access the year and month attributes of my `DateField` objects I am getting the error > AttributeError: 'str' object has no attribute 'date'. I thought that DateField objects were saved as Python Datetime objects instead of strings. Here is the models.py: ``` class MonthControlRecord(models.Model): ...
In your test, you're setting the date as a string: ``` mcr = MonthControlRecord(employee=employee, first_day_of_month="2015-12-01") ``` Try setting it as a date: ``` your_date = datetime.date(2015, 12, 1) mcr = MonthControlRecord(employee=employee, first_day_of_month=your_date) ```
Difference between numpy dot() and Python 3.5+ matrix multiplication @
34,142,485
14
2015-12-07T20:23:26Z
34,142,617
13
2015-12-07T20:30:21Z
[ "python", "numpy", "matrix-multiplication", "python-3.5" ]
I recently moved to Python 3.5 and noticed the [new matrix multiplication operator (@)](https://docs.python.org/3/whatsnew/3.5.html#whatsnew-pep-465) sometimes behaves differently from the [numpy dot](http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html) operator. In example, for 3d arrays: ``` import nu...
The `@` operator calls the array's `__matmul__` method, not `dot`. This method is also present in the API as the function [`np.matmul`](http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.matmul.html). ``` >>> a = np.random.rand(8,13,13) >>> b = np.random.rand(8,13,13) >>> np.matmul(a, b).shape (8, 13, 13) `...
Sklearn How to Save a Model Created From a Pipeline and GridSearchCV Using Joblib or Pickle?
34,143,829
5
2015-12-07T21:46:23Z
34,166,178
7
2015-12-08T21:16:41Z
[ "python", "scikit-learn", "pipeline", "grid-search" ]
After identifying the best parameters using a `pipeline` and `GridSearchCV`, how do I `pickle`/`joblib` this process to re-use later? I see how to do this when it's a single classifier... ``` from sklearn.externals import joblib joblib.dump(clf, 'filename.pkl') ``` But how do I save this overall `pipeline` with the b...
``` from sklearn.externals import joblib joblib.dump(grid.best_estimator_, 'filename.pkl') ``` If you want to dump your object into one file - use: ``` joblib.dump(grid.best_estimator_, 'filename.pkl', compress = 1) ```
Using cosine distance with scikit learn KNeighborsClassifier
34,144,632
2
2015-12-07T22:36:45Z
34,145,444
7
2015-12-07T23:39:54Z
[ "python", "machine-learning", "scikit-learn", "knn" ]
Is it possible to use something like 1 - cosine similarity with scikit learn's KNeighborsClassifier? [This](http://stackoverflow.com/questions/23032628/why-does-scikit-learns-nearest-neighbor-doesnt-seem-to-return-proper-cosine-si) answer says no, but on the [documentation](http://scikit-learn.org/stable/modules/gener...
The cosine similarity is generally defined as xT y / (||x|| \* ||y||), and outputs 1 if they are the same and goes to -1 if they are completely different. This definition is not technically a metric, and so you can't use accelerating structures like ball and kd trees with it. If you force scikit learn to use the brute ...
'is' operator behaves unexpectedly with non-cached integers
34,147,515
28
2015-12-08T03:33:40Z
34,147,516
44
2015-12-08T03:33:40Z
[ "python", "python-3.x", "identity", "python-internals" ]
When playing around with the Python interpreter, I stumbled upon this conflicting case regarding the `is` operator: If the evaluation takes place in the function it returns `True`, if it is done outside it returns `False`. ``` >>> def func(): ... a = 1000 ... b = 1000 ... return a is b ... >>> a = 1000 >>...
## tl;dr: As the [reference manual](https://docs.python.org/3.5/reference/executionmodel.html#structure-of-a-program) states: > A block is a piece of Python program text that is executed as a unit. > The following are blocks: a module, a function body, and a class definition. > **Each command typed interactively is a...
'is' operator behaves unexpectedly with non-cached integers
34,147,515
28
2015-12-08T03:33:40Z
39,325,641
11
2016-09-05T07:24:48Z
[ "python", "python-3.x", "identity", "python-internals" ]
When playing around with the Python interpreter, I stumbled upon this conflicting case regarding the `is` operator: If the evaluation takes place in the function it returns `True`, if it is done outside it returns `False`. ``` >>> def func(): ... a = 1000 ... b = 1000 ... return a is b ... >>> a = 1000 >>...
At the interactive prompt, entry are [compiled in a *single* mode](https://docs.python.org/3/library/functions.html#compile) which processes one complete statement at a time. The compiler itself (in [Python/compile.c](https://hg.python.org/cpython/file/tip/Python/compile.c)) tracks the constants in a dictionary called ...
UnboundLocalError while using += but not append list
34,147,753
3
2015-12-08T03:57:52Z
34,147,963
9
2015-12-08T04:22:14Z
[ "python", "list", "append" ]
I do not quite understand the difference between the following two similar codes: ``` def y(x): temp=[] def z(j): temp.append(j) z(1) return temp ``` calling `y(2)` returns `[1]` ``` def y(x): temp=[] def z(j): temp+=[j] z(1) return temp ``` calling `y(2)` returns `Un...
Answer to the heading, the difference between + and "append" is: ``` [11, 22] + [33, 44,] ``` will give you: ``` [11, 22, 33, 44] ``` and. ``` b = [11, 22, 33] b.append([44, 55, 66]) ``` will give you ``` [11, 22, 33 [44, 55, 66]] ``` **Answer to the error** > This is because when you make an assignment to a v...
Calculate difference each time the sign changes in a list of values
34,153,761
4
2015-12-08T10:42:36Z
34,154,260
8
2015-12-08T11:06:29Z
[ "python", "list", "numpy", "max", "min" ]
Ok let's imagine that I have a list of values like so: ``` list = [-0.23, -0.5, -0.3, -0.8, 0.3, 0.6, 0.8, -0.9, -0.4, 0.1, 0.6] ``` I would like to loop on this list and when the sign changes to get the absolute difference between the maximum (minimum if it's negative) of the first interval and maximum (minimum if i...
This type of grouping operation can be greatly simplified using [`itertools.groupby`](https://docs.python.org/3/library/itertools.html). For example: ``` >>> from itertools import groupby >>> lst = [-0.23, -0.5, -0.3, -0.8, 0.3, 0.6, 0.8, -0.9, -0.4, 0.1, 0.6] # the list >>> minmax = [min(v) if k else max(v) for k,v i...
How to efficiently convert Matlab engine arrays to numpy ndarray?
34,155,829
3
2015-12-08T12:23:41Z
34,155,926
7
2015-12-08T12:27:30Z
[ "python", "matlab", "numpy", "type-conversion", "matlab-engine" ]
I am currently working on a project where I need do some steps of processing with legacy Matlab code (using the Matlab engine) and the rest in Python (numpy). I noticed that converting the results from Matlab's `matlab.mlarray.double` to numpy's `numpy.ndarray` seems horribly slow. Here is some example code for creat...
Moments after posting the question I found the solution. For one-dimensional arrays, access only the `_data` property of the Matlab array. ``` import timeit print 'From list' print timeit.timeit('np.array(x)', setup=setup_range, number=1000) print 'From matlab' print timeit.timeit('np.array(x)', setup=setup_matlab, n...
How to show ampersand (&) symbol in python?
34,157,247
2
2015-12-08T13:33:19Z
34,157,303
11
2015-12-08T13:36:08Z
[ "python", "wxpython" ]
if I do: ``` self.a= wx.Button(self, -1, "Hi&Hello") ``` I get button named: `HiHello` it ignores the `&` symbol. How can I fix it?
`&` is a special marker in GUI labels for buttons and menu items. It defines the standard keyboard shortcut for that element. You can escape it by doubling the character: ``` self.a = wx.Button(self, -1, "Hi&&Hello") ```
Filter a pandas dataframe using values from a dict
34,157,811
2
2015-12-08T13:59:49Z
34,162,576
7
2015-12-08T17:47:40Z
[ "python", "pandas" ]
I need to filter a data frame with a dict, constructed with the key being the column name and the value being the value that I want to filter: ``` filter_v = {'A':1, 'B':0, 'C':'This is right'} # this would be the normal approach df[(df['A'] == 1) & (df['B'] ==0)& (df['C'] == 'This is right')] ``` But I want to do so...
IIUC, you should be able to do something like this: ``` >>> df1.loc[(df1[list(filter_v)] == pd.Series(filter_v)).all(axis=1)] A B C D 3 1 0 right 3 ``` --- This works by making a Series to compare against: ``` >>> pd.Series(filter_v) A 1 B 0 C right dtype: object ``` Selecting the co...
using IFF in python
34,157,836
6
2015-12-08T14:01:07Z
34,157,993
13
2015-12-08T14:08:47Z
[ "python", "python-2.7" ]
Is there any way to write iff statement(i.e if and only if) in python. I want to use it like in ``` for i in range(x) iff x%2==0 and x%i==0: ``` However, there is no `iff` statement in Python. Wikipedia defines the [truth table for iff](https://en.wikipedia.org/wiki/If_and_only_if#Definition) as this: ``` a | ...
If you look at the [truth table for IFF](https://en.wikipedia.org/wiki/If_and_only_if#Definition), you can see that (p iff q) is true when both p and q are true or both are false. That's just the same as checking for equality, so in Python code you'd say: ``` if (x%2==0) == (x%i==0): ```
using IFF in python
34,157,836
6
2015-12-08T14:01:07Z
34,158,002
9
2015-12-08T14:08:57Z
[ "python", "python-2.7" ]
Is there any way to write iff statement(i.e if and only if) in python. I want to use it like in ``` for i in range(x) iff x%2==0 and x%i==0: ``` However, there is no `iff` statement in Python. Wikipedia defines the [truth table for iff](https://en.wikipedia.org/wiki/If_and_only_if#Definition) as this: ``` a | ...
According to [Wikipedia](https://en.wikipedia.org/wiki/If_and_only_if): > Note that it is equivalent to that produced by the XNOR gate, and opposite to that produced by the XOR gate. If that's what you're looking for you simply want this: ``` if not(x%2 == 0 ^ x%i == 0): ```
Variants of string concatenation?
34,158,494
7
2015-12-08T14:31:18Z
34,158,638
12
2015-12-08T14:38:59Z
[ "python", "string", "string-concatenation" ]
Out of the following two variants (with or without plus-sign between) of string literal concatenation: * What's the preferred way? * What's the difference? * When should one or the other be used? * Should non of them ever be used, if so why? * Is `join` preferred? Code: ``` >>> # variant 1. Plus >>> 'A'+'B' 'AB' >>>...
Juxtaposing works only for string literals: ``` >>> 'A' 'B' 'AB' ``` If you work with string objects: ``` >>> a = 'A' >>> b = 'B' ``` you need to use a different method: ``` >>> a b a b ^ SyntaxError: invalid syntax >>> a + b 'AB' ``` The `+` is a bit more obvious than just putting literals next to eac...
How to pass callable in Django 1.9
34,159,071
9
2015-12-08T14:59:23Z
34,159,129
17
2015-12-08T15:02:06Z
[ "python", "django", "django-1.9" ]
Hi i am new in Python and Django and I follow the [django workshop](http://www.django-workshop.de/erste_schritte/views_templates.html) guide. I just installed Python 3.5 and Django 1.9 and get a lot of error messages ... Just now I found a lot of dokumentations but now stuck. I want to add views and and so I added foll...
This is a deprecation warning, which means the code would still run for now. But to address this, just change ``` url(r'^$', 'recipes.views.index'), ``` to this: ``` #First of all explicitly import the view from recipes import views as recipes_views #this is to avoid conflicts with other view imports ``` and in the...
Why do many examples use "fig, ax = plt.subplots()" in Matplotlib/pyplot/python
34,162,443
26
2015-12-08T17:39:39Z
34,162,641
36
2015-12-08T17:51:25Z
[ "python", "matplotlib", "plot", "visualization" ]
I'm learning to use `matplotlib` by studying examples, and a lot of examples seem to include a line like the following before creating a single plot... ``` fig, ax = plt.subplots() ``` Here are some examples... * [Modify tick label text](http://stackoverflow.com/questions/11244514/modify-tick-label-text) * <http://m...
`plt.subplots()` is a function that returns a tuple containing a figure and axes object(s). Thus when using `fig, ax = plt.subplots()` you unpack this tuple into the variables `fig` and `ax`. Having `fig` is useful if you want to change figure-level attributes or save the figure as an image file later (e.g. with `fig.s...
Did something about `namedtuple` change in 3.5.1?
34,166,469
32
2015-12-08T21:35:39Z
34,166,547
8
2015-12-08T21:40:51Z
[ "python", "python-3.5", "namedtuple" ]
On Python 3.5.0: ``` >>> from collections import namedtuple >>> cluster = namedtuple('Cluster', ['a', 'b']) >>> c = cluster(a=4, b=9) >>> c Cluster(a=4, b=9) >>> vars(c) OrderedDict([('a', 4), ('b', 9)]) ``` On Python 3.5.1: ``` >>> from collections import namedtuple >>> cluster = namedtuple('Cluster', ['a', 'b']) >...
From the [docs](https://docs.python.org/3/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields) > Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples. The [docs](https://docs.python.org/3/library/collections.h...
Did something about `namedtuple` change in 3.5.1?
34,166,469
32
2015-12-08T21:35:39Z
34,166,604
25
2015-12-08T21:45:24Z
[ "python", "python-3.5", "namedtuple" ]
On Python 3.5.0: ``` >>> from collections import namedtuple >>> cluster = namedtuple('Cluster', ['a', 'b']) >>> c = cluster(a=4, b=9) >>> c Cluster(a=4, b=9) >>> vars(c) OrderedDict([('a', 4), ('b', 9)]) ``` On Python 3.5.1: ``` >>> from collections import namedtuple >>> cluster = namedtuple('Cluster', ['a', 'b']) >...
Per [Python bug #24931](http://bugs.python.org/issue24931): > [`__dict__`] disappeared because it was fundamentally broken in Python 3, so it had to be removed. Providing `__dict__` broke subclassing and produced odd behaviors. [Revision that made the change](https://hg.python.org/cpython/rev/fa3ac31cfa44) Specifica...
Converting String of a tuple to a Tuple
34,166,703
3
2015-12-08T21:51:28Z
34,166,726
10
2015-12-08T21:52:53Z
[ "python", "arrays", "string", "list", "tuples" ]
If I have a string that looks like a tuple how can I make it into a tuple? ``` s = '(((3,),(4,2),(2,)),((1,),(2,4),(2,)))' ``` and I want to make it into a tuple that contains other tuples. ``` t = tuple((((3,),(4,2),(2,)),((1,),(2,4),(2,)))) ``` Doesn't work because it makes even the `(` as a item in the tuple.
You need to use [`ast.literal_eval`](https://docs.python.org/2/library/ast.html#ast.literal_eval): ``` from ast import literal_eval s = '(((3,),(4,2),(2,)),((1,),(2,4),(2,)))' t = literal_eval(s) print(t) print(type(t)) (((3,), (4, 2), (2,)), ((1,), (2, 4), (2,))) <class 'tuple'> ```
Sort dictionary by multiple values
34,170,515
3
2015-12-09T04:04:12Z
34,170,573
7
2015-12-09T04:11:16Z
[ "python", "sorting", "dictionary" ]
I have the dictionary `{'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7}` I need to sort this dictionary first numerically, then within that, alphabetically. If 2 items have the same number key, they need to be sorted alphabetically. The output of this should be `Bob, Alex, Bill, Charles` I tried using lambda, list c...
Using [`sorted`](https://docs.python.org/3/library/functions.html#sorted) with key function (order by value (`d[k]`) first, then key `k`): ``` >>> d = {'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7} >>> sorted(d, key=lambda k: (d[k], k)) ['Bob', 'Alex', 'Bill', 'Charles'] ```
Normal equation and Numpy 'least-squares', 'solve' methods difference in regression?
34,170,618
13
2015-12-09T04:16:50Z
34,171,374
11
2015-12-09T05:29:21Z
[ "python", "numpy", "machine-learning", "linear-algebra", "linear-regression" ]
I am doing linear regression with multiple variables/features. I try to get thetas (coefficients) by using **normal equation** method (that uses matrix inverse), Numpy least-squares [**numpy.linalg.lstsq**](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html) tool and [**np.linalg.solve**](http:...
### Don't calculate matrix inverse to solve linear systems The professional algorithms don't solve for the matrix inverse. It's slow and introduces unnecessary error. It's not a disaster for small systems, but why do something suboptimal? Basically anytime you see the math written as: ``` x = A^-1 * b ``` you inste...
Tuple unpacking order changes values assigned
34,171,348
43
2015-12-09T05:26:53Z
34,171,485
43
2015-12-09T05:39:37Z
[ "python", "list", "indexing", "tuple-packing" ]
I think the two are identical. ``` nums = [1, 2, 0] nums[nums[0]], nums[0] = nums[0], nums[nums[0]] print nums # [2, 1, 0] nums = [1, 2, 0] nums[0], nums[nums[0]] = nums[nums[0]], nums[0] print nums # [2, 2, 1] ``` But the results are different. Why are the results different? (why is the second o...
## *Prerequisites* - 2 important Points * **Lists are mutable** The main part in lists is that lists are mutable. It means that the values of lists can be changed. This is one of the reason why you are facing the trouble. [Refer the docs for more info](https://docs.python.org/3/tutorial/introduction.html#lists)...
Tuple unpacking order changes values assigned
34,171,348
43
2015-12-09T05:26:53Z
34,171,528
9
2015-12-09T05:43:21Z
[ "python", "list", "indexing", "tuple-packing" ]
I think the two are identical. ``` nums = [1, 2, 0] nums[nums[0]], nums[0] = nums[0], nums[nums[0]] print nums # [2, 1, 0] nums = [1, 2, 0] nums[0], nums[nums[0]] = nums[nums[0]], nums[0] print nums # [2, 2, 1] ``` But the results are different. Why are the results different? (why is the second o...
It's because of that python assignment priority is left to right.So in following code: ``` nums = [1, 2, 0] nums[nums[0]], nums[0] = nums[0], nums[nums[0]] ``` It first assigned the `nums[0]` to `nums[nums[0]]` means `nums[1]==1` and then since lists are mutable objects the nums would be : ``` [1,1,0] ``` and the...
Tuple unpacking order changes values assigned
34,171,348
43
2015-12-09T05:26:53Z
34,171,719
18
2015-12-09T05:58:06Z
[ "python", "list", "indexing", "tuple-packing" ]
I think the two are identical. ``` nums = [1, 2, 0] nums[nums[0]], nums[0] = nums[0], nums[nums[0]] print nums # [2, 1, 0] nums = [1, 2, 0] nums[0], nums[nums[0]] = nums[nums[0]], nums[0] print nums # [2, 2, 1] ``` But the results are different. Why are the results different? (why is the second o...
You can define a class to track the process: ``` class MyList(list): def __getitem__(self, key): print('get ' + str(key)) return super(MyList, self).__getitem__(key) def __setitem__(self, key, value): print('set ' + str(key) + ', ' + str(value)) return super(MyList, self).__seti...
Behaviour of all() in python
34,176,268
6
2015-12-09T10:20:29Z
34,176,372
10
2015-12-09T10:25:01Z
[ "python", "built-in" ]
``` >>all([]) True >>all([[]]) False >>all([[[]]]) True >>all([[[[]]]]) True ``` The documentation of all() reads that it returns True is all the elements are True/For an empty list. Why does all(**[ [ ] ]**) evaluate to False? Because **[ ]** is a member of **[ [ ] ]**, it should evaluate to True as well.
The docstring for `all` is as follows: > `all(iterable) -> bool` > > Return True if bool(x) is True for all values x in the iterable. > If the iterable is empty, return True. This explains the behaviour. `[]` is an empty iterable, so `all` returns True. But `[[]]` is *not* an empty iterable; it is an iterable contain...
How to solve python Celery error when using chain EncodeError(RuntimeError('maximum recursion depth exceeded while getting the str of an object))
34,177,131
6
2015-12-09T11:01:33Z
34,179,519
8
2015-12-09T13:02:56Z
[ "python", "celery" ]
How do you run a chain task in a for loop since the signatures are generated dynamically. The following approach was used because defining the tester task as: ``` @task def tester(items): ch = [] for i in items: ch.append(test.si(i)) return chain(ch)() ``` would raise an error of `EncodeError(Runt...
It seems you met this issue: <https://github.com/celery/celery/issues/1078> Also calling `chain(ch)()` seems to execute it asynchronously. Try to explicitely call `apply()` on it. ``` @app.task def tester(items): ch = [] for i in items: ch.append(test.si(i)) PSIZE = 1000 for cl in range(0, le...
Variable in os.system
34,185,488
2
2015-12-09T17:43:47Z
34,185,515
7
2015-12-09T17:45:39Z
[ "python" ]
I am using `os.system` method in Python to open a file in Linux. But I don't know how to pass the variable (a) inside the os.system command ``` import os a=4 os.system('gedit +a test.txt') ``` How can i pass the variable as an integer inside the command?
``` os.system('gedit +%d test.txt' % (a,)) ``` It is recommended to use [subprocess](https://docs.python.org/3.4/library/subprocess.html?highlight=subprocess) instead of `os.system`: ``` subprocess.call(['gedit', '+%d' % (a,), 'test.txt']) ```
Can you fool isatty AND log stdout and stderr separately?
34,186,035
26
2015-12-09T18:12:45Z
34,189,559
17
2015-12-09T21:43:28Z
[ "python", "linux", "unix", "tty", "pty" ]
## Problem So you want to log the stdout and stderr (separately) of a process or subprocess, without the output being different from what you'd see in the terminal if you weren't logging anything. Seems pretty simple no? Well unfortunately, it appears that it may not be possible to write a general solution for this p...
Like this? ``` % ./challenge.py >stdout 2>stderr % cat stdout This is a real tty :) standard output data % cat stderr standard error data ``` Because I cheated a little bit. ;-) ``` % echo $LD_PRELOAD /home/karol/preload.so ``` Like so... ``` % gcc preload.c -shared -o preload.so -fPIC ``` I feel dirty now, but...
Fast random weighted selection across all rows of a stochastic matrix
34,187,130
6
2015-12-09T19:14:58Z
34,190,035
10
2015-12-09T22:16:07Z
[ "python", "numpy", "matrix", "vectorization", "random-sample" ]
`numpy.random.choice` allows for weighted selection from a vector, i.e. ``` arr = numpy.array([1, 2, 3]) weights = numpy.array([0.2, 0.5, 0.3]) choice = numpy.random.choice(arr, p=weights) ``` selects 1 with probability 0.2, 2 with probability 0.5, and 3 with probability 0.3. What if we wanted to do this quickly in ...
Here's a fully vectorized version that's pretty fast: ``` def vectorized(prob_matrix, items): s = prob_matrix.cumsum(axis=0) r = np.random.rand(prob_matrix.shape[1]) k = (s < r).sum(axis=0) return items[k] ``` *In theory*, `searchsorted` is the right function to use for looking up the random value in ...
Django 1.9: Should I avoid importing models during `django.setup()`?
34,191,392
3
2015-12-10T00:03:13Z
34,191,491
12
2015-12-10T00:12:32Z
[ "python", "django", "django-models", "django-1.9" ]
Porting my app to django 1.9, I got the scary `django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet` Basically my stacktrace is: ``` manage.py execute_from_command_line(sys.argv) django/core/management:352, in execute_from_command_line utility.execute() django/core/management/__init__.py:3...
> Should I import my models in the `__init__.py` of my django apps ? No, you **must** not import any model in the `__init__.py` file of any installed app. This is no longer possible in 1.9. From the [release notes](https://docs.djangoproject.com/en/1.9/releases/1.9/#features-removed-in-1-9): > All models need to be ...
How to loop through a list inside of a loop
34,191,396
3
2015-12-10T00:03:36Z
34,191,474
7
2015-12-10T00:11:21Z
[ "python", "python-3.x" ]
So I have two lists, a **Header list** and a **Client list**: * **Header list** contains headers such as `First Name` or `Phone Number`. * **Client list** contains the details for a particular client such as their first name or phone number. I'm trying to print one piece of each list at a time. For example: ``` Fir...
You can iterate over the header and value at the same time with `zip`: ``` header_list = ['First Name: ', 'Last Name: ', 'Phone: ', 'City: ', 'State: ', 'Zip: '] client_list = ['Joe', 'Somebody', '911'] for head, entry in zip(header_list, client_list): print(head, entry) ``` output: ``` First Name: Joe Last Na...
Best way to flatten a 2D tensor containing a vector in TensorFlow?
34,194,151
8
2015-12-10T05:12:12Z
34,199,902
10
2015-12-10T10:47:47Z
[ "python", "tensorflow" ]
What is the most efficient way to flatten a 2D tensor which is actually a horizontal or vertical vector into a 1D tensor? Is there a difference in terms of performance between: ``` tf.reshape(w, [-1]) ``` and ``` tf.squeeze(w) ``` ?
Both [`tf.reshape(w, [-1])`](https://www.tensorflow.org/versions/master/api_docs/python/array_ops.html#reshape) and [`tf.squeeze(w)`](https://www.tensorflow.org/versions/master/api_docs/python/array_ops.html#squeeze) are "cheap" in that they operate only on the metadata (i.e. the shape) of the given tensor, and don't m...
sorting list of list in python
34,197,047
5
2015-12-10T08:34:19Z
34,197,113
10
2015-12-10T08:38:40Z
[ "python", "string", "python-2.7", "sorting", "python-2.x" ]
I have a list in python like - ``` [['C'], ['B'], ['A'], ['C', 'B'], ['B', 'A'], ['A', 'C']] ``` I want to sort it like follows - ``` [['A'], ['B'], ['C'], ['A', 'B'], ['A', 'C'], ['B', 'C']] ```
First sort the individual items in the lists and then sort the sorted lists based on the length and then the actual elements itself, like this ``` >>> data = [['C'], ['B'], ['A'], ['C', 'B'], ['B', 'A'], ['A', 'C']] >>> sorted((sorted(item) for item in data), key=lambda x: (len(x), x)) [['A'], ['B'], ['C'], ['A', 'B']...
Javascript is giving a different answer to same algorithm in Python
34,197,424
9
2015-12-10T08:55:57Z
34,197,812
13
2015-12-10T09:17:53Z
[ "javascript", "python", "algorithm", "dynamic-programming", "rosalind" ]
I'm working on the Rosalind problem [Mortal Fibonacci Rabbits](http://rosalind.info/problems/fibd/) and the website keeps telling me my answer is wrong when I use my algorithm written JavaScript. When I use the same algorithm in Python I get a different (and correct) answer. The inconsistency only happens when the res...
I think Javascript only has a "Number" datatype, and this actually an IEEE double under the hood. 2,870,048,561,233,730,600 is too large to hold precisely in IEEE double, so it is approximated. (Notice the trailing "00" - 17 decimal places is about right for double.) Python on the other hand has bignum support, and wi...
Javascript is giving a different answer to same algorithm in Python
34,197,424
9
2015-12-10T08:55:57Z
34,198,049
7
2015-12-10T09:27:51Z
[ "javascript", "python", "algorithm", "dynamic-programming", "rosalind" ]
I'm working on the Rosalind problem [Mortal Fibonacci Rabbits](http://rosalind.info/problems/fibd/) and the website keeps telling me my answer is wrong when I use my algorithm written JavaScript. When I use the same algorithm in Python I get a different (and correct) answer. The inconsistency only happens when the res...
Just doing a bit of research, this article seems interesting. [Javascript only supports 53bits integers.](http://www.2ality.com/2012/07/large-integers.html) The result given by Python is indeed out of the maximum safe range for JS. If you try to do ``` parseInt('2870048561233731259') ``` It will indeed return ``` 2...
Cannot import name _uuid_generate_random in heroku django
34,198,538
38
2015-12-10T09:50:31Z
34,199,367
80
2015-12-10T10:25:23Z
[ "python", "django", "heroku", "celery" ]
I am working on a project which scans user gmail inbox and provides a report. I have deployed it in **heroku** with following specs: Language: **Python 2.7** Framework: **Django 1.8** Task scheduler: **Celery** (**Rabbitmq-bigwig** for broker url) Now when heroku execute it the celery is not giving me the output. O...
You are coming across [this issue](https://github.com/celery/kombu/issues/545), which affects Python 2.7.11 (Kombu is required by Celery). The issue is fixed in Kombu 3.0.30.
How to prevent tensorflow from allocating the totality of a GPU memory?
34,199,233
35
2015-12-10T10:19:51Z
34,200,194
43
2015-12-10T11:00:19Z
[ "python", "tensorflow" ]
I work in an environment in which computational resources are shared, i.e., we have a few server machines equipped with a few Nvidia Titan X GPUs each. For small to moderate size models, the 12GB of the Titan X are usually enough for 2-3 people to run training concurrently on the same GPU. If the models are small enou...
You can set the fraction of GPU memory to be allocated when you construct a [`tf.Session`](https://www.tensorflow.org/versions/master/api_docs/python/client.html#Session) by passing a [`tf.GPUOptions`](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/config.proto) as part of the optional `...
How to prevent tensorflow from allocating the totality of a GPU memory?
34,199,233
35
2015-12-10T10:19:51Z
37,454,574
8
2016-05-26T07:43:45Z
[ "python", "tensorflow" ]
I work in an environment in which computational resources are shared, i.e., we have a few server machines equipped with a few Nvidia Titan X GPUs each. For small to moderate size models, the 12GB of the Titan X are usually enough for 2-3 people to run training concurrently on the same GPU. If the models are small enou...
``` config = tf.ConfigProto() config.gpu_options.allow_growth=True sess = tf.Session(config=config) ``` <https://github.com/tensorflow/tensorflow/issues/1578>
Call another function and optionally keep default arguments
34,205,794
12
2015-12-10T15:31:27Z
34,205,906
8
2015-12-10T15:36:42Z
[ "python" ]
I have a function with one optional argument, like this: ``` def funA(x, a, b=1): return a+b*x ``` I want to write a new function that calls `funA` and also has an optional argument, but if no argument is passed, I want to keep the default in `funA`. I was thinking something like this: ``` def funB(x, a, b=None)...
``` def funA(x, a, b=1): return a+b*x def funB(x, a, b=1): return funA(x, a, b) ``` Make the default value of `b=1` in `funB()` and then pass it always to `funA()`
Call another function and optionally keep default arguments
34,205,794
12
2015-12-10T15:31:27Z
34,205,920
16
2015-12-10T15:37:13Z
[ "python" ]
I have a function with one optional argument, like this: ``` def funA(x, a, b=1): return a+b*x ``` I want to write a new function that calls `funA` and also has an optional argument, but if no argument is passed, I want to keep the default in `funA`. I was thinking something like this: ``` def funB(x, a, b=None)...
I would replace `if b` with `if b is not None`, so that if you pass `b=0` (or any other "falsy" value) as argument to `funB` it will be passed to `funA`. Apart from that it seems pretty pythonic to me: clear and explicit. (albeit maybe a bit useless, depending on what you're trying to do!) A little more cryptic way t...
How to assign value to a tensorflow variable?
34,220,532
12
2015-12-11T09:51:46Z
34,220,750
18
2015-12-11T10:01:57Z
[ "python", "variable-assignment", "tensorflow" ]
I am trying to assign a new value to a tensorflow variable in python. ``` import tensorflow as tf import numpy as np x = tf.Variable(0) init = tf.initialize_all_variables() sess = tf.InteractiveSession() sess.run(init) print(x.eval()) x.assign(1) print(x.eval()) ``` But the output I get is ``` 0 0 ``` So the val...
The statement [`x.assign(1)`](https://www.tensorflow.org/versions/master/api_docs/python/state_ops.html#Variable.assign) does not actually assign the value `1` to `x`, but rather creates a [`tf.Operation`](https://www.tensorflow.org/versions/master/api_docs/python/framework.html#Operation) that you have to explicitly *...
Grid search with f1 as scoring function, several pages of error message
34,221,712
2
2015-12-11T10:48:51Z
34,222,309
7
2015-12-11T11:17:47Z
[ "python", "scikit-learn", "grid-search" ]
Want to use Gridsearch to find best parameters and use f1 as the scoring metric. If i remove the scoring function, all works well and i get no errors. Here is my code: ``` from sklearn import grid_search parameters = {'n_neighbors':(1,3,5,10,15),'weights':('uniform','distance'),'algorithm':('ball_tree','kd_tree','b...
Seems that you have label array with values 'no' and 'yes', you should convert them to binary 1-0 numerical representation, because your error states that scoring function cannot understand where 0's and 1's are in your label array. Other possible way to solve it without modifying your label array: ``` from sklearn.m...
Force child class to call parent method when overriding it
34,224,896
6
2015-12-11T13:40:54Z
34,225,828
7
2015-12-11T14:29:06Z
[ "python", "class" ]
I am curious whether there is a way in Python to force (from the Parent class) for a parent method to be called from a child class when it is being overridden. Example: ``` class Parent(object): def __init__(self): self.someValue=1 def start(self): ''' Force method to be called''' se...
# How (not) to do it No, there is no safe way to force users to call super. Let us go over a few options which would reach that or a similar goal and discuss why it’s a bad idea. In the next section, I will also discuss what the sensible (with respect to the Python community) way to deal with the situation is. 1. A...
Find the k smallest values of a numpy array
34,226,400
2
2015-12-11T14:59:17Z
34,226,816
8
2015-12-11T15:20:07Z
[ "python", "numpy" ]
In order to find the index of the smallest value, I can use `argmin`: ``` import numpy as np A = np.array([1, 7, 9, 2, 0.1, 17, 17, 1.5]) print A.argmin() # 4 because A[4] = 0.1 ``` But how can I find the indices of the **k-smallest values**? I'm looking for something like: ``` print A.argmin(numberofvalues=3) ...
Use [`np.argpartition`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html). It does not sort the entire array. It only guarantees that the `kth` element is in sorted position and all smaller elements will be moved before it. Thus the first `k` elements will be the k-smallest elements. ``` imp...
Choosing from different cost function and activation function of a neural network
34,229,140
10
2015-12-11T17:26:10Z
34,248,291
12
2015-12-13T05:28:47Z
[ "python", "machine-learning", "neural-network", "svm", "tensorflow" ]
Recently I started toying with Neural Network. I was trying to implement an `AND`gate with tensorflow. I am having trouble understanding when to use different cost and activation functions. This is a basic neural network. Only no hidden layers. Only an input layer and an output layer. First i tried to implement it in ...
I will answer your questions a little bit out of order, starting with more general answers, and finishing with those specific to your particular experiment. **Activation functions** Different activation functions, in fact, do have different properties. Let's first consider an activation function between two layers of ...
Is it possible to modify an existing TensorFlow computation graph?
34,235,225
6
2015-12-12T01:38:15Z
34,235,413
8
2015-12-12T02:06:24Z
[ "python", "tensorflow" ]
TensorFlow graph is usually built gradually from inputs to outputs, and then executed. Looking at the Python code, the inputs lists of operations are immutable which suggests that the inputs should not be modified. Does that mean that there is no way to update/modify an existing graph?
The TensorFlow [`tf.Graph`](https://www.tensorflow.org/versions/master/api_docs/python/framework.html#Graph) class is an *append-only* data structure, which means that you can add nodes to the graph after executing part of the graph, but you cannot remove or modify existing nodes. Since TensorFlow executes only the nec...
What is the purpose of graph collections in TensorFlow?
34,235,557
5
2015-12-12T02:26:40Z
34,243,895
8
2015-12-12T19:17:47Z
[ "python", "tensorflow" ]
The API discusses [Graph Collections](https://www.tensorflow.org/versions/master/api_docs/python/framework.html#graph-collections) which judging from the [code](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/ops.py#L2071) are a general purpose key/data storage. What is the purpose of t...
Remember that under the hood, Tensorflow is a system for specifying and then executing computational data flow graphs. The graph collections are used as part of keeping track of the constructed graphs and how they must be executed. For example, when you create certain kinds of ops, such as `tf.train.batch_join`, the co...
Difference between np.mean and tf.reduce_mean (numpy | tensorflow)?
34,236,252
13
2015-12-12T00:21:08Z
34,237,210
20
2015-12-12T06:55:01Z
[ "python", "numpy", "machine-learning", "mean", "tensorflow" ]
In the following tutorial: <https://www.tensorflow.org/versions/master/tutorials/mnist/beginners/index.html> There is `accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))` `tf.cast` basically changes the type of tensor the object is...but what is the difference between `tf.reduce_mean` and `np.mean`? Her...
The functionality of `numpy.mean` and `tensorflow.reduce_mean` are the same. They do the same thing. From the documentation, for [numpy](http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html) and [tensorflow](https://www.tensorflow.org/versions/master/api_docs/python/math_ops.html#reduce_mean), you can se...
Cost of using 10**9 over 1000000000?
34,239,159
9
2015-12-12T11:10:56Z
34,239,211
13
2015-12-12T11:18:51Z
[ "python", "performance", "python-2.7", "literals" ]
In Python, are expressions like `10**9` made of literals also literals? What I am asking: **is there a cost to using expressions over less-meaningful but also less-computable literals** in code that is called very often and should be lightweight?
There is no performance cost. Consider this: ``` import dis def foo(): x = 10**9 y = 10**9 def bar(): x = 1000000000 y = 1000000000 dis.dis(foo) dis.dis(bar) ``` yields ``` In [6]: dis.dis(foo) 5 0 LOAD_CONST 3 (1000000000) 3 STORE_FAST 0 (x) ...
difference between tensorflow tf.nn.softmax and tf.nn.softmax_cross_entropy_with_logits
34,240,703
29
2015-12-12T14:03:27Z
34,243,720
64
2015-12-12T19:01:22Z
[ "python", "machine-learning", "tensorflow" ]
I was going through the tensorflow api docs [here](https://www.tensorflow.org/versions/master/api_docs/python/nn.html#softmax). In tensorflow docs they used a keyword called `logits`. What is it? In a lot of methods in the api docs it is written like, `tf.nn.softmax(logits, name=None)` Now what it is written is that ...
Logits simply means that the function operates on the unscaled output of earlier layers and that the relative scale to understand the units is linear. It means, in particular, the sum of the inputs may not equal 1, that the values are *not* probabilities (you might have an input of 5). `tf.nn.softmax` produces just th...
difference between tensorflow tf.nn.softmax and tf.nn.softmax_cross_entropy_with_logits
34,240,703
29
2015-12-12T14:03:27Z
34,272,341
8
2015-12-14T16:47:11Z
[ "python", "machine-learning", "tensorflow" ]
I was going through the tensorflow api docs [here](https://www.tensorflow.org/versions/master/api_docs/python/nn.html#softmax). In tensorflow docs they used a keyword called `logits`. What is it? In a lot of methods in the api docs it is written like, `tf.nn.softmax(logits, name=None)` Now what it is written is that ...
tf.nn.softmax computes the forward propagation through a softmax layer. You use it during evaluation of the model when you compute the probabilities that the model outputs. tf.nn.softmax\_cross\_entropy\_with\_logits computes the cost for a softmax layer. It is only used during training. The logits are the unnormalize...
Remove parentheses around integers in a string
34,245,949
5
2015-12-12T22:53:04Z
34,246,006
7
2015-12-12T22:59:58Z
[ "python", "regex", "string" ]
I want to replace `(number)` with just `number` in an expression like this: ``` 4 + (3) - (7) ``` It should be: ``` 4 + 3 - 7 ``` If the expression is: ``` 2+(2)-(5-2/5) ``` it should be like this: ``` 2+2-(5-2/5) ``` I tried ``` a = a.replace(r'\(\d\+)', '') ``` where `a` is a string, but it did not work. Th...
Python has a powerful module for regular expressions, `re`, featuring a substitution method: ``` >>> import re >>> a = '2+(2)-(5-2/5)' >>> re.sub('\((\d+)\)', r'\1', a) '2+2-(5-2/5)' ```
Python RandomForest - Unknown label Error
34,246,336
7
2015-12-12T23:45:08Z
34,246,469
9
2015-12-13T00:05:09Z
[ "python", "python-3.x", "scikit-learn", "random-forest" ]
I have trouble using RandomForest fit function This is my training set ``` P1 Tp1 IrrPOA Gz Drz2 0 0.0 7.7 0.0 -1.4 -0.3 1 0.0 7.7 0.0 -1.4 -0.3 2 ... ... ... ... ... 3 4...
When you are passing label (y) data to `rf.fit(X,y)`, it expects y to be 1D list. Slicing the Panda frame always result in a 2D list. So, conflict raised in your use-case. You need to convert the 2D list provided by pandas DataFrame to a 1D list as expected by fit function. Try using 1D list first: ``` Y_train = list...
Function with dictionaries as optional arguments - Python
34,251,328
10
2015-12-13T12:59:11Z
34,251,438
13
2015-12-13T13:12:25Z
[ "python", "dictionary", "optional-arguments" ]
I'm trying to create a function that might receive as input many or a few dictionaries. I'm using the following code: ``` def merge_many_dics(dic1,dic2,dic3=True,dic4=True,dic5=True,dic6=True,dic7=True,dic8=True,dic9=True,dic10=True): """ Merging up to 10 dictionaries with same keys and different values :return: a dic...
Using [arbitrary argument list](https://docs.python.org/2/tutorial/controlflow.html#arbitrary-argument-lists), the function can be called with an arbitrary number of arguments: ``` >>> def merge_many_dics(*dicts): ... common_keys = reduce(lambda a, b: a & b, (d.viewkeys() for d in dicts)) ... return {key: tupl...
Does Python's csv.reader(filename) REALLY return a list? Doesn't seem so
34,258,007
4
2015-12-14T00:14:53Z
34,258,024
11
2015-12-14T00:17:06Z
[ "python", "csv" ]
So I am still learning Python and I am on learning about reading files, csv files today. The lesson I just watched tells me that using ``` csv.reader(filename) ``` returns a list. So I wrote the following code: ``` import csv my_file = open(file_name.csv, mode='r') parsed_data = csv.reader(my_file) print(parsed_dat...
What you get is an [*iterable*](https://wiki.python.org/moin/Iterator), i.e. an object which will give you a sequence of other objects (in this case, strings). You can pass it to a `for` loop, or use `list()` to get an actual list: ``` parsed_data = list(csv.reader(my_file)) ``` The reason it is designed this way is ...
Getting good mixing with many input datafiles in tensorflow
34,258,043
3
2015-12-14T00:20:51Z
34,258,214
8
2015-12-14T00:43:47Z
[ "python", "neural-network", "binaryfiles", "tensorflow" ]
I'm working with tensorflow hoping to train a deep CNN to do move prediction for the game Go. The dataset I created consists of 100,000 binary data files, where each datafile corresponds to a recorded game and contains roughly 200 training samples (one for each move in the game). I believe it will be very important to ...
Yes - what you want is to use a combination of two things. First, randomly shuffle the order in which you input your datafiles, by reading from them using a [`tf.train.string_input_producer`](https://www.tensorflow.org/versions/master/api_docs/python/io_ops.html#string_input_producer) with `shuffle=True` that feeds in...
Patch __call__ of a function
34,261,111
17
2015-12-14T06:40:59Z
34,356,508
11
2015-12-18T13:11:34Z
[ "python", "time", "mocking", "python-mock" ]
I need to patch current datetime in tests. I am using this solution: ``` def _utcnow(): return datetime.datetime.utcnow() def utcnow(): """A proxy which can be patched in tests. """ # another level of indirection, because some modules import utcnow return _utcnow() ``` Then in my tests I do some...
**[EDIT]** Maybe the most interesting part of this question is **Why I cannot patch `somefunction.__call__`?** Because the function don't use `__call__`'s code but `__call__` (a method-wrapper object) use function's code. I don't find any well sourced documentation about that, but I can prove it (Python2.7): ``` >>...
Patch __call__ of a function
34,261,111
17
2015-12-14T06:40:59Z
34,443,595
8
2015-12-23T20:56:04Z
[ "python", "time", "mocking", "python-mock" ]
I need to patch current datetime in tests. I am using this solution: ``` def _utcnow(): return datetime.datetime.utcnow() def utcnow(): """A proxy which can be patched in tests. """ # another level of indirection, because some modules import utcnow return _utcnow() ``` Then in my tests I do some...
When you pathch `__call__` of a function, you are setting the `__call__` attribute of that **instance**. Python actually calls the `__call__` method defined on the class. For example: ``` >>> class A(object): ... def __call__(self): ... print 'a' ... >>> a = A() >>> a() a >>> def b(): print 'b' ... >>> b(...
Find "one letter that appears twice" in a string
34,261,346
55
2015-12-14T07:00:09Z
34,261,397
32
2015-12-14T07:03:35Z
[ "python", "regex" ]
I'm trying to catch if one letter that appears twice in a string using RegEx (or maybe there's some better ways?), for example my string is: ``` ugknbfddgicrmopn ``` The output would be: ``` dd ``` However, I've tried something like: ``` re.findall('[a-z]{2}', 'ugknbfddgicrmopn') ``` but in this case, it returns:...
As a Pythonic way You can use `zip` function within a list comprehension: ``` >>> s = 'abbbcppq' >>> >>> [i+j for i,j in zip(s,s[1:]) if i==j] ['bb', 'bb', 'pp'] ``` If you are dealing with large string you can use `iter()` function to convert the string to an iterator and use `itertols.tee()` to create two independe...
Find "one letter that appears twice" in a string
34,261,346
55
2015-12-14T07:00:09Z
34,261,461
9
2015-12-14T07:08:25Z
[ "python", "regex" ]
I'm trying to catch if one letter that appears twice in a string using RegEx (or maybe there's some better ways?), for example my string is: ``` ugknbfddgicrmopn ``` The output would be: ``` dd ``` However, I've tried something like: ``` re.findall('[a-z]{2}', 'ugknbfddgicrmopn') ``` but in this case, it returns:...
Using back reference, it is very easy: ``` import re p = re.compile(ur'([a-z])\1{1,}') re.findall(p, u"ugknbfddgicrmopn") #output: [u'd'] re.findall(p,"abbbcppq") #output: ['b', 'p'] ``` For more details, you can refer to a similar question in perl: [Regular expression to match any character being repeated more than ...
Find "one letter that appears twice" in a string
34,261,346
55
2015-12-14T07:00:09Z
34,261,540
48
2015-12-14T07:13:42Z
[ "python", "regex" ]
I'm trying to catch if one letter that appears twice in a string using RegEx (or maybe there's some better ways?), for example my string is: ``` ugknbfddgicrmopn ``` The output would be: ``` dd ``` However, I've tried something like: ``` re.findall('[a-z]{2}', 'ugknbfddgicrmopn') ``` but in this case, it returns:...
You need use capturing group based regex and define your regex as raw string. ``` >>> re.search(r'([a-z])\1', 'ugknbfddgicrmopn').group() 'dd' >>> [i+i for i in re.findall(r'([a-z])\1', 'abbbbcppq')] ['bb', 'bb', 'pp'] ``` or ``` >>> [i[0] for i in re.findall(r'(([a-z])\2)', 'abbbbcppq')] ['bb', 'bb', 'pp'] ``` Not...
Adding lambda functions with the same operator in python
34,261,390
16
2015-12-14T07:03:17Z
34,261,500
10
2015-12-14T07:11:08Z
[ "python", "numpy", "scipy" ]
I have a rather lengthy equation that I need to integrate over using scipy.integrate.quad and was wondering if there is a way to add lambda functions to each other. What I have in mind is something like this ``` y = lambda u: u**(-2) + 8 x = lambda u: numpy.exp(-u) f = y + x int = scipy.integrate.quad(f, 0, numpy.inf)...
There's no built-in functionality for that, but you can implement it quite easily (with some performance hit, of course): ``` import numpy class Lambda: def __init__(self, func): self._func = func def __add__(self, other): return Lambda( lambda *args, **kwds: self._func(*args, **...
Adding lambda functions with the same operator in python
34,261,390
16
2015-12-14T07:03:17Z
34,261,983
10
2015-12-14T07:47:36Z
[ "python", "numpy", "scipy" ]
I have a rather lengthy equation that I need to integrate over using scipy.integrate.quad and was wondering if there is a way to add lambda functions to each other. What I have in mind is something like this ``` y = lambda u: u**(-2) + 8 x = lambda u: numpy.exp(-u) f = y + x int = scipy.integrate.quad(f, 0, numpy.inf)...
With `sympy` you can do function operation like this: ``` >>> import numpy >>> from sympy.utilities.lambdify import lambdify, implemented_function >>> from sympy.abc import u >>> y = implemented_function('y', lambda u: u**(-2) + 8) >>> x = implemented_function('x', lambda u: numpy.exp(-u)) >>> f = lambdify(u, y(u) + x...
Adding lambda functions with the same operator in python
34,261,390
16
2015-12-14T07:03:17Z
34,263,169
16
2015-12-14T09:12:14Z
[ "python", "numpy", "scipy" ]
I have a rather lengthy equation that I need to integrate over using scipy.integrate.quad and was wondering if there is a way to add lambda functions to each other. What I have in mind is something like this ``` y = lambda u: u**(-2) + 8 x = lambda u: numpy.exp(-u) f = y + x int = scipy.integrate.quad(f, 0, numpy.inf)...
In Python, you'll normally only use a lambda for very short, simple functions that easily fit inside the line that's creating them. (Some languages have other opinions.) As @DSM hinted in their comment, lambdas are essentially a shortcut to creating functions when it's not worth giving them a name. If you're doing mo...
How can auto create uuid column with django
34,264,391
2
2015-12-14T10:13:04Z
34,264,443
7
2015-12-14T10:15:27Z
[ "python", "mysql", "django" ]
I'm using django to create database tables for mysql,and I want it can create a column which type is uuid,I hope it can generate the uuid by itself,that means each time insert a record,I needn't specify a uuid for the model object.How can I make it,thanks!
If you're using Django >= 1.8, you can [use a `UUIDField`](https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.UUIDField): ``` import uuid from django.db import models class MyUUIDModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ``` Passing `d...
XGBoost Categorical Variables: Dummification vs encoding
34,265,102
6
2015-12-14T10:48:22Z
34,346,937
10
2015-12-18T00:55:20Z
[ "python", "categorical-data", "xgboost" ]
When using `XGBoost` we need to convert categorical variables into numeric. Would there be any difference in performance/evaluation metrics between the methods of: 1. dummifying your categorical variables 2. encoding your categorical variables from e.g. (a,b,c) to (1,2,3) ALSO: Would there be any reasons not to go ...
`xgboost` only deals with numeric columns. if you have a feature `[a,b,b,c]` which describes a categorical variable (*i.e. no numeric relationship*) Using [LabelEncoder](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html) you will simply have this: ``` array([0, 1, 1, 2]) ``` `...
Error in function to return 3 largest values from a list of numbers
34,267,961
14
2015-12-14T13:11:43Z
34,268,019
12
2015-12-14T13:15:05Z
[ "python", "numbers", "max" ]
I have this data file and I have to find the 3 largest numbers it contains ``` 24.7 25.7 30.6 47.5 62.9 68.5 73.7 67.9 61.1 48.5 39.6 20.0 16.1 19.1 24.2 45.4 61.3 66.5 72.1 68.4 60.2 50.9 37.4 31.1 10.4 21.6 37.4 44.7 53.2 68.0 73.7 ...
Your data contains `float` numbers not `integer`. You can use `sorted`: ``` >>> data = '''24.7 25.7 30.6 47.5 62.9 68.5 73.7 67.9 61.1 48.5 39.6 20.0 ... 16.1 19.1 24.2 45.4 61.3 66.5 72.1 68.4 60.2 50.9 37.4 31.1 ... 10.4 21.6 37.4 44.7 53...
Error in function to return 3 largest values from a list of numbers
34,267,961
14
2015-12-14T13:11:43Z
34,268,065
7
2015-12-14T13:18:14Z
[ "python", "numbers", "max" ]
I have this data file and I have to find the 3 largest numbers it contains ``` 24.7 25.7 30.6 47.5 62.9 68.5 73.7 67.9 61.1 48.5 39.6 20.0 16.1 19.1 24.2 45.4 61.3 66.5 72.1 68.4 60.2 50.9 37.4 31.1 10.4 21.6 37.4 44.7 53.2 68.0 73.7 ...
Your `return` statement is inside the `for` loop. Once return is reached, the function terminates, so the loop never gets into a second iteration. Move the `return` outside the loop by reducing indentation. ``` for line in file: temps = line.split() for i in temps: if i > largest: ...
Error in function to return 3 largest values from a list of numbers
34,267,961
14
2015-12-14T13:11:43Z
34,268,159
8
2015-12-14T13:22:30Z
[ "python", "numbers", "max" ]
I have this data file and I have to find the 3 largest numbers it contains ``` 24.7 25.7 30.6 47.5 62.9 68.5 73.7 67.9 61.1 48.5 39.6 20.0 16.1 19.1 24.2 45.4 61.3 66.5 72.1 68.4 60.2 50.9 37.4 31.1 10.4 21.6 37.4 44.7 53.2 68.0 73.7 ...
You only get the max elements for the first line because you return at the end of the first iteration. You should de-indent the return statement. Sorting the data and picking the first 3 elements runs in n\*log(n). ``` data = [float(v) for v in line.split() for line in file] sorted(data, reverse=True)[:3] ``` It is ...
Type hints in namedtuple
34,269,772
9
2015-12-14T14:43:24Z
34,269,877
12
2015-12-14T14:47:50Z
[ "python", "python-3.x", "python-3.5", "type-hinting" ]
Consider following piece of code: ``` from collections import namedtuple point = namedtuple("Point", ("x:int", "y:int")) ``` The Code above is just a way to demonstrate as to what I am trying to achieve. I would like to make `namedtuple` with type hints. Do you know any elegant way how to achieve result as intended?
You can use [`typing.NamedTuple`](https://docs.python.org/3/library/typing.html#typing.NamedTuple) From the docs > *Typed version* of `namedtuple`. ``` >>> import typing >>> Point = typing.NamedTuple("Point", [('x', int), ('y', int)]) ``` This is present only in Python 3.5 onwards
django 1.8 does not work on CentOs 6.5 server
34,271,160
3
2015-12-14T15:47:15Z
34,271,260
9
2015-12-14T15:51:55Z
[ "python", "django", "centos6.5" ]
``` Installing collected packages: Django Successfully installed Django-1.8 [root@manage ~]# PYTHON -bash: PYTHON: command not found [root@manage ~]# python Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type "help", "copyright", "credits" or "license" for more inform...
> Django 1.8 requires Python 2.7, 3.2, 3.3, 3.4, or 3.5. <https://docs.djangoproject.com/fr/1.9/releases/1.8/#python-compatibility>
Install python3-venv module on linux mint
34,271,982
11
2015-12-14T16:29:03Z
34,272,200
29
2015-12-14T16:40:22Z
[ "python", "linux", "python-3.x", "mint", "python-venv" ]
I was able to move to Linux mint 17.3 64 bit version from my Linux mint 16. This was long awaited migration. After moving to Linux Mint 17.3, I am not able to the install python3-venv module, which is said to be the replacement for virtualenv in python 3.x. In my linux mint 16 I had access to pyvenv-3.4 tool. I dont k...
Try running this command: ``` sudo apt-get install python3.4-venv ``` Then use this: ``` python3 -m venv test ``` the package name is `python3.4-venv` and not `python3-venv`.
Can I conditionally change which function I'm calling?
34,274,164
3
2015-12-14T18:34:54Z
34,274,216
7
2015-12-14T18:37:47Z
[ "python" ]
Sorry if this has been asked before, but I couldn't find the words to search that would give me the answer I'm looking for. I'm writing a script that contains a helper function, which, in turn, can call one of several functions which all take the same parameters. In this helper function, I end up having strings of thi...
Yes, you can, by using a `dict` mapping names to functions: ``` funcs = dict( func1=func1, func2=func2, func3=func3 ) funcs[funcName](p1, p2, p3) ```
How to print an entire list while not starting by the first item
34,280,147
6
2015-12-15T02:32:29Z
34,280,175
9
2015-12-15T02:35:19Z
[ "python", "list" ]
I'm trying to figure out how to print the following list while not starting by the first item. To be clear: If the list is `[0,1,2,3,4,5,6,7,8]`, I want to print something like `4,5,6,7,8,0,1,2,3` Here's the code: ``` you_can_move_on = False List = [0,1,2,3,4,5,6,7,8] next_player = 3 while not you_can_move_on: ...
I think it should be ``` print(l[3:] + l[:3]) ```
Why is str.translate faster in Python 3.5 compared to Python 3.4?
34,287,893
88
2015-12-15T11:21:05Z
34,287,999
124
2015-12-15T11:26:12Z
[ "python", "string", "python-3.x", "python-internals", "python-3.5" ]
I was trying to remove unwanted characters from a given string using `text.translate()` in Python 3.4. The minimal code is: ``` import sys s = 'abcde12345@#@$#%$' mapper = dict.fromkeys(i for i in range(sys.maxunicode) if chr(i) in '@#$') print(s.translate(mapper)) ``` It works as expected. However the same program...
**TL;DR - [ISSUE 21118](http://bugs.python.org/issue21118)** --- **The long Story** Josh Rosenberg found out that the `str.translate()` function is very slow compared to the `bytes.translate`, he raised an [issue](http://bugs.python.org/issue21118), stating that: > In Python 3, `str.translate()` is usually a perfor...
How to remove punctuation marks from a string in Python 3.x using .translate()?
34,293,875
7
2015-12-15T16:05:03Z
34,294,398
17
2015-12-15T16:27:08Z
[ "python" ]
I want to remove all punctuation marks from a text file using .translate() method. It seems to work well under Python 2.x but under Python 3.4 it doesn't seem to do anything. My code is as follows and the output is the same as input text. ``` import string fhand = open("Hemingway.txt") for fline in fhand: fline =...
You have to create a translation table using `maketrans` that you pass to the `str.translate` method. In Python 3.1 and newer, `maketrans` is now a [static-method on the `str` type](https://docs.python.org/3/library/stdtypes.html#str.maketrans), so you can use it to create a translation of each punctuation you want to...
Strip removing more characters than expected
34,297,084
2
2015-12-15T18:49:01Z
34,297,147
7
2015-12-15T18:52:29Z
[ "python", "string" ]
Can anyone explain what's going on here: ``` s = 'REFPROP-MIX:METHANOL&WATER' s.lstrip('REFPROP-MIX') # this returns ':METHANOL&WATER' as expected s.lstrip('REFPROP-MIX:') # returns 'THANOL&WATER' ``` What happened to that 'ME'? Is a colon a special character for lstrip? This is particularly confusing because thi...
`str.lstrip` removes all the characters in its argument from the string, starting at the left. Since all the characters in the left prefix "REFPROP-MIX:ME" are in the argument "REFPROP-MIX:", all those characters are removed. Likewise: ``` >>> s = 'abcadef' >>> s.lstrip('abc') 'def' >>> s.lstrip('cba') 'def' >>> s.lst...
Python: Find difference between two dictionaries containing lists
34,298,613
10
2015-12-15T20:18:49Z
34,298,690
7
2015-12-15T20:23:31Z
[ "python", "list", "python-2.7", "dictionary" ]
I have two dictionaries that have the following structure: ``` a = {'joe': [24,32,422], 'bob': [1,42,32,24], 'jack':[0,3,222]} b = {'joe': [24], 'bob': [1,42,32]} ``` I would like to retrieve the difference between these two dictionaries which in this case would result as: ``` {'joe': [32,422], 'bob': [24], 'jack':[...
You need to use sets: ``` diff = {} for key in a: diff[key] = list(set(a[key]) - set(b.get(key, []))) print diff ```
Python: Find difference between two dictionaries containing lists
34,298,613
10
2015-12-15T20:18:49Z
34,298,754
11
2015-12-15T20:27:06Z
[ "python", "list", "python-2.7", "dictionary" ]
I have two dictionaries that have the following structure: ``` a = {'joe': [24,32,422], 'bob': [1,42,32,24], 'jack':[0,3,222]} b = {'joe': [24], 'bob': [1,42,32]} ``` I would like to retrieve the difference between these two dictionaries which in this case would result as: ``` {'joe': [32,422], 'bob': [24], 'jack':[...
Assuming that there would be no duplicate entries in any of your lists, you can do what you want with `set`s but not with lists: ``` >>> a = {'joe': [24,32,422], 'bob': [1,42,32,24], 'jack':[0,3,222]} >>> b = {'joe': [24], 'bob': [1,42,32]} >>> {key: list(set(a[key])- set(b.get(key,[]))) for key in a} {'joe': [32, 422...
Django settings Unknown parameters: TEMPLATE_DEBUG
34,298,867
7
2015-12-15T20:32:59Z
34,298,960
14
2015-12-15T20:38:37Z
[ "python", "django", "django-1.9" ]
Hi I'm following the tutorial on the [djangoproject site](https://docs.djangoproject.com/fr/1.9/intro/tutorial03/) and I'm getting an error on my localhost saying: ``` Unknown parameters: TEMPLATE_DEBUG ``` My settings.py looks like this: ``` TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.Dj...
I think you need to do: ``` TEMPLATES = [ { # something else 'OPTIONS': { 'debug': DEBUG, }, }, ] ``` *Django used to accept TEMPLATE\_DEBUG variable but since **Django >= 1.8**, this not allowed any more and is replaced as explained above.* Django [doc](https://docs.djang...