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
Is there a need to close files that have no reference to them?
36,046,167
47
2016-03-16T20:20:26Z
36,063,184
33
2016-03-17T14:16:35Z
[ "python", "python-2.7", "file" ]
As a complete beginner to programming, I am trying to understand the basic concepts of opening and closing files. One exercise I am doing is creating a script that allows me to copy the contents from one file to another. ``` in_file = open(from_file) indata = in_file.read() out_file = open(to_file, 'w') out_file.writ...
You asked about the "basic concepts", so let's take it from the top: When you open a file, your program gains access to **a system resource,** that is, to something outside the program's own memory space. This is basically a bit of magic provided by the operating system (a *system call,* in Unix terminology). Hidden in...
Python: easiest way to flatten a tupple containing another tupple from a function
36,068,444
2
2016-03-17T18:07:06Z
36,068,490
8
2016-03-17T18:09:21Z
[ "python", "tuples", "unpack" ]
My code is like this: ``` def f1(): return 2, 3 def f2(): return 1, f1() ``` I can do: ``` a, (b, c) = f2() ``` I want to do: ``` a, b, c = f2() ``` All the solutions I could find require using a lot of insane parenthesis/brackets, or creating an identity function to use `*` operator. I would like to onl...
Instead of using `1, f2()`, use tuple concatenation: ``` def f2(): return (1,) + f1() ``` As mentioned in a comment, you could also do this: ``` def f2(): x,y = f1() return 1, x, y ``` You could also do this: ``` def f2(): return (lambda *args: args)(1, *f1()) ``` That is a little long, but it has...
How do you load, label, and feed jpeg data into Tensorflow?
36,075,319
4
2016-03-18T02:53:58Z
36,091,574
13
2016-03-18T18:16:18Z
[ "python", "image-processing", "machine-learning", "jpeg", "tensorflow" ]
I have been trying to feed 1750 \* 1750 images into Tensorflow, but I do not know how to label and feed the data after I convert the images into a Tensor using the tf.image.decode\_jpeg() function. Currently, my code is: ``` import tensorflow as tf import numpy as np import imageflow import os, glob sess = tf.Inter...
Depending on what you are trying to do, there are several directions to consider. 1. If you just wish to run inference on an arbitrary JPEG file (i.e. labels are not required), then you can follow the example of classify\_image.py which feeds in a JPEG image into a pre-trained Inception network: [github.com/tensor...
Mysterious exceptions when making many concurrent requests from urllib.request to HTTPServer
36,075,676
18
2016-03-18T03:36:13Z
36,439,055
7
2016-04-05T23:50:45Z
[ "python", "python-3.x", "urllib", "python-multithreading", "httpserver" ]
I am trying to do [this Matasano crypto challenge](http://cryptopals.com/sets/4/challenges/31/) that involves doing a timing attack against a server with an artificially slowed-down string comparison function. It says to use "the web framework of your choosing", but I didn't feel like installing a web framework, so I d...
You're using the default `listen()` backlog value, which is probably the cause of a lot of those errors. This is not the number of simultaneous clients with connection already established, but the number of clients waiting on the listen queue before the connection is established. Change your server class to: ``` class...
Test if function or method is normal or asynchronous
36,076,619
5
2016-03-18T05:13:05Z
36,076,663
7
2016-03-18T05:17:40Z
[ "python", "python-3.x", "asynchronous", "python-3.5", "coroutine" ]
How can I find out if a function or method is a normal function or an async function? I would like my code to automatically support normal or async callbacks and need a way to test what type of function is passed. ``` async def exampleAsyncCb(): pass def exampleNomralCb(): pass def isAsync(someFunc): #do...
Use the [inspect](https://docs.python.org/3/library/inspect.html) module of Python. `inspect.iscoroutinefunction(object)` > Return true if the object is a coroutine function (a function defined with an async def syntax). This function is available since Python 3.5. The module is available for Python 2 with lesser fu...
How do I raise a FileNotFoundError properly?
36,077,266
5
2016-03-18T06:06:00Z
36,077,407
11
2016-03-18T06:15:35Z
[ "python", "python-3.x", "file-not-found" ]
I use a third-party library that's fine but does not handle inexistant files the way I would like. When giving it a non-existant file, instead of raising the good old ``` FileNotFoundError: [Errno 2] No such file or directory: 'nothing.txt' ``` it raises some obscure message: ``` OSError: Syntax error in file None (...
Pass in arguments: ``` import errno import os raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), filename) ``` `FileNotFoundError` is a subclass of [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError), which takes several arguments. The first is an error code from the [`errno` mo...
Why did Django 1.9 replace tuples () with lists [] in settings and URLs?
36,081,149
31
2016-03-18T09:51:06Z
36,081,236
51
2016-03-18T09:54:50Z
[ "python", "django", "python-2.7", "django-settings", "django-1.9" ]
**I am bit curious to know why Django 1.9 replaced tuples () with lists [] in settings, URLs and other configuration files** I just upgraded to Django 1.9 and noticed these changes. What is the logic behind them? ``` INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.content...
It is explained in issue [#8846](https://code.djangoproject.com/ticket/8846) (emphasis mine): > In the documentation for ​Creating your own settings there's a > recommendation which reads "For settings that are sequences, use > tuples instead of lists. This is purely for performance." > > This is bunk. Profiling sho...
Why did Django 1.9 replace tuples () with lists [] in settings and URLs?
36,081,149
31
2016-03-18T09:51:06Z
36,085,296
9
2016-03-18T13:11:23Z
[ "python", "django", "python-2.7", "django-settings", "django-1.9" ]
**I am bit curious to know why Django 1.9 replaced tuples () with lists [] in settings, URLs and other configuration files** I just upgraded to Django 1.9 and noticed these changes. What is the logic behind them? ``` INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.content...
In [the release notes of 1.9](https://docs.djangoproject.com/en/1.9/releases/1.9/#default-settings-that-were-tuples-are-now-lists), there is: > **Default settings that were tuples are now lists** > > The default settings in **django.conf.global\_settings** were a combination of lists and tuples. All settings that were...
Counterintuitive behaviour of int() in python
36,085,185
81
2016-03-18T13:05:59Z
36,085,574
75
2016-03-18T13:24:30Z
[ "python" ]
It's clearly stated in the [docs](https://docs.python.org/3.5/library/functions.html#int) that int(number) is a flooring type conversion: ``` int(1.23) 1 ``` and int(string) returns an int if and only if the string is an integer literal. ``` int('1.23') ValueError int('1') 1 ``` Is there any special reason for tha...
This is almost certainly a case of applying three of the principles from the [Zen of Python](https://www.python.org/dev/peps/pep-0020/): > Explicit is better implicit. > > [...] practicality beats purity > > Errors should never pass silently Some percentage of the time, someone doing `int('1.23')` is calling the wron...
Counterintuitive behaviour of int() in python
36,085,185
81
2016-03-18T13:05:59Z
36,085,637
122
2016-03-18T13:26:51Z
[ "python" ]
It's clearly stated in the [docs](https://docs.python.org/3.5/library/functions.html#int) that int(number) is a flooring type conversion: ``` int(1.23) 1 ``` and int(string) returns an int if and only if the string is an integer literal. ``` int('1.23') ValueError int('1') 1 ``` Is there any special reason for tha...
There is no *special* reason. Python is simply applying its general principle of not performing implicit conversions, which are well-known causes of problems, particularly for newcomers, in languages such as Perl and Javascript. `int(some_string)` is an explicit request to convert a string to integer format; the rules...
Counterintuitive behaviour of int() in python
36,085,185
81
2016-03-18T13:05:59Z
36,090,233
11
2016-03-18T17:03:18Z
[ "python" ]
It's clearly stated in the [docs](https://docs.python.org/3.5/library/functions.html#int) that int(number) is a flooring type conversion: ``` int(1.23) 1 ``` and int(string) returns an int if and only if the string is an integer literal. ``` int('1.23') ValueError int('1') 1 ``` Is there any special reason for tha...
In simple words - they're not the same function. int( decimal ) and int( string ) are 2 different functions with the *same name* that return an integer. One is a string-integer-conversion, one is performing floor on a decimal, and they're both called 'int' because it's short and makes sense for each, but there's no im...
Counterintuitive behaviour of int() in python
36,085,185
81
2016-03-18T13:05:59Z
36,098,510
16
2016-03-19T06:09:21Z
[ "python" ]
It's clearly stated in the [docs](https://docs.python.org/3.5/library/functions.html#int) that int(number) is a flooring type conversion: ``` int(1.23) 1 ``` and int(string) returns an int if and only if the string is an integer literal. ``` int('1.23') ValueError int('1') 1 ``` Is there any special reason for tha...
Sometimes a thought experiment can be useful. * Behavior A: `int('1.23')` fails with an error. This is the existing behavior. * Behavior B: `int('1.23')` produces `1` without error. This is what you're proposing. With behavior A, it's straightforward and trivial to get the effect of behavior B: use `int(float('1.23')...
Static behavior of iterators in Python
36,085,354
4
2016-03-18T13:13:12Z
36,085,414
7
2016-03-18T13:16:15Z
[ "python", "python-3.x", "iterator" ]
I am reading [Learning Python by M.Lutz](http://rads.stackoverflow.com/amzn/click/1449355730) and found bizarre block of code: ``` >>> M = map(abs, (-1, 0, 1)) >>> I1 = iter(M); I2 = iter(M) >>> print(next(I1), next(I1), next(I1)) 1 0 1 >>> next(I2) Traceback (most recent call last): File "<stdin>", line 1, in <modu...
This has nothing to do with "static" objects, which don't exist in Python. `iter(M)` does not create a copy of M. Both I1 and I2 are iterators wrapping the same object; in fact, since `M` is already an iterator, calling `iter` on it just returns the underlying object: ``` >>> iter(M) <map object at 0x1012272b0> >>> M...
pandas: how to find the most frequent value of each row?
36,091,902
2
2016-03-18T18:35:40Z
36,092,067
7
2016-03-18T18:43:08Z
[ "python", "pandas", "dataframe" ]
how to find the most frequent value of each row of a dataframe? For example: ``` In [14]: df Out[14]: a b c 0 2 3 3 1 1 1 2 2 7 7 8 ``` return: [3,1,7]
try [.mode()](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mode.html) method: ``` In [88]: df Out[88]: a b c 0 2 3 3 1 1 1 2 2 7 7 8 In [89]: df.mode(axis=1) Out[89]: 0 0 3 1 1 2 7 ```
why is 1e400 not an int?
36,092,203
5
2016-03-18T18:50:12Z
36,092,258
8
2016-03-18T18:53:02Z
[ "python", "floating-point", "int", "scientific-notation" ]
Why is a number in Scientific notation always read as a `float`, and how can i convert a string like '1e400' to an `int` (which is too large for a `float`) ? ``` >>>int('1e400') ValueError: invalid literal for int() with base 10: '1e400' >>>int(float('1e400')) OverflowError: cannot convert float infinity to integer `...
Perhaps you could use `Decimal` as an intermediary type before converting to int. ``` >>> import decimal >>> decimal.Decimal("1e400") Decimal('1E+400') >>> int(decimal.Decimal("1e400")) 10000000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000...
How can I use a 'for' loop for just one variable in a function which depends on two variables?
36,096,915
5
2016-03-19T01:47:07Z
36,097,023
38
2016-03-19T02:04:15Z
[ "python", "for-loop" ]
I just want to use the `for` loop for the `t` variable in my function: ``` l = [] def func(s): for i in range(1, 100): t = i p = t * 2 + s * 2 return p l.append(func(10)) print l ``` I want the value of t to go from 1 to 99 and and print a list of all the value, but I always end up getti...
I assume you have [NumPy](http://en.wikipedia.org/wiki/NumPy) installed (at least your original question suggested it), so I'll present a way how you can get your result using `numpy-arrays` in a very efficient manner (without any list-comprehensions and explicit iterations): ``` > import numpy as np > s = 10 > l = np...
How to call a function with a dictionary that contains more items than the function has parameters?
36,102,075
27
2016-03-19T13:03:24Z
36,102,152
11
2016-03-19T13:11:05Z
[ "python", "dictionary", "named-parameters", "kwargs" ]
I am looking for the best way to combine a function with a dictionary *that contains more items than the function's inputs* basic \*\*kwarg unpacking fails in this case: ``` def foo(a,b): return a + b d = {'a':1, 'b':2, 'c':3} foo(**d) --> TypeError: foo() got an unexpected keyword argument 'c' ``` A...
Your problem lies with the way you defined your function, it should be defined like this - ``` def foo(**kwargs): ``` And then inside the function you can iterate over the number of arguments sent to the function like so - ``` if kwargs is not None: for key, value in kwargs.iteritems(): do so...
How to call a function with a dictionary that contains more items than the function has parameters?
36,102,075
27
2016-03-19T13:03:24Z
36,102,245
8
2016-03-19T13:19:39Z
[ "python", "dictionary", "named-parameters", "kwargs" ]
I am looking for the best way to combine a function with a dictionary *that contains more items than the function's inputs* basic \*\*kwarg unpacking fails in this case: ``` def foo(a,b): return a + b d = {'a':1, 'b':2, 'c':3} foo(**d) --> TypeError: foo() got an unexpected keyword argument 'c' ``` A...
You can also use a [decorator function](https://www.python.org/dev/peps/pep-0318/) to filter out those *keyword arguments* that are not allowed in you function. Of you use the [`signature`](https://docs.python.org/3/library/inspect.html#inspect.signature) function new in 3.3 to return your function [`Signature`](https:...
How to call a function with a dictionary that contains more items than the function has parameters?
36,102,075
27
2016-03-19T13:03:24Z
36,102,254
23
2016-03-19T13:20:22Z
[ "python", "dictionary", "named-parameters", "kwargs" ]
I am looking for the best way to combine a function with a dictionary *that contains more items than the function's inputs* basic \*\*kwarg unpacking fails in this case: ``` def foo(a,b): return a + b d = {'a':1, 'b':2, 'c':3} foo(**d) --> TypeError: foo() got an unexpected keyword argument 'c' ``` A...
How about *making a [decorator](http://thecodeship.com/patterns/guide-to-python-function-decorators/)* that would *filter allowed keyword arguments only*: ``` import inspect def get_input_names(function): '''get arguments names from function''' return inspect.getargspec(function)[0] def filter_dict(dict_,k...
How to call a function with a dictionary that contains more items than the function has parameters?
36,102,075
27
2016-03-19T13:03:24Z
36,105,034
14
2016-03-19T17:45:43Z
[ "python", "dictionary", "named-parameters", "kwargs" ]
I am looking for the best way to combine a function with a dictionary *that contains more items than the function's inputs* basic \*\*kwarg unpacking fails in this case: ``` def foo(a,b): return a + b d = {'a':1, 'b':2, 'c':3} foo(**d) --> TypeError: foo() got an unexpected keyword argument 'c' ``` A...
All of these answers are wrong. It is not possible to do what you are asking, because the function might be declared like this: ``` def foo(**kwargs): a = kwargs.pop('a') b = kwargs.pop('b') if kwargs: raise TypeError('Unexpected arguments: %r' % kwargs) ``` Now, why on earth would anyone write t...
Python Pandas Dataframe: Normalize data between 0.01 and 0.99?
36,102,348
2
2016-03-19T13:28:39Z
36,102,391
9
2016-03-19T13:32:08Z
[ "python", "pandas", "dataframe", "normalization" ]
I am trying to bound every value in a dataframe between 0.01 and 0.99 I have successfully normalised the data between 0 and 1 using: `.apply(lambda x: (x - x.min()) / (x.max() - x.min()))` as follows: ``` df = pd.DataFrame({'one' : ['AAL', 'AAL', 'AAPL', 'AAPL'], 'two' : [1, 1, 5, 5], 'three' : [4,4,2,2]}) df[['two'...
There's an app, err [clip method](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.clip.html), for that: ``` import pandas as pd df = pd.DataFrame({'one' : ['AAL', 'AAL', 'AAPL', 'AAPL'], 'two' : [1, 1, 5, 5], 'three' : [4,4,2,2]}) df = df[['two', 'three']].apply(lambda x: (x - x.min()) / (x....
Are simple hardcoded arithmetics cached/compiled away?
36,105,978
4
2016-03-19T19:11:46Z
36,106,000
7
2016-03-19T19:13:24Z
[ "python", "python-internals" ]
I would like to know if python caches / compiles away in its .pyc files simple arithmetics like `5*5+5`. Sometimes I like to write `if seconds > 24*60*60` for a day for example. I know that the effect on performance is unnoticeable but I'm curious nevertheless.
Yes, CPython (the default implementation of Python) uses a [peephole optimiser](https://en.wikipedia.org/wiki/Peephole_optimization) to collapse such expressions into one number; this is called [*constant folding*](https://en.wikipedia.org/wiki/Constant_folding). You can check for this using the [`dis` disassembler](h...
How can I limit iterations of a loop in Python?
36,106,712
4
2016-03-19T20:22:48Z
36,106,713
8
2016-03-19T20:22:48Z
[ "python", "enumerate" ]
Say I have a list of items, and I want to iterate over the first few of it: ``` items = list(range(10)) # I mean this to represent any kind of iterable. limit = 5 ``` ## Naive implementation The Python naïf coming from other languages would probably write this perfectly serviceable and performant (if unidiomatic) c...
> # How can I limit iterations of a loop in Python? > > ``` > for index, item in enumerate(items): > print(item) > if index == limit: > break > ``` > > Is there a shorter, idiomatic way to write the above? How? ## Including the index `zip` stops on the shortest iterable of its arguments. (In contrast ...
Why is a double semicolon a SyntaxError in Python?
36,111,915
64
2016-03-20T09:07:56Z
36,111,947
101
2016-03-20T09:12:36Z
[ "python", "syntax-error", "language-lawyer" ]
I know that semicolons are unnecessary in Python, but they can be used to cram multiple statements onto a single line, e.g. ``` >>> x = 42; y = 54 ``` I always thought that a semicolon was equivalent to a line break. So I was a bit surprised to learn (h/t [Ned Batchelder on Twitter](https://twitter.com/nedbat/status/...
From the Python grammar, we can see that `;` is not defined as `\n`. The parser expects another statement after a `;`, except if there's a newline after it: ``` Semicolon w/ statement Maybe a semicolon Newline \/ \/ \/ \/ simple_stmt: ...
Why is a double semicolon a SyntaxError in Python?
36,111,915
64
2016-03-20T09:07:56Z
36,111,954
23
2016-03-20T09:12:52Z
[ "python", "syntax-error", "language-lawyer" ]
I know that semicolons are unnecessary in Python, but they can be used to cram multiple statements onto a single line, e.g. ``` >>> x = 42; y = 54 ``` I always thought that a semicolon was equivalent to a line break. So I was a bit surprised to learn (h/t [Ned Batchelder on Twitter](https://twitter.com/nedbat/status/...
An empty statement still needs `pass`, even if you have a semicolon. ``` >>> x = 42;pass; >>> x 42 ```
Make IPython Import What I Mean
36,112,275
4
2016-03-20T09:50:26Z
36,116,171
10
2016-03-20T16:12:51Z
[ "python", "ipython", "ipython-magic" ]
I want to modify how IPython handles import errors by default. When I prototype something in the IPython shell, I usually forget to first import `os`, `re` or whatever I need. The first few statements often follow this pattern: ``` In [1]: os.path.exists("~/myfile.txt") ------------------------------------------------...
**NOTE:** This is now being maintained [on Github](https://github.com/OrangeFlash81/ipython-auto-import/tree/master). Download the latest version of the script from there! I developed a script that binds to IPython's exception handling through `set_custom_exc`. If there's a `NameError`, it uses a regex to find what mo...
How to loop over a tedious if statement
36,116,988
2
2016-03-20T17:25:03Z
36,117,020
10
2016-03-20T17:28:13Z
[ "python", "music", "translate" ]
I'm currently trying to make a program that takes sheet music for violin and translates the given notes into a position on a string, but my problem is that when I ask if a key is sharp or flat, and how many sharps or flats are in that key signature I find that I'm making a bunch of tedious if/then statements such as: ...
You could use a dictionary: ``` transpositions = { (sharp, 2): {'LE': 'D4', 'SC': 'A4'}, (sharp, 3): {'LE': 'D5', 'SC': 'G2'}, # etc. } note.update(transpositions.get((keysig, signum), {})) ``` This uses a tuple of `(keysig, signum)` as the key, mapping to specific note transpositions. If no such signatu...
Pythonic way to avoid "if x: return x" statements
36,117,583
201
2016-03-20T18:11:44Z
36,117,603
254
2016-03-20T18:13:00Z
[ "python" ]
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. ``` def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x ...
You could use a loop: ``` conditions = (check_size, check_color, check_tone, check_flavor) for condition in conditions: result = condition() if result: return result ``` This has the added advantage that you can now make the number of conditions variable. You could use [`map()`](https://docs.python.o...
Pythonic way to avoid "if x: return x" statements
36,117,583
201
2016-03-20T18:11:44Z
36,117,720
368
2016-03-20T18:22:56Z
[ "python" ]
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. ``` def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x ...
Alternatively to Martijn's fine answer, you could chain `or`. This will return the first truthy value, or `None` if there's no truthy value: ``` def check_all_conditions(): return check_size() or check_color() or check_tone() or check_flavor() or None ``` Demo: ``` >>> x = [] or 0 or {} or -1 or None >>> x -1 >>...
Pythonic way to avoid "if x: return x" statements
36,117,583
201
2016-03-20T18:11:44Z
36,121,285
17
2016-03-21T00:14:15Z
[ "python" ]
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. ``` def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x ...
If you want the same code structure, you could use ternary statements! ``` def check_all_conditions(): x = check_size() x = x if x else check_color() x = x if x else check_tone() x = x if x else check_flavor() return x if x else None ``` I think this looks nice and clear if you look at it. Demo:...
Pythonic way to avoid "if x: return x" statements
36,117,583
201
2016-03-20T18:11:44Z
36,126,903
38
2016-03-21T09:14:00Z
[ "python" ]
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. ``` def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x ...
This is a variant of Martijns first example. It also uses the "collection of callables"-style in order to allow short-circuiting. Instead of a loop you can use the builtin `any`. ``` conditions = (check_size, check_color, check_tone, check_flavor) return any(condition() for condition in conditions) ``` Note that `an...
Pythonic way to avoid "if x: return x" statements
36,117,583
201
2016-03-20T18:11:44Z
36,129,322
78
2016-03-21T11:03:04Z
[ "python" ]
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. ``` def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x ...
**Don't change it** There are other ways of doing this as the various other answers show. None are as clear as your original code.
Pythonic way to avoid "if x: return x" statements
36,117,583
201
2016-03-20T18:11:44Z
36,140,014
67
2016-03-21T19:35:05Z
[ "python" ]
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. ``` def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x ...
According to [Curly's law](http://blog.codinghorror.com/curlys-law-do-one-thing/), you can make this code more readable by splitting two concerns: * What things do I check? * Has one thing returned true? into two functions: ``` def all_conditions(): yield check_size() yield check_color() yield check_tone...
Pythonic way to avoid "if x: return x" statements
36,117,583
201
2016-03-20T18:11:44Z
36,141,317
21
2016-03-21T20:49:46Z
[ "python" ]
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. ``` def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x ...
I'm quite surprised nobody mentioned the built-in [`any`](https://docs.python.org/2/library/functions.html#any) which is made for this purpose: ``` def check_all_conditions(): return any([ check_size(), check_color(), check_tone(), check_flavor() ]) ``` Note that although this ...
Pythonic way to avoid "if x: return x" statements
36,117,583
201
2016-03-20T18:11:44Z
36,142,616
23
2016-03-21T22:12:00Z
[ "python" ]
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. ``` def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x ...
Have you considered just writing `if x: return x` all on one line? ``` def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x x = check_tone() if x: return x x = check_flavor() if x: return x return None ``` This isn't any less *repetitive*...
Pythonic way to avoid "if x: return x" statements
36,117,583
201
2016-03-20T18:11:44Z
36,161,683
64
2016-03-22T17:48:31Z
[ "python" ]
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. ``` def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x ...
In effectively the same answer as timgeb, but you could use parenthesis for nicer formatting: ``` def check_all_the_things(): return ( one() or two() or five() or three() or None ) ```
Error: 'conda' can only be installed into the root environment
36,117,904
5
2016-03-20T18:40:29Z
36,298,307
20
2016-03-30T01:58:59Z
[ "python", "package", "install", "seaborn", "conda" ]
I am getting the following error when I try to install the python package seaborn: ``` conda install --name dato-env seaborn Error: 'conda' can only be installed into the root environment ``` This, of course, is puzzling because I am not trying to install conda. I am trying to install seaborn. This is my setup. I ha...
If you clone root you get conda-build and conda-env in your new environment but afaik they shouldn't be there and are not required outside root provided root remains on your path. So if you remove them from your non-root env first your command should work. For example, I had the same error when trying to update anacond...
why are empty numpy arrays not printed
36,133,069
6
2016-03-21T14:00:56Z
36,133,235
8
2016-03-21T14:08:03Z
[ "python", "arrays", "numpy" ]
If I initialise a python list ``` x = [[],[],[]] print(x) ``` then it returns ``` [[], [], []] ``` but if I do the same with a numpy array ``` x = np.array([np.array([]),np.array([]),np.array([])]) print(x) ``` then it only returns ``` [] ``` How can I make it return a nested empty list as it does for a normal ...
It actually *does* return a nested empty list. For example, try ``` x = np.array([np.array([]),np.array([]),np.array([])]) >>> array([], shape=(3, 0), dtype=float64) ``` or ``` >>> print x.shape (3, 0) ``` Don't let the output of `print x` fool you. These types of outputs merely reflect the (aesthetic) choices of t...
Search list of string elements that match another list of string elements
36,134,536
9
2016-03-21T15:00:56Z
36,134,592
8
2016-03-21T15:03:31Z
[ "python" ]
I have a list with strings called `names`, I need to search each element in the `names` list with each element from the `pattern` list. Found several guides that can loop through for a individual string but not for a list of strings ``` a = [x for x in names if 'st' in x] ``` Thank you in advance! ``` names = ['chri...
Use the [any()](https://docs.python.org/3/library/functions.html#any) function with a [generator expression](https://docs.python.org/3/reference/expressions.html#grammar-token-generator_expression): ``` a = [x for x in names if any(pat in x for pat in pattern)] ``` `any()` is a short-circuiting function, so the first...
Defining SQLAlchemy enum column with Python enum raises "ValueError: not a valid enum"
36,136,112
6
2016-03-21T16:08:05Z
36,136,344
8
2016-03-21T16:18:10Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy" ]
I am trying to follow [this example](http://docs.sqlalchemy.org/en/latest/core/type_basics.html) to have an enum column in a table that uses Python's `Enum` type. I define the enum then pass it to the column as shown in the example, but I get `ValueError: <enum 'FruitType'> is not a valid Enum`. How do I correctly defi...
The column type should be [`sqlalchemy.types.Enum`](http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.Enum). You're using the Python `Enum` type again, which is valid for the value but not the column type. ``` class MyTable(db.Model): id = db.Column(db.Integer, primary_key = True) fru...
Python the same char not equals
36,137,602
12
2016-03-21T17:15:26Z
36,137,846
9
2016-03-21T17:28:14Z
[ "python", "python-2.7", "python-3.x" ]
I have a text in my database. I send some text from xhr to my view. Function find does not find some unicode chars. I want find selected text using just: ``` text.find(selection) ``` but sometimes variable 'selection' has char like that: ``` ę # in xhr unichr(281) ``` in variable 'text' there is a char: ``` ę #...
Here [`unicodedata.normalize`](https://docs.python.org/3/library/unicodedata.html#unicodedata.normalize) might help you. Basically if you normalize the data coming from the db, and normalize your selection to the same form, you should have a better result when using `str.find`, `str.__contains__` (i.e. `in`), `str.ind...
How to find a value closest to another value X in a large sorted array efficiently
36,143,149
3
2016-03-21T22:54:36Z
36,143,259
9
2016-03-21T23:02:56Z
[ "python", "search" ]
For a sorted list, how can I find the smallest number which close to the a given number? For example, ``` mysortedList = [37, 72, 235, 645, 715, 767, 847, 905, 908, 960] ``` How can I find the largest element which is less or equal to 700 **quickly**? (If I have 10 million elements, then it will be slow to search li...
You can use the [`bisect`](https://docs.python.org/2/library/bisect.html) module: ``` import bisect data = [37, 72, 235, 645, 715, 767, 847, 905, 908, 960] location = bisect.bisect_left(data, 700) result = data[location - 1] ``` This is a module in the standard library which will use [binary search](https://en.wik...
Difference between "raise" and "raise e"?
36,153,805
14
2016-03-22T11:57:45Z
36,153,948
11
2016-03-22T12:04:35Z
[ "python", "exception" ]
In python, is there a difference between `raise` and `raise e` in an except block? `dis` is showing me different results, but I don't know what it means. What's the end behavior of both? ``` import dis def a(): try: raise Exception() except Exception as e: raise def b(): try: ra...
There is no difference in this case. `raise` without arguments [will always raise the last exception thrown](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement) (which is also accessible with `sys.exc_info()`). The reason the bytecode is different is because Python is a dynamic language and the ...
Efficient way of Creating dummy variables in python
36,157,329
4
2016-03-22T14:36:20Z
36,157,546
7
2016-03-22T14:45:09Z
[ "python" ]
I want to create a vector of dummy variables(can take only O or 1). I am doing the following: ``` data = ['one','two','three','four','six'] variables = ['two','five','ten'] ``` I got the following two ways: ``` dummy=[] for variable in variables: if variable in data: dummy.append(1) else: dum...
If you convert `data` to a `set` the lookup will be quicker. You can also convert the boolean to an integer to get `1` or `0` for `True` or `False`. ``` >>> int(True) 1 ``` You can call `__contains__` on the set of data for each variable so save creating the set each time through the loop. You can map all these tog...
n**n**n heuristics in Python
36,159,204
5
2016-03-22T15:54:53Z
36,159,331
13
2016-03-22T16:00:06Z
[ "python", "algorithm" ]
I just play around with `Python` and found just interesting thing: my computer (i5, 3 GHz) just hang out after several hours of attempting to compute `10 ** 10 ** 10`. I know Math isn't a purpose Python was created for, but I wonder isn't there a way to help `Python` to compute it. What I have so far is my observation...
`10 ** 10 ** 10` is a **very very large number**. Python is trying to allocate enough memory to represent that number. 10.000.000.000 (10 billion) digits takes a lot more memory than your computer can provide in one go, so your computer is now swapping out memory to disk to make space, which is why things are now so ve...
How to use inverse of a GenericRelation
36,163,430
12
2016-03-22T19:27:28Z
39,945,828
7
2016-10-09T16:25:25Z
[ "python", "sql", "django", "generic-foreign-key", "django-generic-relations" ]
I must be really misunderstanding something with the [`GenericRelation` field](https://docs.djangoproject.com/en/1.7/ref/contrib/contenttypes/#reverse-generic-relations) from Django's content types framework. To create a minimal self contained example, I will use the polls example app from the tutorial. Add a generic ...
**TL;DR** This was a bug in Django 1.7 that was fixed in Django 1.8. * Fix commit: [1c5cbf5e5d5b350f4df4aca6431d46c767d3785a](https://github.com/django/django/commit/1c5cbf5e5d5b350f4df4aca6431d46c767d3785a) * Fix PR: [GenericRelation filtering targets related model's pk](https://github.com/django/django/pull/3743) * ...
Python subprocess .check_call vs .check_output
36,169,571
3
2016-03-23T03:56:41Z
36,214,461
10
2016-03-25T05:20:10Z
[ "python", "bash", "ssh", "subprocess" ]
My python script (python 3.4.3) calls a bash script via subprocess: ``` import subprocess as sp res = sp.check_output("bashscript", shell=True) ``` The **bashscript** contains the following line: ``` ssh -MNf somehost ``` which opens a shared master connection to some remote host to allow some subsequent operations...
`check_call()` returns as soon as `/bin/sh` process exits without waiting for descendant processes. `check_output()` waits until all output is read. If `ssh` inherits the pipe then `check_output()` will wait until it exits (until it closes its inherited pipe ends). `check_call()` code example: ``` #!/usr/bin/env pyt...
Iterate over a dict except for x item items
36,184,371
7
2016-03-23T17:01:48Z
36,184,412
9
2016-03-23T17:03:34Z
[ "python", "dictionary" ]
I have a dict in this format: ``` d_data = {'key_1':value_1,'key_2':value_2,'key_3':value_3,'key_x':value_x,'key_n':value_n} ``` and I have to iterate over it's items: ``` for key,value in columns.items(): do something ``` except for the pair: ``` 'key_x':value_x ```
Simply use the [`continue`](https://docs.python.org/2/reference/simple_stmts.html#the-continue-statement) statement, to skip ahead to the next iteration of the for loop: ``` for key,value in columns.items(): if key == 'key_x': continue # do something ```
python: check if an numpy array contains any element of another array
36,190,533
5
2016-03-23T23:19:59Z
36,190,611
8
2016-03-23T23:26:40Z
[ "python", "numpy" ]
What is the best way to check if an numpy array contains any element of another array? example: ``` array1 = [10,5,4,13,10,1,1,22,7,3,15,9] array2 = [3,4,9,10,13,15,16,18,19,20,21,22,23]` ``` I want to get a `True` if `array1` contains any value of `array2`, otherwise a `False`.
Using Pandas, you can use `isin`: ``` a1 = np.array([10,5,4,13,10,1,1,22,7,3,15,9]) a2 = np.array([3,4,9,10,13,15,16,18,19,20,21,22,23]) >>> pd.Series(a1).isin(a2).any() True ``` And using the [in1d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html#numpy.in1d) numpy function(per the comment from @...
Why can't I duplicate selected items in for loop?
36,191,418
2
2016-03-24T00:53:09Z
36,191,440
8
2016-03-24T00:56:00Z
[ "python", "python-3.x" ]
Like I have a list: `letters = ['a', 'b', 'c']` and I want to insert `'c'` at the first of the list: ``` for letter in letters: if letter == 'c': letters.insert(0, letter) ``` When I hit enter there's nothing happen and I have to force quit my terminal...
You should never mutate lists, dictionaries or other such containers while iterating over them. One way around it is to make a copy for iteration: ``` for letter in letters[:]: if letter == 'c': letters.insert(0, letter) ```
Split python dictionary to result in all combinations of values
36,198,540
7
2016-03-24T10:57:22Z
36,199,218
9
2016-03-24T11:35:20Z
[ "python", "dictionary" ]
``` my_dict = {'a':[1,2], 'b':[3], 'c':{'d':[4,5], 'e':[6,7]}} ``` I need to derive all the combinations out of it as below. ``` {'a':1, 'b':3, 'c':{'d':4, 'e':6}} {'a':1, 'b':3, 'c':{'d':4, 'e':7}} {'a':1, 'b':3, 'c':{'d':5, 'e':6}} {'a':1, 'b':3, 'c':{'d':5, 'e':7}} {'a':2, 'b':3, 'c':{'d':4, 'e':6}} ``` and so on...
``` from itertools import product my_dict = {'a':[1,2], 'b':[3], 'c':{'d':[4,5], 'e':[6,7]}} def process(d): to_product = [] # [[('a', 1), ('a', 2)], [('b', 3),], ...] for k, v in d.items(): if isinstance(v, list): to_product.append([(k, i) for i in v]) elif isinstance(v, dict):...
Read file content from S3 bucket with boto3
36,205,481
4
2016-03-24T16:41:02Z
36,205,825
7
2016-03-24T16:57:04Z
[ "python", "amazon-web-services", "amazon-s3", "boto3" ]
I read the filenames in my S3 bucket by doing ``` objs = boto3.client.list_objects(Bucket='my_bucket') while 'Contents' in objs.keys(): objs_contents = objs['Contents'] for i in range(len(objs_contents)): filename = objs_contents[i]['Key'] ``` Now, I need to get the actual content of t...
boto3 offers a resource model that makes tasks like iterating through objects easier. Unfortunately, StreamingBody doesn't provide `readline` or `readlines`. ``` s3 = boto3.resource('s3') bucket = s3.Bucket('test-bucket') # Iterates through all the objects, doing the pagination for you. Each obj # is an ObjectSummary,...
clang: error: : errorunsupported option '-fopenmp' on Mac OSX El Capitan building XGBoost
36,211,018
4
2016-03-24T22:22:56Z
36,211,162
9
2016-03-24T22:38:01Z
[ "python", "osx", "gcc", "xgboost" ]
I'm trying to build [XGBoost](http://xgboost.readthedocs.org/) package for Python following [these instructions](http://xgboost.readthedocs.org/en/latest/build.html#building-on-osx): > Here is the complete solution to use OpenMP-enabled compilers to install XGBoost. Obtain gcc-5.x.x with openmp support by `brew instal...
You installed `gcc` with Homebrew, yet the error is from `clang`. That should simply mean that your default compiler still points to `clang` instead of the newly installed `gcc`. If you read the comments in the Makefile, you'll see the following lines: ``` # choice of compiler, by default use system preference. # expo...
finding longest word in a list python
36,214,058
2
2016-03-25T04:32:40Z
36,214,066
10
2016-03-25T04:33:39Z
[ "python", "python-3.x" ]
I am trying to find the longest word in a non-empty list. My function is supposed to return the longest word. If elements are of equal length in the list, I am trying to sort out the longest in terms of Unicode sorting. For example, I am trying to return the following: ``` >>> highest_word(['a', 'cat', 'sat']) ...
Here's a simple one liner ``` print(max(['a', 'cat', 'sat', 'g'], key=lambda s: (len(s), s))) ``` This works by mapping each element of the list to a tuple containing its length and the string itself. When comparing two tuples `A` and `B`, if `A[0] > B[0]` then `A > B`. Only if `A[0] == B[0]` are the second elements...
How to compare pandas DataFrame against None in Python?
36,217,969
4
2016-03-25T10:13:46Z
36,218,033
8
2016-03-25T10:16:39Z
[ "python", "pandas", "python-2.x", "nonetype" ]
How do I compare a pandas DataFrame with `None`? I have a constructor that takes one of a `parameter_file` or a `pandas_df` but never both. ``` def __init__(self,copasi_file,row_to_insert=0,parameter_file=None,pandas_df=None): self.copasi_file=copasi_file self.parameter_file=parameter_file self.pandas_df=p...
Use `is not`: ``` if self.pandas_df is not None: print 'Do stuff' ``` [PEP 8](https://www.python.org/dev/peps/pep-0008/) says: > Comparisons to singletons like `None` should always be done with `is` or `is not`, never the equality operators. There is also a nice [explanation](http://jaredgrubb.blogspot.de/2009/...
Python remove elements from two dimensional list
36,224,325
3
2016-03-25T16:55:05Z
36,224,378
10
2016-03-25T16:58:07Z
[ "python", "arrays", "list", "max", "min" ]
Trying to remove min and max values from two dimensional list in array. My code: ``` myList = [[1, 3, 4], [2, 4, 4], [3, 4, 5]] maxV = 0 minV = myList[0]0] for list in myList: for innerlist in list: if innerlist > maxV: maxV = innerlist if innerlist < minV: minV = innerlist innerlis...
Just for the sake of showing a much simpler way of doing this using `list comprehensions`, the `sorted` method and `slicing`: ``` d = [[1, 3, 4], [2, 4, 4], [3, 4, 5]] n = [sorted(l)[1:-1] for l in d] print(n) # [[3], [4], [4]] ``` Some reading material on each of the items used to solve this problem: * [list c...
Count multiple occurrences in a set list
36,245,973
3
2016-03-27T09:47:56Z
36,245,998
7
2016-03-27T09:52:07Z
[ "python", "list", "count" ]
Is there a way to count the amount occurrences of a set of string lists? For example, when I have this list, it counts 7 `' '` blanks. ``` list = [[' ', ' ', ' ', ' ', ' ', ' ', ' ']] print(list.count(' ')) ``` Is there a way I can do this same thing but for a set of multiple lists? Like this for example below: ```...
# Solution This works: ``` >>> data = [[' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ']] >>> sum(x.count(' ') for x in data) 21 ``` You need to count in each sub list. I use a [generator expression](https://docs.python.org/3/refer...
how to setup cuDnn with theano on Windows 7 64 bit
36,248,056
4
2016-03-27T13:48:04Z
36,464,973
9
2016-04-07T01:10:01Z
[ "python", "theano", "cudnn" ]
I have installed `Theano` framework and enabled CUDA on my machine, however when I "import theano" in my python console, I got the following message: ``` >>> import theano Using gpu device 0: GeForce GTX 950 (CNMeM is disabled, CuDNN not available) ``` Now that "CuDNN not available", I downloaded `cuDnn` from Nvidia ...
There should be a way to do it by setting only the Path environment variable but I could never get that to work. The only thing that worked for me was to manually copy the CuDNN files into the appropriate folders in your CUDA installation. For example, if your CUDA installation is in C:\CUDA\v7.0 and you extracted CuD...
Importing installed package from script raises "AttributeError: module has no attribute" or "ImportError: cannot import name"
36,250,353
15
2016-03-27T17:27:05Z
36,250,354
17
2016-03-27T17:27:05Z
[ "python", "exception", "python-module", "shadowing" ]
I have a script named `requests.py` that imports the requests package. The script either can't access attributes from the package, or can't import them. Why isn't this working and how do I fix it? The following code raises an `AttributeError`. ``` import requests res = requests.get('http://www.google.ca') print(res)...
This happens because your local module named `requests.py` shadows the installed `requests` module you are trying to use. The current directory is prepended to `sys.path`, so the local name takes precedence over the installed name. An extra debugging tip when this comes up is to look at the Traceback carefully, and re...
limit() and sort() order pymongo and mongodb
36,250,963
12
2016-03-27T18:25:06Z
36,311,154
9
2016-03-30T14:01:40Z
[ "python", "mongodb", "pymongo" ]
Despite reading peoples answers stating that the sort is done first, evidence shows something different that the limit is done before the sort. Is there a way to force sort always first? ``` views = mongo.db.view_logging.find().sort([('count', 1)]).limit(10) ``` Whether I use `.sort().limit()` or `.limit().sort()`, t...
According to the [documentation](https://docs.mongodb.org/manual/reference/method/db.collection.find/#combine-cursor-methods), **regardless of which goes first in your chain of commands, `sort()` would be always applied before the `limit()`.** You can also study the [`.explain()`](https://docs.mongodb.org/manual/refer...
Counting Cars OpenCV + Python Issue
36,254,452
5
2016-03-28T00:57:19Z
36,274,515
13
2016-03-29T02:50:27Z
[ "python", "opencv", "tracking", "traffic" ]
I have been Trying to count cars when crossing the line and it works, but the problem is it counts one car many times which is ridiculous because it should be counted once Here is the code I am using: ``` import cv2 import numpy as np bgsMOG = cv2.BackgroundSubtractorMOG() cap = cv2.VideoCapture("traffic.avi") co...
# Preparation In order to understand what is happening, and eventually solve our problem, we first need to improve the script a little. I've added logging of the important steps of your algorithm, refactored the code a little, and added saving of the mask and processed images, added ability to run the script using th...
All possible ways to interleave two strings
36,260,956
19
2016-03-28T11:01:14Z
36,261,144
16
2016-03-28T11:11:36Z
[ "python", "permutation", "itertools" ]
I am trying to generate all possible ways to interleave any two arbitrary strings in Python. For example: If the two strings are `'ab'` and `'cd'`, the output I wish to get is: ``` ['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab'] ``` See `a` is always before `b` (and `c` before `d`). I am struggling to find a soluti...
## The Idea Let the two strings you want to interleave be `s` and `t`. We will use recursion to generate all the possible ways to interleave these two strings. If at any point of time we have interleaved the first `i` characters of `s` and the first `j` characters of `t` to create some string `res`, then we have two ...
All possible ways to interleave two strings
36,260,956
19
2016-03-28T11:01:14Z
36,261,206
9
2016-03-28T11:15:29Z
[ "python", "permutation", "itertools" ]
I am trying to generate all possible ways to interleave any two arbitrary strings in Python. For example: If the two strings are `'ab'` and `'cd'`, the output I wish to get is: ``` ['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab'] ``` See `a` is always before `b` (and `c` before `d`). I am struggling to find a soluti...
Highly inefficient but working: ``` def shuffle(s,t): if s=="": return [t] elif t=="": return [s] else: leftShuffle=[s[0]+val for val in shuffle(s[1:],t)] rightShuffle=[t[0]+val for val in shuffle(s,t[1:])] leftShuffle.extend(rightShuffle) return leftShuffle ...
All possible ways to interleave two strings
36,260,956
19
2016-03-28T11:01:14Z
36,271,870
13
2016-03-28T21:53:28Z
[ "python", "permutation", "itertools" ]
I am trying to generate all possible ways to interleave any two arbitrary strings in Python. For example: If the two strings are `'ab'` and `'cd'`, the output I wish to get is: ``` ['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab'] ``` See `a` is always before `b` (and `c` before `d`). I am struggling to find a soluti...
Several other solutions have already been posted, but most of them generate the full list of interleaved strings (or something equivalent to it) in memory, making their memory usage grow exponentially as a function of the input length. Surely there must be a better way. Enumerating all ways to interleave two sequences...
Cannot install pip packages due to locale.error inside Ubuntu Vagrant Box
36,283,915
5
2016-03-29T12:11:11Z
36,292,208
11
2016-03-29T18:24:31Z
[ "python", "ubuntu", "vagrant", "pip", "virtualenv" ]
I just created a vagrant box with ubuntu/trusty32. The vagrant provisioner, during box creation time, has done the following: * downloaded python virtualenv source tarball using `wget` * untarred the virtualenv source tarball using `tar zxvf ./virtualenv.tar.gz` * created a virtualenv called `venv` using `python ./vir...
First check your current **locale** config by simply putting `locale` in command line. You should see something similar to: ``` locale: Cannot set LC_CTYPE to default locale: No such file or directory LANG=C LC_CTYPE=utf8 ``` Set a valid locale in the LC\_CTYPE environment variable by running the following commands:...
Python - Shortcircuiting strange behaviour
36,289,297
3
2016-03-29T15:58:13Z
36,289,420
8
2016-03-29T16:03:31Z
[ "python", "short-circuiting" ]
In the following code fragment function `f` gets executed as expected: ``` def f(): print('hi') f() and False #Output: 'hi' ``` But in the following similar code fragment `a` doesn't increment: ``` a=0 a+=1 and False a #Output: 0 ``` But if we shortcircuit with True instead of False `a` gets incremented: ``` a=0...
That's because `f() and False` is an expression (technically a single-expression statement) whereas `a += 1 and False` is an assignment statement. It actually resolves to `a += (1 and False)`, and since `1 and False` equals `False` and `False` is actually the integer 0, what happens is `a += 0`, a no-op. `(1 and True)...
Why can't I break out of this itertools infinite loop?
36,320,473
11
2016-03-30T21:57:49Z
36,320,558
10
2016-03-30T22:03:18Z
[ "python", "python-3.x", "signals", "posix" ]
In the REPL, we can usually interrupt an infinite loop with a sigint, i.e. `ctrl`+`c`, and regain control in the interpreter. ``` >>> while True: pass ... ^CTraceback (most recent call last): File "<stdin>", line 1, in <module> KeyboardInterrupt >>> ``` But in this loop, the interrupt seems to be blocked and I hav...
The `KeyboardInterrupt` is checked after each Python instruction. `itertools.repeat` and the tuple generation is handled in C Code. The interrupt is handled afterwards, i.e. never.
find the set of integers for which two linear equalities holds true
36,321,558
6
2016-03-30T23:28:49Z
36,376,671
7
2016-04-02T17:39:35Z
[ "java", "c#", "python", "algorithm", "language-agnostic" ]
What algorithm can I use to find the set of all positive integer values of `n1, n2, ... ,n7` for which the the following inequalities holds true. ``` 97n1 + 89n2 + 42n3 + 20n4 + 16n5 + 11n6 + 2n7 - 185 > 0 -98n1 - 90n2 - 43n3 - 21n4 - 17n5 - 12n6 - 3n7 + 205 > 0 n1 >= 0, n2 >= 0, n3 >=0. n4 >=0, n5 >=0, n6 >=0, n7 >= ...
Reti43 has the right idea, but there's a quick recursive solution that works with less restrictive assumptions about your inequalities. ``` def solve(smin, smax, coef1, coef2): """ Return a list of lists of non-negative integers `n` that satisfy the inequalities, sum([coef1[i] * n[i] for i in range(le...
matplotlib error - no module named tkinter
36,327,134
4
2016-03-31T07:42:34Z
36,327,323
9
2016-03-31T07:53:42Z
[ "python", "matplotlib", "tkinter" ]
I tried to use the matplotlib package via Pycharm IDE on windows 10. when I run this code: ``` from matplotlib import pyplot ``` I get the following error: ``` ImportError: No module named 'tkinter' ``` I know that in python 2.x it was called Tkinter, but that is not the problem - I just installed a brand new pytho...
``` sudo apt-get install python3-tk ``` Then, ``` >> import tkinter # all fine ``` **Edit**: For Windows, I think the problem is you didn't install complete Python package. Since Tkinter should be shipped with Python out of box. See: <http://www.tkdocs.com/tutorial/install.html> I suggest install [ipython](https:/...
how to get multiple conditional operations after a Pandas groupby?
36,337,012
5
2016-03-31T14:57:57Z
36,341,363
9
2016-03-31T18:51:10Z
[ "python", "pandas" ]
consider the following example: ``` import pandas as pd import numpy as np df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : [12,10,-2,-4,-2,5,8,7], 'C' : [-5,5,-20,0,1,5,4,-4]}) df Out[12]: A B C 0 foo ...
Another alternative is to precompute the values you will need before using `groupby/agg`: ``` import numpy as np import pandas as pd N = 1000 df = pd.DataFrame({'A' : np.random.choice(['foo', 'bar'], replace=True, size=(N,)), 'B' : np.random.randint(-10, 10, size=(N,)), 'C' : np....
getting the last index, better to use len(list)-1 or use own variable?
36,340,008
2
2016-03-31T17:33:10Z
36,340,108
7
2016-03-31T17:38:46Z
[ "python" ]
In my code below, would it be better to use the i = len(scheduled\_meetings)-1 or the i=0/i+=1 method? I know the cost of len() is O(1) and it's probably more clear whats going on this way, but it gets calculated for every m in sorted\_meetings. i=0 is set once then only incremented if something is appended to the list...
Use neither of these. Use `your_list[-1]` instead. It's less code and doesn't require other variables like `i`. `-1` means *the first element from the right* which is apparently the last element of the list. See *Example 3.7* [here](http://www.diveintopython.net/native_data_types/lists.html) for more information abou...
asyncio.ensure_future vs. BaseEventLoop.create_task vs. simple coroutine?
36,342,899
7
2016-03-31T20:15:20Z
36,415,477
7
2016-04-05T01:11:12Z
[ "python", "python-3.x", "python-3.5", "coroutine", "python-asyncio" ]
I've seen several basic Python 3.5 tutorials on asyncio doing the same operation in various flavours. In this code: ``` import asyncio async def doit(i): print("Start %d" % i) await asyncio.sleep(3) print("End %d" % i) return i if __name__ == '__main__': loop = asyncio.get_event_loop() #fut...
## `ensure_future` vs `create_task` `ensure_future` is method to create [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task) from [`coroutine`](https://docs.python.org/3/library/asyncio-task.html#coroutines). It creates task different ways based on argument (including using of `create_task` for c...
What is the equivalent of from django.views.generic.simple import direct_to_template in django 1.9
36,349,646
6
2016-04-01T06:40:35Z
36,349,783
8
2016-04-01T06:50:09Z
[ "python", "django" ]
I want to make my home page as `index.html` which is located inside the template directory named as `templates/castle_tm/index.html`, but the url shows > "no module named simple". Generic based views are deprecated in django >1.4. Now, How can i redirect the home page to index.html urls.py ``` from django.conf.urls...
In latest versions of django you can use [`TemplateView`](https://docs.djangoproject.com/en/1.9/ref/class-based-views/base/#templateview) ``` from django.views.generic import TemplateView ... url(r'^api/casinova$', TemplateView.as_view(template_name='castle_tm/index.html')), ```
High performance array mean
36,351,317
9
2016-04-01T08:14:51Z
36,355,092
9
2016-04-01T11:22:56Z
[ "python", "arrays", "numpy", "matrix" ]
I've got a performance bottleneck. I'm computing the column-wise mean of large arrays (250 rows & 1.3 million columns), and I do so more than a million times in my application. My test case in Python: ``` import numpy as np big_array = np.random.random((250, 1300000)) %timeit mean = big_array.mean(axis = 0) # ~400 mi...
Julia, if I'm not mistaken, uses fortran ordering in memory as opposed to numpy which uses C memory layout by default. So if you rearrange things to adhere to the same layout so that the mean is happening along contiguous memory, you get better performance: ``` In [1]: import numpy as np In [2]: big_array = np.random...
how to remove a object in a python list
36,360,632
6
2016-04-01T15:51:38Z
36,360,751
8
2016-04-01T15:58:12Z
[ "python" ]
I create a class named point as following: ``` class point: def __init__(self): self.x = 0 self.y = 0 ``` and create a list of point ``` p1 = point() p1.x = 1 p1.y = 1 p2 = point() p2.x = 2 p2.y = 2 p_list = [] p_list.append(p1) p_list.append(p2) ``` Now I'd like remove the point, which x = 1 an...
Your `__cmp__` function is not correct. [`__cmp__`](https://docs.python.org/2/reference/datamodel.html#object.__cmp__) should return `-1/0/+1` depending on whether the second element is smaller/equal/greater than `self`. So when your `__cmp__` is called, it returns `True` if the elements are equal, which is then interp...
Python naming convention - namedtuples
36,371,047
6
2016-04-02T08:33:34Z
36,371,122
7
2016-04-02T08:43:27Z
[ "python", "python-3.x", "naming-conventions", "pep8", "namedtuple" ]
I am new to Python and I have been reading both the online documentation and (trying) to follow [PEP 0008](https://www.python.org/dev/peps/pep-0008/) to have a good Python code style. I am curious about the code segment I found in the official Python [docs](https://docs.python.org/3/library/re.html#writing-a-tokenizer)...
In the code-segment you provided, `Token` is a [**named tuple**](https://docs.python.org/3/library/collections.html#collections.namedtuple), definitely not a constant. It does not follow other variable names naming style only to put emphasis on the fact that it is a **class factory function**. No warning will occur fro...
Get part of an integer in Python
36,378,479
4
2016-04-02T20:41:40Z
36,378,493
9
2016-04-02T20:42:54Z
[ "python", "integer" ]
Is there an elegant way (maybe in `numpy`) to get a given part of a Python integer, eg say I want to get `90` from `1990`. I can do: ``` my_integer = 1990 int(str(my_integer)[2:4]) # 90 ``` But it is quite ugly. Any other option?
`1990 % 100` would do the trick. (`%` is the modulo operator and returns the remainder of the division, here 1990 = 19\*100 + 90.) --- *Added after answer was accepted:* If you need something generic, try this: ``` def GetIntegerSlice(i, n, m): # return nth to mth digit of i (as int) l = math.floor(math.log10(...
How to integrate Flask & Scrapy?
36,384,286
6
2016-04-03T10:25:38Z
37,270,442
7
2016-05-17T08:04:17Z
[ "python", "flask", "scrapy" ]
I'm using scrapy to get data and I want to use flask web framework to show the results in webpage. But I don't know how to call the spiders in the flask app. I've tried to use `CrawlerProcess` to call my spiders,but I got the error like this : ``` ValueError ValueError: signal only works in main thread Traceback (mos...
Adding HTTP server in front of your spiders is not that easy. There are couple of options. ## 1. Python subprocess If you are really limited to Flask, if you can't use anything else, only way to integrate Scrapy with Flask is by launching external process for every spider crawl as other answer recommends (note that y...
What range function does to a python list?
36,386,543
4
2016-04-03T14:17:50Z
36,386,595
9
2016-04-03T14:22:32Z
[ "python", "python-2.7" ]
I am not able to figure out what is happening here. Appending reference to `range` function is kind of creating a recursive list at index `3`. ``` >>> x = range(3) [0, 1, 2] >>> x.append(x) [0, 1, 2, [...]] >>> x[3][3][3][3][0] = 5 [5, 1, 2, [...]] ``` Where as, when I try this: ``` >>> x = range(3) [0, 1, 2...
In python2, `range`s are `list`s. `list`s, and most of the things in python are *objects* with *identities*. ``` li = [0,1] li[1] = li # [0, [...]] # ^----v id(li) # 2146307756 id(li[1]) # 2146307756 ``` Since you're putting the list inside *itself*, you're creating a *recursive* data str...
pip install - locale.Error: unsupported locale setting
36,394,101
30
2016-04-04T03:24:45Z
36,394,262
86
2016-04-04T03:47:21Z
[ "python", "python-3.x", "centos", "pip" ]
Full stacktrace: ``` ➜ ~ pip install virtualenv Traceback (most recent call last): File "/usr/bin/pip", line 11, in <module> sys.exit(main()) File "/usr/lib/python3.4/site-packages/pip/__init__.py", line 215, in main locale.setlocale(locale.LC_ALL, '') File "/usr/lib64/python3.4/locale.py", line 592, ...
try it: ``` $ export LC_ALL=C ``` Here is my `locale` settings: ``` $ locale LANG=en_US.UTF-8 LANGUAGE= LC_CTYPE="C" LC_NUMERIC="C" LC_TIME="C" LC_COLLATE="C" LC_MONETARY="C" LC_MESSAGES="C" LC_PAPER="C" LC_NAME="C" LC_ADDRESS="C" LC_TELEPHONE="C" LC_MEASUREMENT="C" LC_IDENTIFICATION="C" LC_ALL=C ``` ***Python2.7**...
How to add index into a dict
36,395,127
5
2016-04-04T05:29:36Z
36,395,180
10
2016-04-04T05:34:35Z
[ "python", "list", "dictionary", "indexing", "list-comprehension" ]
For example, given: ``` ['A', 'B', 'A', 'B'] ``` I want to have: ``` {'A': [0, 2], 'B': [1, 3]} ``` I tried a loop that goes like; add the index of where the character is found, then replace it with `''` so the next time the loop goes through, it passes on to the next character. However, that loops doesn't work fo...
Use [enumerate](https://docs.python.org/2/library/functions.html#enumerate) and [setdefault](http://www.tutorialspoint.com/python/dictionary_setdefault.htm): ``` example = ['a', 'b', 'a', 'b'] mydict = {} for idx, item in enumerate(example): indexes = mydict.setdefault(item, []) indexes.append(idx) ```
Why I cannot import a library that is in my pip list?
36,397,885
2
2016-04-04T08:34:27Z
36,397,946
7
2016-04-04T08:37:52Z
[ "python", "import", "pip", "pypng" ]
I have just installed `pypng` library with `sudo -E pip install pypng`. I see this library in the list when I execute `pip list` (the version that I see there is `0.0.18`). When I start python (or ipython) session and execute ``` import pypng ``` I get ``` ImportError: No module named pypng ```
According to docs on [github](https://github.com/drj11/pypng#quick-start) you need to import png. ``` import png png.from_array([[255, 0, 0, 255], [0, 255, 255, 0]], 'L').save("small_smiley.png") ```
PyInstaller doesn't import Queue
36,400,111
7
2016-04-04T10:25:11Z
36,668,562
8
2016-04-16T19:15:25Z
[ "python", "pyinstaller" ]
I'm trying to compile some script with twisted and Queue. ``` pyinstaller sample.py --onefile ``` ``` # -*- coding: utf-8 -*-# from twisted import * import queue as Queue a = Queue.Queue() ``` Unfortunately, produced file fails with `ImportError: No module named queue`.
I don't think this is a PyInstaller or Twisted related issue at all. The `Queue` module is part of the standard library, and the issue is how you're naming it. In Python 2, it's `Queue` with a capital letter, but in Python 3, it's renamed `queue` to follow the more standard naming convention where modules have lowercas...
Python: Elementwise join of two lists of same length
36,403,851
5
2016-04-04T13:20:25Z
36,403,968
7
2016-04-04T13:25:01Z
[ "python" ]
I have two lists of the same length ``` a = [[1,2], [2,3], [3,4]] b = [[9], [10,11], [12,13,19,20]] ``` and want to combine them to ``` c = [[1, 2, 9], [2, 3, 10, 11], [3, 4, 12, 13, 19, 20]] ``` I do this by ``` c= [] for i in range(0,len(a)): c.append(a[i]+ b[i]) ``` However, I am used from R to avoid for l...
``` >>> help(map) map(...) map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each ...
Recognize the characters of license plate
36,407,608
4
2016-04-04T16:06:44Z
36,412,223
9
2016-04-04T20:23:53Z
[ "python", "c++", "opencv" ]
I try to recognize the characters of license plates using OCR, but my licence plate have worse quality. [![enter image description here](http://i.stack.imgur.com/a3QZd.jpg)](http://i.stack.imgur.com/a3QZd.jpg) I'm trying to somehow improve character recognition for OCR, but my best result is this:result. [![enter imag...
One possible algorithm to clean up the images is as follows: * Scale the image up, so that the letters are more substantial. * Reduce the image to only 8 colours by k-means clustering. * Threshold the image, and erode it to fill in any small gaps and make the letters more substantial. * Invert the image to make maskin...
How to create a random array in a certain range
36,412,006
6
2016-04-04T20:11:12Z
36,412,132
10
2016-04-04T20:17:55Z
[ "python", "arrays", "numpy", "random", "numpy-random" ]
Suppose I want to create a list or a numpy array of 5 elements like this: ``` array = [i, j, k, l, m] ``` where: * `i` is in range 1.5 to 12.4 * `j` is in range 0 to 5 * `k` is in range 4 to 16 * `l` is in range 3 to 5 * `m` is in range 2.4 to 8.9. This is an example to show that some ranges include fractions. What...
You can just do (thanks user2357112!) ``` [np.random.uniform(1.5, 12.4), np.random.uniform(0, 5), ...] ``` using [`numpy.random.uniform`](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.uniform.html).
map vs list; why different behaviour?
36,417,879
13
2016-04-05T05:33:00Z
36,418,140
12
2016-04-05T05:52:33Z
[ "python", "python-3.x", "functional-programming" ]
In the course of implementing the "Variable Elimination" algorithm for a Bayes' Nets program, I encountered an unexpected bug that was the result of an iterative map transformation of a sequence of objects. For simplicity's sake, I'll use an analogous piece of code here: ``` >>> nums = [1, 2, 3] >>> for x in [4, 5, 6...
The answer is very simple: [`map`](https://docs.python.org/3/library/functions.html#map) is a [lazy](http://stackoverflow.com/questions/20535342/lazy-evaluation-python) function in Python 3, it returns an iterable object (in Python 2 it returns a `list`). Let me add some output to your example: ``` In [6]: nums = [1, ...
Django: Is there a way to keep the dev server from restarting when a local .py file is changed and dynamically loaded?
36,420,833
5
2016-04-05T08:21:45Z
36,420,989
9
2016-04-05T08:28:36Z
[ "python", "django" ]
In Django (1.9) trying to load `.py` files (modules) dynamically (via `importlib`). The dynamic reload is working like a charm, but every time I reload a module, the dev server restarts, having to reload everything else. I'm pulling in a lot of outside data (xml) for testing purposes, and every time the environment re...
If you run the development server using [`--noreload`](https://docs.djangoproject.com/en/1.9/ref/django-admin/#cmdoption-runserver--noreload) parameter it will not auto reload the changes: ``` python manage.py runserver --noreload ``` > Disables the auto-reloader. This means any Python code changes you make while the...
Python decorator example
36,427,374
4
2016-04-05T13:11:02Z
36,427,481
7
2016-04-05T13:15:30Z
[ "python", "decorator", "python-decorators" ]
I am learning a bit about decorators from a great tutorial on [thecodeship](http://thecodeship.com/patterns/guide-to-python-function-decorators/) but have found myself rather confused by one example. First a simple example followed by an explanation is given for what a decorator is. ``` def p_decorate(func): def f...
Within limits, everything after the `@` is executed to *produce* a decorator. In your first example, what follows after the `@` is just a name: ``` @p_decorate ``` so Python looks up `p_decorate` and calls it with the decorated function as an argument: ``` get_text = p_decorate(get_text) ``` (oversimplified a bit, ...
create an ordered dict
36,442,146
3
2016-04-06T05:20:05Z
36,442,210
9
2016-04-06T05:24:23Z
[ "python", "dictionary" ]
I have a dict like: ``` original_dict = {'two':'2','three':'3','one':'1','foo':'squirrel'} ``` And I wanted two be in this order: `ordered_dict = OrderedDict({'one':'1','two':'2','three':'3','foo':'squirrel'`}) but I don't get the same order, `{'one':'1','two':'2','three':'3','foo':'squirrel'}` creates a dict by it...
``` order=['one','two','three','foo'] ordered_dict = OrderedDict((k, original_dict[k]) for k in order) ```
How can I programmatically terminate a running process in the same script that started it?
36,452,099
3
2016-04-06T13:06:44Z
36,453,982
8
2016-04-06T14:21:49Z
[ "java", "python", "bash", "perl", "perl6" ]
**How do I start processes from a script in a way that also allows me to terminate them?** Basically, I can easily terminate the main script, but terminating the external processes that this main script starts has been the issue. I googled like crazy for Perl 6 solutions. I was just about to post my question and then ...
For Perl 6, there seems to be the [Proc::Async](http://doc.perl6.org/type/Proc::Async) module > Proc::Async allows you to run external commands asynchronously, capturing standard output and error handles, and optionally write to its standard input. ``` # command with arguments my $proc = Proc::Async.new('echo', 'foo'...
When the Python interpreter deals with a .py file, is it different from dealing with a single statement?
36,474,782
6
2016-04-07T11:25:18Z
36,475,087
10
2016-04-07T11:38:49Z
[ "python", "python-2.7" ]
Running: ``` a = 257 b = 257 print id(a) == id(b) ``` Results in: [![same statement](http://i.stack.imgur.com/lyBdc.png)](http://i.stack.imgur.com/lyBdc.png) [![enter image description here](http://i.stack.imgur.com/5YwTb.png)](http://i.stack.imgur.com/5YwTb.png) Same statement but opposite results. Why?
## The code in `test.py` is parsed together which is more optimizable than the code parsed as separate statements in the interpreter When you put it in a `test.py` and run it *as a whole*, the byte code compiler has a better chance of analyzing the usage of literals and optimizing them. (Hence you get `a` and `b` poin...
Why do file permissions show different in Python and bash?
36,486,194
9
2016-04-07T20:07:53Z
36,487,902
9
2016-04-07T21:53:37Z
[ "python", "bash", "shell", "command-line", "stat" ]
From **Python**: ``` >>> import os >>> s = os.stat( '/etc/termcap') >>> print( oct(s.st_mode) ) **0o100444** ``` When I check through **Bash**: ``` $ stat -f "%p %N" /etc/termcap **120755** /etc/termcap ``` Why does this return a different result?
This is because your /etc/termcap is a **symlink**. Let me demonstrate this to you: **Bash**: ``` $ touch bar $ ln -s bar foo $ stat -f "%p %N" foo 120755 foo $ stat -f "%p %N" bar 100644 bar ``` **Python**: ``` >>> import os >>> oct(os.stat('foo').st_mode) '0100644' >>> oct(os.stat('bar').st_mode) '0100644' >>> oc...
Convert list into tuple then add this tuple into list in python
36,489,069
2
2016-04-07T23:39:30Z
36,489,147
8
2016-04-07T23:46:33Z
[ "python", "python-3.x" ]
Hi I want my output to be ``` add_sizes(['hello', 'world']) -> [('hello', 5), ('world', 5)] ``` but I'm getting ``` add_sizes(['hello', 'world']) -> [('hello', 5), ('hello', 5, 'helloworld', 5)] ``` My code is ``` def add_sizes(strings): s = () t=[] m=[] for i in strings: x=i for i...
Just use a list comprehension: ``` >>> def add_sizes(strings): ... return [(s, len(s)) for s in strings] ... >>> >>> add_sizes(['hello', 'world']) [('hello', 5), ('world', 5)] ``` Or if you want to do it in-place: ``` >>> def add_size(strings): ... for i, s in enumerate(strings): ... strings[i] = (...
How to effectively apply gradient clipping in tensor flow?
36,498,127
4
2016-04-08T11:09:55Z
36,501,922
7
2016-04-08T14:15:39Z
[ "python", "machine-learning", "tensorflow", "deep-learning", "lstm" ]
Considering the [example code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3%20-%20Neural%20Networks/recurrent_network.py). I would like to know How to apply gradient clipping on this network on the RNN where there is a possibility of exploding gradients. ``` tf.clip_by_value(t, clip_val...
Gradient clipping needs to happen after computing the gradients, but before applying them to update the model's parameters. In the example you're referring to, both of those things are handled by the `AdamOptimizer.minimize()` method on [line 76](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples...
Height of binary tree
36,500,291
5
2016-04-08T13:02:38Z
36,500,340
8
2016-04-08T13:05:01Z
[ "python", "python-3.x" ]
I'm trying to implement a recursive method to calculate the height of a binary tree. Here is the "height"-code: ``` def height(self): if self.root==None: return 0 return max(height(self.root.left), height(self.root.right))+1 ``` When I try to call the function, I get the following error msg: ``` Name...
This is a method of your class, hence you must call it from an instance (`self`) or the class itself. Though it won't work as you think, unless you define it as a `staticmethod` or change your call, e.g. ``` def height(self): return 1 + max(self.left.height() if self.left is not None else 0, se...
Sort a list in python based on another sorted list
36,518,800
4
2016-04-09T15:22:38Z
36,518,844
7
2016-04-09T15:25:55Z
[ "python", "list", "sorting" ]
I would like to sort a list in Python based on a pre-sorted list ``` presorted_list = ['2C','3C','4C','2D','3D','4D'] unsorted_list = ['3D','2C','4D','2D'] ``` Is there a way to sort the list to reflect the presorted list despite the fact that not all the elements are present in the unsorted list? I want the result ...
``` In [5]: sorted(unsorted_list, key=presorted_list.index) Out[5]: ['2C', '2D', '3D', '4D'] ``` or, for better performance (particularly when `len(presorted_list)` is large), ``` In [6]: order = {item:i for i, item in enumerate(presorted_list)} In [7]: sorted(unsorted_list, key=order.__getitem__) Out[7]: ['2C', ...
Pandas: how to get rid of `Unnamed:` column in a dataframe
36,519,086
4
2016-04-09T15:47:43Z
36,519,122
8
2016-04-09T15:50:11Z
[ "python", "pandas", "ipython" ]
I have a situation wherein sometimes when I read a `csv` from `df` I get an unwanted index-like column named `unnamed:0`. This is very annoying! I have tried ``` merge.to_csv('xy.df', mode = 'w', inplace=False) ``` which I thought was a solution to this, but I am still getting the `unnamed:0` column! Does anyone have...
It's the index column, pass `index=False` to not write it out, see the [docs](http://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.DataFrame.to_csv.html) Example: ``` In [37]: df = pd.DataFrame(np.random.randn(5,3), columns=list('abc')) pd.read_csv(io.StringIO(df.to_csv())) Out[37]: Unnamed: 0 ...
Understanding == applied to a NumPy array
36,526,035
9
2016-04-10T05:06:53Z
36,526,198
12
2016-04-10T05:30:22Z
[ "python", "python-2.7", "numpy", "tensorflow" ]
I'm new to Python, and I am learning **TensorFlow**. In a tutorial using the *notMNIST dataset*, they give example code to transform the labels matrix to a one-of-n encoded array. The goal is to take an array consisting of label integers 0...9, and return a matrix where each integer has been transformed into a one-of-...
There are a few things going on here: numpy's vector ops, adding a singleton axis, and broadcasting. First, you should be able to see how the `==` does the magic. Let's say we start with a simple label array. `==` behaves in a vectorized fashion, which means that we can compare the entire array with a scalar and get ...
Cycle a list from alternating sides
36,533,553
27
2016-04-10T18:11:13Z
36,533,624
23
2016-04-10T18:16:17Z
[ "python", "algorithm", "list", "iteration" ]
Given a list ``` a = [0,1,2,3,4,5,6,7,8,9] ``` how can I get ``` b = [0,9,1,8,2,7,3,6,4,5] ``` That is, produce a new list in which each successive element is alternately taken from the two sides of the original list?
[`cycle`](https://docs.python.org/dev/library/itertools.html#itertools.cycle) between getting items from the forward [`iter`](https://docs.python.org/3.5/library/functions.html#iter) and the [`reversed`](https://docs.python.org/3.5/library/functions.html#reversed) one. Just make sure you stop at `len(a)` with [`islice`...