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
Cycle a list from alternating sides
36,533,553
27
2016-04-10T18:11:13Z
36,533,770
8
2016-04-10T18:26:55Z
[ "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?
A very nice one-liner in Python 2.7: ``` results = list(sum(zip(a, reversed(a))[:len(a)/2], ())) >>>> [0, 9, 1, 8, 2, 7, 3, 6, 4, 5] ``` First you zip the list with its reverse, take *half* that list, sum the tuples to form one tuple, and *then* convert to list. In Python 3, `zip` returns a generator, so you have ha...
Cycle a list from alternating sides
36,533,553
27
2016-04-10T18:11:13Z
36,533,868
50
2016-04-10T18:35: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?
``` >>> [a[-i//2] if i % 2 else a[i//2] for i in range(len(a))] [0, 9, 1, 8, 2, 7, 3, 6, 4, 5] ``` *Explanation:* This code picks numbers from the beginning (`a[i//2]`) and from the end (`a[-i//2]`) of `a`, alternatingly (`if i%2 else`). A total of `len(a)` numbers are picked, so this produces no ill effects even if...
Variable assignment faster than one liner
36,548,518
63
2016-04-11T12:19:24Z
36,549,633
87
2016-04-11T13:08:10Z
[ "python", "python-3.x", "cpython", "python-internals" ]
I have encountered this weird behavior and failed to explain it. These are the benchmarks: ``` py -3 -m timeit "tuple(range(2000)) == tuple(range(2000))" 10000 loops, best of 3: 97.7 usec per loop py -3 -m timeit "a = tuple(range(2000)); b = tuple(range(2000)); a==b" 10000 loops, best of 3: 70.7 usec per loop ``` Ho...
My results were similar to yours: the code using variables was pretty consistently 10-20 % faster. However when I used IPython on the very same Python 3.4, I got these results: ``` In [1]: %timeit -n10000 -r20 tuple(range(2000)) == tuple(range(2000)) 10000 loops, best of 20: 74.2 µs per loop In [2]: %timeit -n10000 ...
Assigning string with boolean expression
36,550,588
4
2016-04-11T13:46:24Z
36,551,857
7
2016-04-11T14:41:09Z
[ "python", "python-2.7" ]
I am trying to understand this code from someone else's project. If you want the context it's here: <https://github.com/newsapps/beeswithmachineguns/blob/master/beeswithmachineguns/bees.py#L501> `IS_PY2` is just a boolean variable, `True` if the Python major version is 2. I know that a non-empty string is `True`, but ...
The `and` and `or` operators *don't* simply perform a boolean operation on their operands, giving a boolean result. The result they give is *always* one of their operands. These operators evaluate from left to right, and they short-circuit, meaning that they stop evaluating their operands as soon as possible. In pure ...
Making len() work with instance methods
36,557,079
17
2016-04-11T19:01:52Z
36,557,192
26
2016-04-11T19:07:06Z
[ "python", "instance-methods" ]
Is there a way to make `len()` work with instance methods without modifying the class? Example of my problem: ``` >>> class A(object): ... pass ... >>> a = A() >>> a.__len__ = lambda: 2 >>> a.__len__() 2 >>> len(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type ...
No. Python always looks up special methods through the object's class. There are several good reasons for this, one being that `repr(A)` should use `type(A).__repr__` instead of `A.__repr__`, which is intended to handle instances of `A` instead of the `A` class itself. If you want different instances of `A` to compute...
Making len() work with instance methods
36,557,079
17
2016-04-11T19:01:52Z
36,557,277
10
2016-04-11T19:12:20Z
[ "python", "instance-methods" ]
Is there a way to make `len()` work with instance methods without modifying the class? Example of my problem: ``` >>> class A(object): ... pass ... >>> a = A() >>> a.__len__ = lambda: 2 >>> a.__len__() 2 >>> len(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type ...
Special methods such as `__len__` (double-underscore or "dunder" methods) must be defined on the class. They won't work if only defined on the instance. It is possible to define non-dunder methods on an instance. However, you must convert your function to an instance method by adding a wrapper to it, which is how `sel...
Why does dict.get(key) run slower than dict[key]
36,566,331
4
2016-04-12T07:24:26Z
36,566,435
7
2016-04-12T07:29:13Z
[ "python", "performance", "dictionary" ]
While running a numerical integrator, I noticed a noticeable difference in speed depending on how I extract the value of the field in a dictionary ``` import numpy as np def bad_get(mydict): '''Extract the name field using get()''' output = mydict.get('name', None) return output def good_get(mydict): ...
Python has to do more work for `dict.get()`: * `get` is an attribute, so Python has to look this up, and then bind the descriptor found to the dictionary instance. * `()` is a call, so the current frame has to be pushed on the stack, a call has to be made, then the frame has to be popped again from the stack to contin...
Is there a "wildcard method" in Python?
36,574,812
2
2016-04-12T13:29:30Z
36,574,885
9
2016-04-12T13:32:27Z
[ "python", "class", "methods" ]
I am looking for a way to use a method of a class which is not defined in that class, but handled dynamically. What I would like to achieve, to take an example, is to move from ``` class Hello: def aaa(self, msg=""): print("{msg} aaa".format(msg=msg)) def bbb(self, msg=""): print("{msg} bbb".f...
You could overload the class' [`__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) method: ``` class Hello: def __getattr__(self, name): def f(msg=""): print("{} {}".format(msg, name)) return f if __name__ == "__main__": h = Hello() h.aaa("hell...
Square root of complex numbers in python
36,584,466
11
2016-04-12T21:32:51Z
36,584,865
8
2016-04-12T22:03:22Z
[ "python", "math", "complex-numbers" ]
I have run across some confusing behaviour with square roots of complex numbers in python. Running this code: ``` from cmath import sqrt a = 0.2 b = 0.2 + 0j print(sqrt(a / (a - 1))) print(sqrt(b / (b - 1))) ``` gives the output ``` 0.5j -0.5j ``` A similar thing happens with ``` print(sqrt(-1 * b)) print(sqrt(-b)...
Both answers (`+0.5j` and `-0.5j`) are correct, since they are [complex conjugates](https://en.wikipedia.org/wiki/Complex_conjugate) -- i.e. the real part is identical, and the imaginary part is sign-flipped. Looking at the [code](https://hg.python.org/cpython/file/tip/Modules/cmathmodule.c#l732) makes the behavior cl...
Splitting a python list into a list of overlapping chunks
36,586,897
3
2016-04-13T01:21:52Z
36,586,925
7
2016-04-13T01:26:03Z
[ "python" ]
hi this question is similar to this other [Slicing a list into a list of sub-lists](http://stackoverflow.com/questions/2231663/slicing-a-list-into-a-list-of-sub-lists), but in my case I want to include the last element of the each previous sub-list, as the first element in the next sub-list. And have to take into accou...
``` >>> list_ = ['a','b','c','d','e','f','g','h'] >>> n = 3 # group size >>> m = 1 # overlap size >>> [list_[i:i+n-m+1] for i in xrange(0,len(list_), n-m)] [['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f', 'g'], ['g', 'h']] ```
What does x[x < 2] = 0 mean in Python?
36,603,042
83
2016-04-13T15:27:15Z
36,603,120
44
2016-04-13T15:31:00Z
[ "python", "python-2.7", "numpy" ]
I came across some code with a line similar to ``` x[x<2]=0 ``` Playing around with variations, I am still stuck on what this syntax does. Examples: ``` >>> x = [1,2,3,4,5] >>> x[x<2] 1 >>> x[x<3] 1 >>> x[x>2] 2 >>> x[x<2]=0 >>> x [0, 2, 3, 4, 5] ```
``` >>> x = [1,2,3,4,5] >>> x<2 False >>> x[False] 1 >>> x[True] 2 ``` The bool is simply converted to an integer. The index is either 0 or 1.
What does x[x < 2] = 0 mean in Python?
36,603,042
83
2016-04-13T15:27:15Z
36,603,274
113
2016-04-13T15:37:54Z
[ "python", "python-2.7", "numpy" ]
I came across some code with a line similar to ``` x[x<2]=0 ``` Playing around with variations, I am still stuck on what this syntax does. Examples: ``` >>> x = [1,2,3,4,5] >>> x[x<2] 1 >>> x[x<3] 1 >>> x[x>2] 2 >>> x[x<2]=0 >>> x [0, 2, 3, 4, 5] ```
This only makes sense with **[NumPy](http://en.wikipedia.org/wiki/NumPy) arrays**. The behavior with lists is useless, and specific to Python 2 (not Python 3). You may want to double-check if the original object was indeed a NumPy array (see further below) and not a list. But in your code here, x is a simple list. Si...
What does x[x < 2] = 0 mean in Python?
36,603,042
83
2016-04-13T15:27:15Z
36,606,250
13
2016-04-13T18:08:26Z
[ "python", "python-2.7", "numpy" ]
I came across some code with a line similar to ``` x[x<2]=0 ``` Playing around with variations, I am still stuck on what this syntax does. Examples: ``` >>> x = [1,2,3,4,5] >>> x[x<2] 1 >>> x[x<3] 1 >>> x[x>2] 2 >>> x[x<2]=0 >>> x [0, 2, 3, 4, 5] ```
The original code in your question works only in Python 2. If `x` is a `list` in Python 2, the comparison `x < y` is `False` if `y` is an `int`eger. This is because it does not make sense to compare a list with an integer. However in Python 2, if the operands are not comparable, the comparison is based in CPython on th...
What does x[x < 2] = 0 mean in Python?
36,603,042
83
2016-04-13T15:27:15Z
36,619,440
8
2016-04-14T09:47:42Z
[ "python", "python-2.7", "numpy" ]
I came across some code with a line similar to ``` x[x<2]=0 ``` Playing around with variations, I am still stuck on what this syntax does. Examples: ``` >>> x = [1,2,3,4,5] >>> x[x<2] 1 >>> x[x<3] 1 >>> x[x>2] 2 >>> x[x<2]=0 >>> x [0, 2, 3, 4, 5] ```
This has one more use: code golf. Code golf is the art of writing programs that solve some problem in as few source code bytes as possible. ``` return(a,b)[c<d] ``` is roughly equivalent to ``` if c < d: return b else: return a ``` except that both a and b are evaluated in the first version, but not in the ...
Efficiently merge lists into a list of dictionaries
36,612,437
2
2016-04-14T01:46:51Z
36,612,461
12
2016-04-14T01:49:34Z
[ "python", "list", "dictionary" ]
I have 2 lists and I want to merge them as list of dictionaries. The code I have: ``` import pprint list1 = [1, 2, 3, 4] list2 = [0, 1, 1, 2] newlist = [] for i in range(0, len(list1)): newdict = {} newdict["original"] = list1[i] newdict["updated"] = list2[i] newlist.append(newdict) pprint.pprint(newl...
You can [zip](https://docs.python.org/3/library/functions.html#zip) your two lists and then use a list comprehension, where you create your dictionary as each item in the list: ``` list1=[1,2,3,4] list2=[0,1,1,2] new_list = [{'original': v1, 'updated': v2} for v1, v2 in zip(list1, list2)] print(new_list) ``` Output...
List of lists in to list of tuples, reordered
36,614,053
6
2016-04-14T04:43:50Z
36,614,070
10
2016-04-14T04:46:16Z
[ "python", "list", "tuples" ]
How 'pythonic-ly', do I turn this: ``` [[x1,y1], [x2,y2]] ``` Into: ``` [(x1,x2),(y1,y2)] ```
Use a [`zip`](https://docs.python.org/3/library/functions.html#zip) and unpacking operator. ``` >>> l = [['x1','y1'], ['x2','y2']] >>> zip(*l) [('x1', 'x2'), ('y1', 'y2')] ```
ignoring backslash character in python
36,623,916
2
2016-04-14T13:00:26Z
36,624,033
9
2016-04-14T13:05:31Z
[ "python" ]
This one is a bit tricky I think. if I have: ``` a = "fwd" b = "\fwd" ``` how can I ignore the `"\"` so something like ``` print(a in b) ``` can evaluate to True?
You don't have `fwd` in `b`. You have `wd`, preceded by [ASCII codepoint 0C, the FORM FEED character](https://en.wikipedia.org/wiki/Page_break#Form_feed). That's the value Python puts there when you use a `\f` escape sequence in a regular string literal. Double the backslash if you want to include a backslash or use a...
Compare two large dictionaries and create lists of values for keys they have in common
36,628,586
18
2016-04-14T16:16:09Z
36,628,623
27
2016-04-14T16:18:23Z
[ "python", "dictionary" ]
I have a two dictionaries like: ``` dict1 = { (1,2) : 2, (2,3): 3, (1,3): 3} dict2 = { (1,2) : 1, (1,3): 2} ``` What I want as output is two list of values for the items which exist in both dictionaries: ``` [2,3] [1,2] ``` What I am doing right now is something like this: ``` list1 = [] list2 = [] for key in dic...
``` commons = set(dict1).intersection(set(dict2)) list1 = [dict1[k] for k in commons] list2 = [dict2[k] for k in commons] ```
Compare two large dictionaries and create lists of values for keys they have in common
36,628,586
18
2016-04-14T16:16:09Z
36,628,627
14
2016-04-14T16:18:41Z
[ "python", "dictionary" ]
I have a two dictionaries like: ``` dict1 = { (1,2) : 2, (2,3): 3, (1,3): 3} dict2 = { (1,2) : 1, (1,3): 2} ``` What I want as output is two list of values for the items which exist in both dictionaries: ``` [2,3] [1,2] ``` What I am doing right now is something like this: ``` list1 = [] list2 = [] for key in dic...
Don't use `dict.keys`. On python2.x, it creates a new list every time it is called (which is an `O(N)` operation -- And `list.__contains__` is another `O(N)` operation on average). Just rely on the fact that dictionaries are iterable containers directly (with `O(1)` lookup): ``` list1 = [] list2 = [] for key in dict1...
How to perfectly convert one-element list to tuple in Python?
36,637,564
2
2016-04-15T03:04:33Z
36,637,630
7
2016-04-15T03:10:35Z
[ "python", "python-3.x", "tuples", "python-3.5" ]
So I am trying to do this: ``` tuple([1]) ``` The output I expect is : ``` (1) ``` However, I got this: ``` (1,) ``` But if I do this: ``` tuple([1,2]) ``` It works perfectly! like this: ``` (1,2) ``` This is so weird that I don't know why the tuple function cause this result. Please help me to fix it.
This is such a common question that the [Python Wiki has a page dedicated to it](https://wiki.python.org/moin/TupleSyntax): > **One Element Tuples** > > One-element tuples look like: > > `1,` > > The essential element here is the trailing comma. As for any > expression, parentheses are optional, so you may also write ...
Exceptions catching performance in python
36,642,633
7
2016-04-15T08:57:31Z
36,738,324
8
2016-04-20T08:41:27Z
[ "python", "performance", "exception-handling" ]
I know exceptions in python are fast when it comes to the `try` but that it may be expensive when it comes to the catch. Does this mean that: ``` try: some code except MyException: pass ``` is faster than this ? ``` try: some code except MyException as e: pass ```
In addition to Francesco's answer, it seems that one of the (relatively) expensive part of the catch is the exception matching: ``` >>> timeit.timeit('try:\n raise KeyError\nexcept KeyError:\n pass', number=1000000 ) 1.1587663322268327 >>> timeit.timeit('try:\n raise KeyError\nexcept:\n pass', number=10000...
difference between ways to generate index list in python
36,647,439
4
2016-04-15T12:41:01Z
36,647,879
8
2016-04-15T13:00:01Z
[ "python", "indexing" ]
I am reading Joel Grus's data science from scratch book and found something a bit mysterious. Basically, in some sample code, he wrote ``` a = [1, 2 ,3 ,4] xs = [i for i,_ in enumerate(a)] ``` Why would he prefer to do this way? Instead of ``` xs = range(len(a)) ```
I looked at [the code available on github](https://github.com/joelgrus/data-science-from-scratch) and frankly, I do not see any other reason for this except the personal preference of the author. However, the result needs to be a `list` in places like [this](https://github.com/joelgrus/data-science-from-scratch/blob/2...
difference between ways to generate index list in python
36,647,439
4
2016-04-15T12:41:01Z
36,659,915
12
2016-04-16T03:53:56Z
[ "python", "indexing" ]
I am reading Joel Grus's data science from scratch book and found something a bit mysterious. Basically, in some sample code, he wrote ``` a = [1, 2 ,3 ,4] xs = [i for i,_ in enumerate(a)] ``` Why would he prefer to do this way? Instead of ``` xs = range(len(a)) ```
Answer: personal preference of the author. I find `[i for i, _ in enumerate(xs)]` clearer and more readable than `list(range(len(xs)))` which feels clunky to me. (I don't like reading the nested functions.) Your mileage may vary (and apparently does!). That said, I am pretty sure I didn't say *not to* do the secon...
Intel MKL FATAL ERROR: Cannot load libmkl_avx2.so or libmkl_def.so
36,659,453
4
2016-04-16T02:17:52Z
36,967,410
11
2016-05-01T13:49:10Z
[ "python", "anaconda", "intel-mkl" ]
I am running a python script and I get this error: ``` Intel MKL FATAL ERROR: Cannot load libmkl_avx2.so or libmkl_def.so. ``` Both files are present in the anaconda2/lib directory. How can I fix this error? Thanks.
if you use conda , try with two commands conda install nomkl numpy scipy scikit-learn numexpr conda remove mkl mkl-service It should fix your problem
Multiple inputs from one input
36,663,600
5
2016-04-16T11:34:06Z
36,663,673
8
2016-04-16T11:40:02Z
[ "python", "python-3.x" ]
I'm writing a function to append an input to a list. I want it so that when you input `280 2` the list becomes `['280', '280']` instead of `['280 2']`.
``` >>> number, factor = input().split() 280 2 >>> [number]*int(factor) ['280', '280'] ``` Remember that concatenating a list with itself with the \* operator can have [unexpected results](http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly) if your list contai...
Python: what's the difference - abs and operator.abs
36,665,110
3
2016-04-16T13:59:38Z
36,665,125
7
2016-04-16T14:01:17Z
[ "python", "operators" ]
In python what is the difference between : `abs(a)` and `operator.abs(a)` They are the very same and they work alike. If they are the very same then why are two separate functions doing the same stuff are made?? If there is some specific functionality for any one of it - please do explain it.
There is no difference. The documentation even says so: ``` >>> import operator >>> print(operator.abs.__doc__) abs(a) -- Same as abs(a). ``` It is implemented as a wrapper just so the documentation can be updated: ``` from builtins import abs as _abs # ... def abs(a): "Same as abs(a)." return _abs(a) ``` ...
Bigquery - Insert new data row into table by python
36,673,456
3
2016-04-17T06:40:11Z
36,849,400
7
2016-04-25T19:26:45Z
[ "python", "google-bigquery" ]
I read many documents about google bigquery-python, but I can't understand how to manage bigquery data by python code. At first, I make a new table as below. ``` credentials = GoogleCredentials.get_application_default() service = build('bigquery', 'v2', credentials = credentials) project_id = 'my_project' dataset_id...
There are a few different ways that you can use to insert data to BQ. For a deeper understanding of how the python-api works, here's everything you'll need: [bq-python-api](https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/python/latest/) (at first the docs are somewhat scary but after yo...
Decorator for a class method that caches return value after first access
36,684,319
15
2016-04-18T01:55:49Z
36,684,610
8
2016-04-18T02:35:31Z
[ "python", "caching", "decorator", "python-decorators" ]
# My problem, and why I'm trying to write a decorator for a class method, `@cachedproperty`. I want it to behave so that when the method is first called, the method is replaced with its return value. I also want it to behave like `@property` so that it doesn't need to be explicitly called. Basically, it should be indi...
If you don't mind alternative solutions, I'd recommend [`lru_cache`](https://docs.python.org/3/library/functools.html#functools.lru_cache) for example ``` from functools import lru_cache class Test: @property @lru_cache(maxsize=None) def calc(self): print("Calculating") return 1 ``` Expec...
Let a class behave like it's a list in Python
36,688,966
28
2016-04-18T08:31:31Z
36,690,145
39
2016-04-18T09:30:14Z
[ "python", "list", "python-3.x" ]
I have a class which is essentially a collection/list of things. But I want to add some extra functions to this list. What I would like, is the following: * I have an instance `li = MyFancyList()`. Variable `li` should behave as it was a list whenever I use it as a list: `[e for e in li]`, `li.expand(...)`, `for e in ...
If you want only part of the list behavior, use composition (i.e. your instances hold a reference to an actual list) and implement only the methods necessary for the behavior you desire. These methods should delegate the work to the actual list any instance of your class holds a reference to, for example: ``` def __ge...
Python - Program to reduce file size is increasing file size
36,699,062
2
2016-04-18T16:05:23Z
36,699,172
7
2016-04-18T16:10:49Z
[ "python" ]
For University, I'm doing research into compression techniques. One experiment I'm trying to perform is replacing certain Welsh language letters (which are digraphs) with a single character. It would be my thought that replacing two characters with a single character would reduce the file size (however marginally) or ...
You're changing the encoding of the file. latin-1 is always 1-byte per character, but utf-8 isn't, so some of your special characters are being encoded with multiple bytes, resulting in the increase in size.
Django REST Framework + Django REST Swagger + ImageField
36,701,877
15
2016-04-18T18:42:05Z
36,876,574
7
2016-04-26T22:01:25Z
[ "python", "django", "django-rest-framework", "swagger", "django-swagger" ]
I created a simple Model with an ImageField and I wanna make an api view with django-rest-framework + django-rest-swagger, that is documented and is able to upload the file. Here is what I got: **`models.py`** ``` from django.utils import timezone from django.db import models class MyModel(models.Model): sourc...
I got this working by making a couple of changes to your code. First, in `models.py`, change `ImageField` name to `file` and use relative path to upload folder. When you upload file as binary stream, it's available in `request.data` dictionary under file key (`request.data.get('file')`), so the cleanest option is to m...
Image processing issues with blood vessels
36,711,627
11
2016-04-19T07:38:21Z
36,821,625
8
2016-04-24T09:54:51Z
[ "python", "image", "opencv", "image-processing" ]
I'm trying to extract the blood vessels from an image, and to do so, I'm first equalizing the image, applying CLAHE histogram to obtain the following result: ``` clahe = cv2.createCLAHE(clipLimit=100.0, tileGridSize=(100,100)) self.cl1 = clahe.apply(self.result_array) self.cl1 = 255 - self.cl1 ...
Getting really good results is a difficult problem (you'll probably have to somehow model the structure of the blood vessels and the noise) but you can probably still do better than filtering. One technique for addressing this kind of problems, inspired by the Canny edge detector, is using two thresholds - `[hi,low]` ...
List comprehension- fill arbitrary value if list is empty
36,743,765
2
2016-04-20T12:26:02Z
36,743,816
9
2016-04-20T12:27:59Z
[ "python", "list", "list-comprehension" ]
I am using a list comprehension to assign values to an object. In short, I have two lists. One which contains a collection of values and another which contains a collection of indices (from that previous list) ``` values = [1.4,1.5,1.6,1.8] indices = [0,1] a.newvalues = [values[i] for i in indices] ``` This works fin...
Like this? ``` values = [1.4,1.5,1.6,1.8] indices = [0,1] a.newvalues = [values[i] for i in indices] if indices else [-1] ``` I'm not sure I follow. When indices is empty, `a.newvalues` should take the value -1, not a list of some length?
Why do these two python functions return different results?
36,745,436
3
2016-04-20T13:30:36Z
36,745,510
8
2016-04-20T13:33:10Z
[ "python", "python-2.7", "python-3.x" ]
1- ``` def fib1(n): a = 0 b = 1 while a < n: print b a = b b = a+b ``` 2- ``` def fib2(n): a, b = 0,1 while a < n: print b a,b = b, b+a ``` On execution: `fib1(10)` I got the wrong answer: `0 1 2 4 8` `fib2(10)` I got the right answer: `0 1 1 2 ...
In fib 1 `a = b` overwrites the value of `a`, which means `a` is no longer the right value for the statement `b = a+b` However, in your second example both those things happen at the same time on the line `a,b = a, b+a` which means `a` is the right value still.
Automatic type conversions of user defined classes
36,745,595
8
2016-04-20T13:36:30Z
36,745,772
12
2016-04-20T13:43:45Z
[ "python", "python-3.x" ]
So what I want to do is create a class that wraps an int and allows some things not normally allowed with int types. I don't really care if its not pythonic or w/e I'm just looking for results. Here is my code: ``` class tInt(int): def __add__(self, other): if type(other) == str: return str(sel...
You need to implement an `__radd__` method to handle the case when an instance of your class is on the right hand side of the addition. The [docs](https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types) say: > These methods are called to implement the binary arithmetic operations > (+, -, \*, @, /...
set() not removing duplicates
36,750,621
2
2016-04-20T17:07:10Z
36,750,749
11
2016-04-20T17:13:26Z
[ "python", "regex", "list", "python-3.x", "set" ]
I'm trying to find unique instances of IP addresses in a file using regex. I find them fine and try to append them to a list and later try to use `set()` on my list to remove duplicates. I'm finding each item okay and there are duplicates but I can't get the list to simplify. The output of printing my set is the same a...
You are not storing the matched strings. You are storing the [*`re.Match` objects*](https://docs.python.org/3/library/re.html#match-objects). These don't compare equal even if they matched the same text, so they are all seen as unique by a `set` object: ``` >>> import re >>> line = '137.43.92.119\n' >>> match1 = re.se...
Finding ContiguousCount of items in list?
36,762,673
3
2016-04-21T07:29:35Z
36,762,749
8
2016-04-21T07:32:47Z
[ "python", "list", "counter", "contiguous" ]
Given a list: ``` >>> l = ['x', 'x', 'y', 'y', 'x'] ``` I could get the count of the list by using `collections.Counter`: ``` >>> from collections import Counter >>> Counter(l) Counter({'x': 3, 'y': 2}) ``` **How can I count contiguous items instead of the global count of the elements in the list?** E.g. ``` >>> l...
You could use built-in [`itertools.groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby) function: ``` In [3]: from itertools import groupby In [4]: l = ['x', 'x', 'y', 'y', 'x'] In [5]: list(groupby(l)) Out[5]: [('x', <itertools._grouper at 0x7fd94716f1d0>), ('y', <itertools._grouper at 0x...
Why are Python's arrays slow?
36,778,568
129
2016-04-21T19:16:49Z
36,778,655
176
2016-04-21T19:20:51Z
[ "python", "arrays", "performance", "boxing", "python-internals" ]
I expected `array.array` to be faster than lists, as arrays seem to be unboxed. However, I get the following result: ``` In [1]: import array In [2]: L = list(range(100000000)) In [3]: A = array.array('l', range(100000000)) In [4]: %timeit sum(L) 1 loop, best of 3: 667 ms per loop In [5]: %timeit sum(A) 1 loop, b...
The *storage* is "unboxed", but every time you access an element Python has to "box" it (embed it in a regular Python object) in order to do anything with it. For example, your `sum(A)` iterates over the array, and boxes each integer, one at a time, in a regular Python `int` object. That costs time. In your `sum(L)`, a...
Why are Python's arrays slow?
36,778,568
129
2016-04-21T19:16:49Z
36,781,207
76
2016-04-21T21:58:49Z
[ "python", "arrays", "performance", "boxing", "python-internals" ]
I expected `array.array` to be faster than lists, as arrays seem to be unboxed. However, I get the following result: ``` In [1]: import array In [2]: L = list(range(100000000)) In [3]: A = array.array('l', range(100000000)) In [4]: %timeit sum(L) 1 loop, best of 3: 667 ms per loop In [5]: %timeit sum(A) 1 loop, b...
To add to Tim Peters' excellent answer, arrays implement the [buffer protocol](https://docs.python.org/3/c-api/buffer.html), while lists do not. This means that, *if you are writing a C extension* (or the moral equivalent, such as writing a [Cython](http://cython.org) module), then you can access and work with the elem...
F# Equivalent of Python range
36,780,574
3
2016-04-21T21:12:09Z
36,780,819
8
2016-04-21T21:29:10Z
[ "python", "f#" ]
I've started learning F#, and one thing I've run into is I don't know any way to express the equivalent of the `range` function in Python. I know `[1..12]` is the equivalent of range(1,13). But what I want to be able to do is `range(3, 20, 2)` (I know Haskell has `[3,5..19]`). How can I express this?
``` seq { 3 .. 2 .. 20 } ``` results in ``` 3 5 7 9 11 13 15 17 19 ``` <https://msdn.microsoft.com/en-us/library/dd233209.aspx>
how to properly overload the __add__ method in python
36,785,417
9
2016-04-22T05:18:56Z
36,785,681
9
2016-04-22T05:37:31Z
[ "python", "class", "overloading" ]
I am required to write a class involving dates. I am supposed to overload the + operator to allow days being added to dates. To explain how it works: A Date object is represented as (2016,4,15) in the format year,month, date. Adding integer 10 to this should yield (2016,4,25). The Date class has values self.year,self.m...
[`__radd__`](http://www.python-course.eu/python3_magic_methods.php) handles right side addition so you need to implement that as well. I am seeing some flaws in your implementation so I recommend you using [`datetime`](https://docs.python.org/2/library/datetime.html) module *(especially **datetime.timedelta** class)* ...
How to erase line from text file in Python?
36,785,789
6
2016-04-22T05:45:00Z
36,785,843
9
2016-04-22T05:48:16Z
[ "python", "io" ]
I'm trying to make a code to rewrite a specific line from a .txt file. I can get to write in the line i want, but i can't erase the previous text on the line. Here is my code: (i'm trying a couple of things) ``` def writeline(file,n_line, text): f=open(file,'r+') count=0 for line in f: count=cou...
You are reading from the file and also writing to it. Don't do that. Instead, you should write to a [`NamedTemporaryFile`](https://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) and then [`rename`](https://docs.python.org/2/library/os.html#os.rename) it over the original file after you finish writ...
How to display full output in Jupyter, not only last result?
36,786,722
4
2016-04-22T06:43:02Z
36,835,741
8
2016-04-25T08:44:44Z
[ "python", "ipython", "jupyter" ]
I want Jupyter to print all the interactive output without resorting to print, not only the last result. How to do it? Example : ``` a=3 a a+1 ``` I would like to display > 3 > 4
Thanks to Thomas, here is the solution I was looking for: ``` from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" ```
What exactly is __weakref__ in Python?
36,787,603
22
2016-04-22T07:28:38Z
36,788,031
7
2016-04-22T07:52:29Z
[ "python", "python-3.x" ]
Surprisingly, there's no explicit documentation for `__weakref__`. Weak references are explained [here](https://docs.python.org/2/library/weakref.html). `__weakref__` is also shortly mentioned in the documentation of `__slots__`. But I could not find anything about `__weakref__` itself. What exactly is `__weakref__`? ...
the `__weakref__` variable is an attribute which enable the object in order to support the weak references and preserving the weak references to object. As you mentioned python documentation has explained the `weakref` [here](https://docs.python.org/2/library/weakref.html): > when the only remaining references to a r...
What exactly is __weakref__ in Python?
36,787,603
22
2016-04-22T07:28:38Z
36,788,452
9
2016-04-22T08:12:59Z
[ "python", "python-3.x" ]
Surprisingly, there's no explicit documentation for `__weakref__`. Weak references are explained [here](https://docs.python.org/2/library/weakref.html). `__weakref__` is also shortly mentioned in the documentation of `__slots__`. But I could not find anything about `__weakref__` itself. What exactly is `__weakref__`? ...
[Edit 1: Explain the linked list nature and when weakrefs are re-used] Interestingly enough, the [official documentation](https://docs.python.org/3/reference/datamodel.html#slots) is somewhat non-enlightening on this topic: > Without a `__weakref__` variable for each instance, classes defining `__slots__` do not supp...
What exactly is __weakref__ in Python?
36,787,603
22
2016-04-22T07:28:38Z
36,789,779
9
2016-04-22T09:18:11Z
[ "python", "python-3.x" ]
Surprisingly, there's no explicit documentation for `__weakref__`. Weak references are explained [here](https://docs.python.org/2/library/weakref.html). `__weakref__` is also shortly mentioned in the documentation of `__slots__`. But I could not find anything about `__weakref__` itself. What exactly is `__weakref__`? ...
`__weakref__` is just an opaque object that references all the weak references to the current object. In actual fact it's an instance of `weakref` (or sometimes `weakproxy`) which is both a weak reference to the object and part of a doubly linked list to all weak references for that object. It's just an implementation...
Boring Factorials in python
36,792,027
7
2016-04-22T11:00:59Z
36,792,665
7
2016-04-22T11:29:14Z
[ "python", "algorithm" ]
I am trying to understand and solve the following problem : > > Sameer and Arpit want to overcome their fear of Maths and so they have been recently practicing Maths problems a lot. Aman, their friend > > has been helping them out. But as it goes, Sameer and Arpit have got > > bored of problems involving factorials. R...
This is not a straight-forward application of the Wilson's theorem. Along with it use the following facts: * if `n >= p` then `n! = 0 (mod p)` * if `n < p` then `n! = (p-1)!/[(n+1)(n+2)..(p-1)]`. Now use the fact that `(p-1)! = -1 (mod p)`. All that is left for you to find is the [modular multiplicative inverse](https...
Python linebreak '\n' is not working when I include something at end
36,792,582
2
2016-04-22T11:25:05Z
36,792,708
7
2016-04-22T11:31:15Z
[ "python", "line-breaks" ]
The Python linebreak command \n doesn't work for me on Python 2.7 when I include something in the statement, like an int or a numpy array. Is there a way to do this? Here are some examples: ``` print("These \n linebreaks don't work:\n", 1) "These \n linebreaks don't work:\n", 1 print("These \n work fine\n") These w...
If you want to use `print` like a function, import the one from Python3. ``` >>> from __future__ import print_function >>> print("These \n linebreaks don't work:\n", 1) These linebreaks don't work: 1 ``` Now they actually do and you won't have to change anything.
PEP8 E226 recommendation
36,794,533
5
2016-04-22T12:58:57Z
36,794,875
7
2016-04-22T13:14:34Z
[ "python", "pep8" ]
The [E226](http://pep8.readthedocs.org/en/latest/intro.html#error-codes) error code is about *"missing whitespace around arithmetic operator"*. I use [Anaconda](http://damnwidget.github.io/anaconda/)'s package in Sublime which will highlight as a PEP8 E226 violation for example this line: ``` hypot2 = x*x + y*y ``` ...
The maintainers of the PEP8 tool decide what goes into it. As you noticed, these do not always match the PEP8 style guide exactly. In this particular case, I don't know whether it's an oversite by the maintainers, or a deliberate decision. You'd have to ask them to find out, or you might find the answer in the commit ...
On what CPU cores are my Python processes running?
36,795,086
19
2016-04-22T13:23:32Z
36,799,994
9
2016-04-22T17:29:38Z
[ "python", "multithreading", "python-3.x", "multiprocessing" ]
**The setup** I have written a pretty complex piece of software in Python (on a Windows PC). My software starts basically two Python interpreter shells. The first shell starts up (I suppose) when you double click the `main.py` file. Within that shell, other threads are started in the following way: ``` # Start TC...
> **Q:** Is it true that a Python interpreter uses only one CPU core at a time to run all the threads? No. GIL and CPU affinity are unrelated concepts. GIL can be released during blocking I/O operations, long CPU intensive computations inside a C extension anyway. If a thread is blocked on GIL; it is probably not on ...
Upgraded to Ubuntu 16.04 now MySQL-python dependencies are broken
36,796,167
8
2016-04-22T14:13:37Z
36,835,229
10
2016-04-25T08:17:17Z
[ "python", "mysql", "ubuntu", "pip", "ubuntu-16.04" ]
I just upgraded my Ubuntu install to 16.04 and this seems to have broken my mysql dependencies in the MySQL-python package. Here is my error message: ``` File "/opt/monitorenv/local/lib/python2.7/site-packages/sqlalchemy/engine/__init__.py", line 386, in create_engine return strategy.create(*args, **kwargs) File ...
I ended up finding the solution to my problems with `pip install --no-binary MySQL-python MySQL-python` as stated in this thread : [Python's MySQLdb can’t find libmysqlclient.dylib with Homebrewed MySQL](http://stackoverflow.com/questions/34536914/pythons-mysqldb-can-t-find-libmysqlclient-dylib-with-homebrewed-mysql)
How to remove an extension to a blob caused by morphology
36,800,444
8
2016-04-22T17:57:37Z
36,801,788
8
2016-04-22T19:21:47Z
[ "python", "opencv", "image-processing", "scipy" ]
I have an image that I'm eroding and dilating like so: ``` kernel = np.ones((5,5),np.float32)/1 eroded_img = cv2.erode(self.inpainted_adjusted_image, kernel, iterations=10) dilated_img = cv2.dilate(eroded_img, kernel, iterations=10) ``` Here's the result of the erosion and dilation: [![enter image de...
Working with a different type of threshold (adaptive threshold, which takes local brigthness into account) will already get rid of your problem: The adaptive threshold result is what you are looking for. [![enter image description here](http://i.stack.imgur.com/QWbWD.png)](http://i.stack.imgur.com/QWbWD.png) [EDIT: I...
Dictionary comprehension with lambda functions gives wrong results
36,805,071
15
2016-04-23T00:09:09Z
36,805,118
12
2016-04-23T00:16:40Z
[ "python", "dictionary", "lambda" ]
I tried the following code in Python 3.5.1: ``` >>> f = {x: (lambda y: x) for x in range(10)} >>> f[5](3) 9 ``` It's obvious that this should return `5`. I don't understand where the other value comes from, and I wasn't able to find anything. It seems like it's something related to reference - it always returns the ...
**Python scoping is lexical**. A closure will refer to the name and scope of the variable, not the actual object/value of the variable. What happens is that each lambda is capturing the variable `x` *not* the value of `x`. At the end of the loop the variable `x` is bound to 9, therefore **every lambda will refer to t...
Python Recursive Search of Dict with Nested Keys
36,808,260
6
2016-04-23T08:03:19Z
36,808,400
7
2016-04-23T08:18:44Z
[ "python", "list", "dictionary", "recursion", "global" ]
I recently had to solve a problem in a real data system with a nested dict/list combination. I worked on this for quite a while and came up with a solution, but I am very unsatisfied. I had to resort to using `globals()` and a named temporary global parameter. I do not like to use globals. That's just asking for an in...
This is a slightly modified version without using globals. Set `h` to `None` as default and create a new list for the first call to `_get_recursive_results()`. Later provide `h` as an argument in the recursive calls to `_get_recursive_results()`: ``` def _get_recursive_results(d, iter_key, get_keys, h=None): if h ...
Calculate average of every x rows in a table and create new table
36,810,595
5
2016-04-23T12:06:50Z
36,810,658
7
2016-04-23T12:13:12Z
[ "python", "python-3.x", "pandas", "numpy" ]
I have a long table of data (~200 rows by 50 columns) and I need to create a code that can calculate the mean values of every two rows and for each column in the table with the final output being a new table of the mean values. This is obviously crazy to do in Excel! I use python3 and I am aware of some similar questio...
You can create an artificial group using `df.index//2` (or as @DSM pointed out, using `np.arange(len(df))//2` - so that it works for all indices) and then use groupby: ``` df.groupby(np.arange(len(df))//2).mean() Out[13]: a b c d 0 3.0 30.5 31.5 35.0 1 7.0 35.0 21.5 25.0 2 11.0 37.5 41....
Reading Very Large One Liner Text File
36,820,605
5
2016-04-24T07:52:49Z
36,820,782
10
2016-04-24T08:15:18Z
[ "python", "python-3.x", "numbers", "text-files", "large-files" ]
I have a 30MB .txt file, with ***one*** line of data *(30 Million Digit Number)* Unfortunately, every method I've tried (`mmap.read()`, `readline()`, allocating 1GB of RAM, for loops) takes 45+ minutes to completely read the file. Every method I found on the internet seems to work on the fact that each line is small,...
The file read is quick (<1s): ``` with open('number.txt') as f: data = f.read() ``` Converting a 30-million-digit string to an integer, that's slow: ``` z=int(data) # still waiting... ``` If you store the number as raw big- or little-endian binary data, then `int.from_bytes(data,'big')` is much quicker. If I d...
Mapping two list without looping
36,822,478
5
2016-04-24T11:25:42Z
36,822,504
9
2016-04-24T11:28:40Z
[ "python" ]
I have two lists of equal length. The first list `l1` contains data. ``` l1 = [2, 3, 5, 7, 8, 10, ... , 23] ``` The second list `l2` contains the category the data in `l1` belongs to: ``` l2 = [1, 1, 2, 1, 3, 4, ... , 3] ``` How can I partition the first list based on the positions defined by numbers such as `1, 2,...
You can use a dictionary: ``` >>> l1 = [2, 3, 5, 7, 8, 10, 23] >>> l2 = [1, 1, 2, 1, 3, 4, 3] >>> d = {} >>> for i, j in zip(l1, l2): ... d.setdefault(j, []).append(i) ... >>> >>> d {1: [2, 3, 7], 2: [5], 3: [8, 23], 4: [10]} ```
Mapping two list without looping
36,822,478
5
2016-04-24T11:25:42Z
36,822,526
8
2016-04-24T11:31:10Z
[ "python" ]
I have two lists of equal length. The first list `l1` contains data. ``` l1 = [2, 3, 5, 7, 8, 10, ... , 23] ``` The second list `l2` contains the category the data in `l1` belongs to: ``` l2 = [1, 1, 2, 1, 3, 4, ... , 3] ``` How can I partition the first list based on the positions defined by numbers such as `1, 2,...
If a `dict` is fine, I suggest using a [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict): ``` >>> from collections import defaultdict >>> d = defaultdict(list) >>> for number, category in zip(l1, l2): ... d[category].append(number) ... >>> d defaultdict(<type 'list'>, {1:...
PEP8 – import not at top of file with sys.path
36,827,962
5
2016-04-24T19:35:39Z
38,338,146
7
2016-07-12T20:16:57Z
[ "python", "python-3.x", "pep8" ]
# Problem PEP8 has a rule about putting imports at the top of a file: > Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. However, in certain cases, I might want to do something like: ``` import sys sys.path.insert("..", 0) import...
If there are just a few imports, you can just ignore PEP8 on those `import` lines: ``` import sys sys.path.insert("..", 0) import my_module # noqa ```
Modifying ancestor nested Meta class in descendant
36,835,177
3
2016-04-25T08:14:44Z
36,835,198
7
2016-04-25T08:15:42Z
[ "python", "django" ]
Suppose I have: ``` class A(object): class Meta: a = "a parameter" class B(A): class Meta: a = "a parameter" b = "b parameter" ``` How can I avoid having to rewrite the whole Meta class, when I only want to append `b = "b parameter"` to it?
You could subclass `A.Meta`: ``` class B(A): class Meta(A.Meta): b = "b parameter" ``` Now `B.Meta` inherits all attributes from `A.Meta`, and all you have to do is declare overrides or new attributes.
Lowercasing script in Python vs Perl
36,840,612
11
2016-04-25T12:29:25Z
36,987,626
7
2016-05-02T16:55:39Z
[ "python", "string", "perl", "file", "lowercase" ]
In Perl, to lowercase a textfile, I could do the following [`lowercase.perl`](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/lowercase.perl): ``` #!/usr/bin/env perl use warnings; use strict; binmode(STDIN, ":utf8"); binmode(STDOUT, ":utf8"); while(<STDIN>) { print lc($_); } ``` And on t...
Python 3.x equivalent for your Perl code may look as follows: ``` #!/usr/bin/env python3.4 import sys for line in sys.stdin: print(line[:-1].lower(), file=sys.stdout) ``` It reads stdin line-by-line and could be used in shell pipeline
Split the result of 'counter'
36,850,550
7
2016-04-25T20:34:17Z
36,850,601
8
2016-04-25T20:37:06Z
[ "python", "count" ]
I count the occurrences of items in a list using ``` timesCrime = Counter(districts) ``` Which gives me this: ``` Counter({3: 1575, 2: 1462, 6: 1359, 4: 1161, 5: 1159, 1: 868}) ``` I want to separate the parts of the list items (3 and 1575 for example) and store them in a list of lists. How do I do this?
`Counter` is a `dict`, so you have the usual `dict` methods available: ``` >>> from collections import Counter >>> counter = Counter({3: 1575, 2: 1462, 6: 1359, 4: 1161, 5: 1159, 1: 868}) >>> counter.items() [(1, 868), (2, 1462), (3, 1575), (4, 1161), (5, 1159), (6, 1359)] ``` If you wanted them stored column major, ...
Is it possible to know if two python functions are functionally equivalent?
36,852,912
5
2016-04-25T23:33:32Z
36,852,937
11
2016-04-25T23:36:04Z
[ "python", "function" ]
Let's say I have two python functions `f` and `g`: ``` def f(x): y = x**2 + 1 return y def g(x): a = x**2 b = a + 1 return b ``` These two functions are clearly functionally equivalent (both return `x**2 + 1`). My definition of functionally equivalent is as follows: **If two functions `f` and `...
By [Rice's Theorem](https://en.wikipedia.org/wiki/Rice%27s_theorem), no. If you could do this, you could solve the [halting problem](https://en.wikipedia.org/wiki/Halting_problem). (This is true even if `f` and `g` are always guaranteed to halt.)
Is it possible to run a command that is in a list?
36,868,392
5
2016-04-26T14:47:35Z
36,868,461
10
2016-04-26T14:50:31Z
[ "python" ]
I am trying to make a program that will pick a random number, and run a corresponding command to that number. I put multiple commands in a list as seen below ``` list = [cmd1(), cmd2(), cmd3(), cmd4()] x = randint(0, len(list-1)) list[x] ``` Is there any way to run a command this way? (I am using python 3.5)
Yes, functions and methods are first class objects, you can assign them, pass them as arguments, etc...: ``` commands = [cmd1, cmd2, cmd3, cmd4] # omit the parenthesis (call) current_command = random.choice(commands) current_command() ```
Appropriate Deep Learning Structure for multi-class classification
36,885,474
13
2016-04-27T09:19:02Z
36,887,827
12
2016-04-27T10:58:34Z
[ "python", "machine-learning", "scikit-learn", "tensorflow", "deep-learning" ]
I have the following data ``` feat_1 feat_2 ... feat_n label gene_1 100.33 10.2 ... 90.23 great gene_2 13.32 87.9 ... 77.18 soso .... gene_m 213.32 63.2 ... 12.23 quitegood ``` The size of `M` is large ~30K rows, and `N` is much smaller ~10 columns. My question is what is ...
To expand a little on @sung-kim 's comment: * CNN's are used primarily for problems in computer imaging, such as classifying images. They are modelled on animals visual cortex, they basically have a connection network such that there are tiles of features which have some overlap. Typically they require a lot of ...
How do I identify sequences of values in a boolean array?
36,894,822
13
2016-04-27T15:51:29Z
36,894,977
9
2016-04-27T15:58:14Z
[ "python", "list", "python-3.x", "boolean" ]
I have a long boolean array: ``` bool_array = [ True, True, True, True, True, False, False, False, False, False, True, True, True, False, False, True, True, True, True, False, False, False, False, False, False, False ] ``` I need to figure out where the values flips, i.e., the addresses where sequences of `True` and ...
This will tell you where: ``` >>> import numpy as np >>> np.argwhere(np.diff(bool_array)).squeeze() array([ 4, 9, 12, 14, 18]) ``` --- `np.diff` calculates the difference between each element and the next. For booleans, it essentially interprets the values as integers (0: False, non-zero: True), so differences appe...
How do I identify sequences of values in a boolean array?
36,894,822
13
2016-04-27T15:51:29Z
36,895,305
14
2016-04-27T16:11:21Z
[ "python", "list", "python-3.x", "boolean" ]
I have a long boolean array: ``` bool_array = [ True, True, True, True, True, False, False, False, False, False, True, True, True, False, False, True, True, True, True, False, False, False, False, False, False, False ] ``` I need to figure out where the values flips, i.e., the addresses where sequences of `True` and ...
As a more efficient approach for large datasets, in python 3.X you can use [`accumulate`](https://docs.python.org/3.5/library/itertools.html#itertools.accumulate) and [`groupby`](https://docs.python.org/3.5/library/itertools.html#itertools.groupby) function from `itertools` module. ``` >>> from itertools import accumu...
Why is this valid Python?
36,897,247
4
2016-04-27T17:48:54Z
36,897,278
9
2016-04-27T17:50:29Z
[ "python" ]
This code: ``` bounding_box = ( -122.43687629699707, 37.743774801147126 -122.3822021484375, 37.80123932755579 ) ``` produces the following value: ``` (-122.43687629699707, -84.63842734729037, 37.80123932755579) ``` There are three values because I forgot a trailing comma on the first line. Surprisingly, Pyt...
What happens is simple. In the following assignment ``` bounding_box = ( -122.43687629699707, 37.743774801147126 -122.3822021484375, 37.80123932755579 ) ``` Is equivalent to ``` bounding_box = (-122.43687629699707, **37.743774801147126-122.3822021484375**, 37.80123932755579) ``` So, the two values are just ...
In Python, when are two objects the same?
36,898,917
36
2016-04-27T19:14:23Z
36,899,010
19
2016-04-27T19:18:40Z
[ "python", "oop", "python-3.x", "object", "reference" ]
It seems that `2 is 2` and `3 is 3` will always be true in python, and in general, any reference to an integer is the same as any other reference to the same integer. The same happens to `None` (i.e., `None is None`). I know that this does *not* happen to user-defined types, or mutable types. But it sometimes fails on ...
It varies according to implementation. CPython caches some immutable objects in memory. This is true of "small" integers like 1 and 2 (-5 to 255, as noted in the comments below). CPython does this for performance reasons; small integers are commonly used in most programs, so it saves memory to only have one copy creat...
In Python, when are two objects the same?
36,898,917
36
2016-04-27T19:14:23Z
36,899,294
35
2016-04-27T19:33:37Z
[ "python", "oop", "python-3.x", "object", "reference" ]
It seems that `2 is 2` and `3 is 3` will always be true in python, and in general, any reference to an integer is the same as any other reference to the same integer. The same happens to `None` (i.e., `None is None`). I know that this does *not* happen to user-defined types, or mutable types. But it sometimes fails on ...
Python has some types that it guarantees will only have one instance. Examples of these instances are `None`, `NotImplemented`, and `Ellipsis`. These are (by definition) singletons and so things like `None is None` are guaranteed to return `True` because there is no way to create a new instance of `NoneType`. It also ...
What does Python mean by printing "[...]" for an object reference?
36,904,351
49
2016-04-28T02:46:00Z
36,904,367
48
2016-04-28T02:48:58Z
[ "python", "recursion", "ellipsis", "recursive-datastructures" ]
I'm printing a value of a what I thought was a list, but the output that I get is: ``` [...] ``` What does this represent? How do I test for it? I've tried: ``` myVar.__repr__() != '[...]' ``` and ``` myVar.__repr_() != Ellipsis ``` but no dice... Here's a cutdown of the code that's giving the issue: ``` def bu...
It represents an infinite loop within the structure. An example: ``` In [1]: l = [1, 2] In [2]: l[0] = l In [3]: l Out[3]: [[...], 2] ``` `l`'s first item is itself. It's a recursive reference, and so python can't reasonably display its contents. Instead it shows `[...]`
What does Python mean by printing "[...]" for an object reference?
36,904,351
49
2016-04-28T02:46:00Z
36,904,370
11
2016-04-28T02:49:13Z
[ "python", "recursion", "ellipsis", "recursive-datastructures" ]
I'm printing a value of a what I thought was a list, but the output that I get is: ``` [...] ``` What does this represent? How do I test for it? I've tried: ``` myVar.__repr__() != '[...]' ``` and ``` myVar.__repr_() != Ellipsis ``` but no dice... Here's a cutdown of the code that's giving the issue: ``` def bu...
It's a recursive reference as your list contains itself. Python doesn't try to recursively print this which would lead to an infinite loop. `repr` detects this. So, if you looked at the internal representation of your list object you would see (where the ellipsis occur) "Reference to the same list object at address \*...
What does Python mean by printing "[...]" for an object reference?
36,904,351
49
2016-04-28T02:46:00Z
36,904,384
20
2016-04-28T02:50:34Z
[ "python", "recursion", "ellipsis", "recursive-datastructures" ]
I'm printing a value of a what I thought was a list, but the output that I get is: ``` [...] ``` What does this represent? How do I test for it? I've tried: ``` myVar.__repr__() != '[...]' ``` and ``` myVar.__repr_() != Ellipsis ``` but no dice... Here's a cutdown of the code that's giving the issue: ``` def bu...
If your list contains self references Python will display that as `[...]` rather than trying to recursively print it out, which would lead to an infinte loop: ``` >>> l = [1, 2, 3] >>> print(l) [1, 2, 3] >>> l.append(l) >>> print(l) [1, 2, 3, [...]] >>> print(l[-1]) # print the last item of list l [1, 2, 3, [.....
What does Python mean by printing "[...]" for an object reference?
36,904,351
49
2016-04-28T02:46:00Z
36,904,517
32
2016-04-28T03:03:46Z
[ "python", "recursion", "ellipsis", "recursive-datastructures" ]
I'm printing a value of a what I thought was a list, but the output that I get is: ``` [...] ``` What does this represent? How do I test for it? I've tried: ``` myVar.__repr__() != '[...]' ``` and ``` myVar.__repr_() != Ellipsis ``` but no dice... Here's a cutdown of the code that's giving the issue: ``` def bu...
Depending on the context here it could different things: # indexing/slicing with `Ellipsis` I think it's not implemented for any python class but it *should* represent an arbitary number of data structure nestings (*as much needed*). So for example: `a[..., 1]` should return all the second elements of the innermost n...
Pairwise circular Python 'for' loop
36,917,042
74
2016-04-28T14:02:56Z
36,917,162
48
2016-04-28T14:07:53Z
[ "python" ]
Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first. So for instance, if I have the list [1, 2, 3], I would like to get the following pairs: * 1 - 2 * 2 - 3 * 3 - 1
I would use a [`deque`](https://docs.python.org/3/library/collections.html#collections.deque) with [`zip`](https://docs.python.org/3/library/functions.html#zip) to achieve this. ``` >>> from collections import deque >>> >>> l = [1,2,3] >>> d = deque(l) >>> d.rotate(-1) >>> zip(l, d) [(1, 2), (2, 3), (3, 1)] ```
Pairwise circular Python 'for' loop
36,917,042
74
2016-04-28T14:02:56Z
36,917,173
27
2016-04-28T14:08:09Z
[ "python" ]
Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first. So for instance, if I have the list [1, 2, 3], I would like to get the following pairs: * 1 - 2 * 2 - 3 * 3 - 1
There are more efficient ways (that don't built temporary lists), but I think this is the most concise: ``` > l = [1,2,3] > zip(l, (l+l)[1:]) [(1, 2), (2, 3), (3, 1)] ```
Pairwise circular Python 'for' loop
36,917,042
74
2016-04-28T14:02:56Z
36,917,441
21
2016-04-28T14:19:06Z
[ "python" ]
Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first. So for instance, if I have the list [1, 2, 3], I would like to get the following pairs: * 1 - 2 * 2 - 3 * 3 - 1
I would use a list comprehension, and take advantage of the fact that `l[-1]` is the last element. ``` >>> l = [1,2,3] >>> [(l[i-1],l[i]) for i in range(len(l))] [(3, 1), (1, 2), (2, 3)] ``` You don't need a temporary list that way.
Pairwise circular Python 'for' loop
36,917,042
74
2016-04-28T14:02:56Z
36,917,579
106
2016-04-28T14:24:38Z
[ "python" ]
Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first. So for instance, if I have the list [1, 2, 3], I would like to get the following pairs: * 1 - 2 * 2 - 3 * 3 - 1
A Pythonic way to access a list pairwise is: `zip(L, L[1:])`. To connect the last item to the first one: ``` >>> L = [1, 2, 3] >>> zip(L, L[1:] + L[:1]) [(1, 2), (2, 3), (3, 1)] ```
Pairwise circular Python 'for' loop
36,917,042
74
2016-04-28T14:02:56Z
36,917,655
39
2016-04-28T14:28:11Z
[ "python" ]
Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first. So for instance, if I have the list [1, 2, 3], I would like to get the following pairs: * 1 - 2 * 2 - 3 * 3 - 1
I'd use a slight modification to the `pairwise` recipe from the [`itertools` documentation](https://docs.python.org/3/library/itertools.html#itertools-recipes): ``` def pairwise_circle(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ... (s<last>,s0)" a, b = itertools.tee(iterable) first_value = next(b, None) ...
Pairwise circular Python 'for' loop
36,917,042
74
2016-04-28T14:02:56Z
36,918,720
19
2016-04-28T15:11:06Z
[ "python" ]
Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first. So for instance, if I have the list [1, 2, 3], I would like to get the following pairs: * 1 - 2 * 2 - 3 * 3 - 1
> # Pairwise circular Python 'for' loop If you like the accepted answer, ``` zip(L, L[1:] + L[:1]) ``` you can go much more memory light with semantically the same code using `itertools`: ``` from itertools import islice, chain #, izip as zip # uncomment if Python 2 ``` And this barely materializes anything in mem...
Pairwise circular Python 'for' loop
36,917,042
74
2016-04-28T14:02:56Z
36,918,890
37
2016-04-28T15:18:36Z
[ "python" ]
Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first. So for instance, if I have the list [1, 2, 3], I would like to get the following pairs: * 1 - 2 * 2 - 3 * 3 - 1
I would pair [`itertools.cycle`](https://docs.python.org/3.5/library/itertools.html#itertools.cycle) with `zip`: ``` import itertools def circular_pairwise(l): second = itertools.cycle(l) next(second) return zip(l, second) ``` `cycle` returns an iterable that yields the values of its argument in order, l...
Pairwise circular Python 'for' loop
36,917,042
74
2016-04-28T14:02:56Z
36,920,630
7
2016-04-28T16:38:33Z
[ "python" ]
Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first. So for instance, if I have the list [1, 2, 3], I would like to get the following pairs: * 1 - 2 * 2 - 3 * 3 - 1
This one will work even if the list `l` has consumed most of the system's memory. (If something guarantees this case to be impossible, then zip as posted by chepner is fine) ``` l.append( l[0] ) for i in range( len(l)-1): pair = l[i],l[i+1] # stuff involving pair del l[-1] ``` or more generalizably (works for a...
Pairwise circular Python 'for' loop
36,917,042
74
2016-04-28T14:02:56Z
36,924,406
10
2016-04-28T20:00:03Z
[ "python" ]
Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first. So for instance, if I have the list [1, 2, 3], I would like to get the following pairs: * 1 - 2 * 2 - 3 * 3 - 1
I like a solution that does not modify the original list and does not copy the list to temporary storage: ``` def circular(a_list): for index in range(len(a_list) - 1): yield a_list[index], a_list[index + 1] yield a_list[-1], a_list[0] for x in circular([1, 2, 3]): print x ``` Output: ``` (1, 2)...
Pairwise circular Python 'for' loop
36,917,042
74
2016-04-28T14:02:56Z
36,927,946
18
2016-04-29T01:08:22Z
[ "python" ]
Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first. So for instance, if I have the list [1, 2, 3], I would like to get the following pairs: * 1 - 2 * 2 - 3 * 3 - 1
Amazing how many different ways there are to solve this problem. Here's one more. You can use the `pairwise` recipe but instead of zipping with `b`, `chain` it with the first element that you already popped off. Don't need to `cycle` when we just need a single extra value: ``` from itertools import chain, izip, tee ...
How int() object using "==" operator without __eq__() method in python2?
36,921,558
13
2016-04-28T17:25:56Z
36,922,306
7
2016-04-28T18:04:47Z
[ "python", "python-2.7", "python-internals" ]
after I read the "Fluent python" book, I understand how `==` operator works with python objects, using `__eq__()` method. But how it works with `int` instances in python2? ``` >>> a = 1 >>> b = 1 >>> a == b True >>> a.__eq__(b) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'i...
Python [prefers to use rich comparison functions](https://docs.python.org/2/reference/datamodel.html#object.__ge__) (`__eq__`, `__lt__`, `__neq__`, etc.), but if those don't exist, it falls back to using a single comparison function (`__cmp__`, removed in Python 3): > These are the so-called “rich comparison” meth...
Can't seem to iterate over a sorted dictionary where the keys are number strings. How do you sort a dictioanry to iterate?
36,946,649
2
2016-04-29T20:08:21Z
36,946,676
8
2016-04-29T20:10:12Z
[ "python", "sorting", "dictionary" ]
I have this dictionary (dic) where the keys are strings, but the strings are actually just numbers. I can't find a way to iterate over the sorted string (since sorting the dictionary will not sort numerically) ``` for j in sorted([int(k) for k in dic.iteritems()]): print dic[str(j)] #converting the integer back i...
`dict.iteritems()` returns 2-tuples, which cannot be converted into ints. ``` for j in sorted(dic, key=int): print dic[j] ```
Removing white space from txt with python
36,957,908
9
2016-04-30T17:20:32Z
36,958,049
7
2016-04-30T17:33:16Z
[ "python", "regex", "python-2.7", "whitespace", "shlex" ]
I have a .txt file (scraped as pre-formatted text from a website) where the data looks like this: ``` B, NICKOLAS CT144531X D1026 JUDGE ANNIE WHITE JOHNSON ANDREWS VS BALL JA-15-0050 D0015 JUDGE EDWARD A ROBERTS ``` I'd like to remove all extra spaces (they'r...
You can apply the regex `'\s{2,}'` (two or more whitespace characters) to each line and substitute the matches with a single `'|'` character. ``` >>> import re >>> line = 'ANDREWS VS BALL JA-15-0050 D0015 JUDGE EDWARD A ROBERTS ' >>> re.sub('\s{2,}', '|', line.strip()) 'ANDREWS VS BALL...
Ansible roles/packages - Ansible Galaxy - error on instalation MAC OSX
36,958,125
13
2016-04-30T17:41:49Z
36,987,168
59
2016-05-02T16:29:29Z
[ "python", "ansible", "ansible-galaxy" ]
Im trying to install ansible-galaxy roles on Mac OS X El Capitan via CLI ``` $ ansible-galaxy install -r requirements.yml ``` I am getting this error: ``` ERROR! Unexpected Exception: (setuptools 1.1.6 (/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python), Requirement.parse('setuptools>=11.3')...
Run the following to upgrade setuptools under the `python` user: ``` pip install --upgrade setuptools --user python ``` For some reason, the way things are installed inside OS X (and in my case, under CentOS 7 inside a Docker container), the setuptools package doesn't get installed correctly under the right user.
Zip list of tuples with flat list
36,961,738
4
2016-05-01T00:32:43Z
36,961,763
7
2016-05-01T00:35:38Z
[ "python", "python-3.x" ]
I'm wondering if there's an easy way to do the following in Python 3.x. Say I have two lists structured as follows: ``` list_a = [(1,2), (1,2), (1,2), ...] list_b = [3, 3, 3, ...] ``` What's the simplest way to produce a generator (here represented by calling a function `funky_zip`) that would let me iterate through ...
You just need parentheses: ``` list_a = [(1,2), (1,2), (1,2)] list_b = [3, 3, 3] for (a, b), c in zip(list_a, list_b): print(a, b, c) ``` Result: ``` 1 2 3 1 2 3 1 2 3 ```
Theano CNN on CPU: AbstractConv2d Theano optimization failed
36,965,010
8
2016-05-01T09:15:23Z
37,475,827
9
2016-05-27T05:56:39Z
[ "python", "neural-network", "cpu", "theano", "blas" ]
I'm trying to train a CNN for object detection on images with the CIFAR10 dataset for a seminar at my university but I get the following Error: > AssertionError: AbstractConv2d Theano optimization failed: there is no > implementation available supporting the requested options. Did you > exclude both "conv\_dnn" and "c...
Add one line to .theanorc file ``` optimizer = None ``` as a global configuration.
Appending to list of tuples
36,966,839
3
2016-05-01T12:49:00Z
36,966,881
8
2016-05-01T12:53:08Z
[ "python" ]
I have a list of tuple which looks like this: ``` my_list = [(["$"], 1.5)] ``` And I also have these valuables stored as variables: ``` val1 = "#" val2 = 3.0 ``` I want to be able to append val1 to the list within the tuple, and multiply val2 with the second element in the tuple. It should look like thi...
Tuples are immutable. Therefore, you must create a new one: ``` for i, item in enumerate(my_list): item[0].append("#") my_list[i] = item[0], item[1] * 3 ```
Python basic Calculator program doesn't return answer
36,972,518
4
2016-05-01T22:07:06Z
36,972,552
8
2016-05-01T22:10:57Z
[ "python", "calculator" ]
So I am trying to figure out how to make a calculator with the things that I have learned in python, but I just can't make it give me an answer. This is the code I have so far: ``` def add(x, y): return x + y def subtract (x, y): return x - y def divide (x, y): return x / y def multiply (x, y): r...
Instead of: ``` choice == ("add, Add") ``` You want: ``` choice in ["add", "Add"] ``` Or more likely: ``` choice.lower() == "add" ``` Why? You're trying to check that the choice input is equal to the tuple ("add, Add") in your code which is not what you want. You instead want to check that the choice input is in ...
How to crop biggest rectangle out of an image
36,982,736
32
2016-05-02T12:41:51Z
36,988,763
10
2016-05-02T18:04:50Z
[ "python", "opencv", "image-processing" ]
I have a few images of pages on a table. I would like to crop the pages out of the image. Generally, the page will be the biggest rectangle in the image, however, all four sides of the rectangle might not be visible in some cases. I am doing the following but not getting desired results: ``` import cv2 import numpy a...
That's a pretty complicated task which cannot be solved by simply searching contours. The Economist cover for example only shows 1 edge of the magazine which splits the image in half. How should your computer know which one is the magazine and which one is the table? So you have to add much more intelligence to your pr...
How to crop biggest rectangle out of an image
36,982,736
32
2016-05-02T12:41:51Z
37,176,835
15
2016-05-12T03:38:58Z
[ "python", "opencv", "image-processing" ]
I have a few images of pages on a table. I would like to crop the pages out of the image. Generally, the page will be the biggest rectangle in the image, however, all four sides of the rectangle might not be visible in some cases. I am doing the following but not getting desired results: ``` import cv2 import numpy a...
As I have previously done something similar, I have experienced with hough transforms, but they were much harder to get right for my case than using contours. I have the following suggestions to help you get started: 1. Generally paper (edges, at least) is white, so you may have better luck by going to a colorspace li...
How to eliminate all strings from a list
37,004,138
5
2016-05-03T12:28:05Z
37,004,241
9
2016-05-03T12:31:58Z
[ "python", "python-3.x" ]
my question is how to eliminate all strings from a list, for example if I have `list=['hello',1,2,3,4,'goodbye','help']` and the outcome to be `list=[1,2,3,4]`
You need to use [`isinstance`](https://docs.python.org/3/library/functions.html#isinstance) to filter out those elements that are string. Also don't name your variable `list` it will shadow the built in `list` ``` >>> from numbers import Real >>> lst = ['hello', 1, 2, 3, 4, 'goodbye', 'help'] >>> [element for element ...
What is the fastest way to upload a big csv file in notebook to work with python pandas?
37,010,212
7
2016-05-03T17:06:48Z
37,012,035
12
2016-05-03T18:45:37Z
[ "python", "csv", "pandas", "dataframe" ]
I'm trying to upload a csv file, which is 250MB. Basically 4 million rows and 6 columns of time series data (1min). The usual procedure is: ``` location = r'C:\Users\Name\Folder_1\Folder_2\file.csv' df = pd.read_csv(location) ``` This procedure takes about 20 minutes !!!. Very preliminary I have explored the followin...
Here are results of my read and write comparison for the DF (shape: 4000000 x 6, size in memory 183.1 MB, size of uncompressed CSV - 492 MB). Comparison for the following storage formats: (`CSV`, `CSV.gzip`, `Pickle`, `HDF5` [various compression]): ``` read_s write_s size_ratio_to_CSV storage CSV ...
How to tell if a single line of python is syntactically valid?
37,012,947
15
2016-05-03T19:37:17Z
37,014,121
13
2016-05-03T20:50:31Z
[ "python", "validation" ]
It is very similar to this: [How to tell if a string contains valid Python code](http://stackoverflow.com/questions/11854745/how-to-tell-if-a-string-contains-valid-python-code) The only difference being instead of the entire program being given altogether, I am interested in a single line of code at a time. Formally...
This uses [`codeop.compile_command`](https://docs.python.org/3/library/codeop.html#codeop.compile_command) to attempt to compile the code. This is the same logic that the [`code`](https://docs.python.org/3/library/code.html) module [does](https://github.com/python/cpython/blob/master/Lib/code.py) to determine whether t...
Python dictionary doesn't have all the keys assigned, or items
37,018,085
26
2016-05-04T03:50:06Z
37,018,119
28
2016-05-04T03:53:55Z
[ "python", "dictionary" ]
I created the following dictionary ``` exDict = {True: 0, False: 1, 1: 'a', 2: 'b'} ``` and when I print `exDict.keys()`, well, it gives me a generator. Ok, so I coerce it to a list, and it gives me ``` [False, True, 2] ``` Why isn't 1 there? When I print `exDict.items()` it gives me ``` [(False, 1), (True, 'a'), ...
This happens because `True == 1` (and `False == 0`, but you didn't have `0` as a key). You'll have to refactor your code or data somehow, because a `dict` considers keys to be the same if they are "equal" (rather than `is`).
Python dictionary doesn't have all the keys assigned, or items
37,018,085
26
2016-05-04T03:50:06Z
37,018,123
12
2016-05-04T03:54:18Z
[ "python", "dictionary" ]
I created the following dictionary ``` exDict = {True: 0, False: 1, 1: 'a', 2: 'b'} ``` and when I print `exDict.keys()`, well, it gives me a generator. Ok, so I coerce it to a list, and it gives me ``` [False, True, 2] ``` Why isn't 1 there? When I print `exDict.items()` it gives me ``` [(False, 1), (True, 'a'), ...
What you are seeing is python coercing the `1` to be equal to the `True`. You'll see that the dictionary you print is: ``` False 1 True a 2 b ``` Where the value `a` was meant to be assigned to the `1`, but instead the value for `True` got reassigned to `a`. According to the [Python 3 Documentation](https:/...
Lambda use case confusion
37,046,966
9
2016-05-05T09:26:23Z
37,047,177
8
2016-05-05T09:35:58Z
[ "python" ]
I've been playing around with Celery / Django. In their example celery.py file there is the following line ``` app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) ``` Where `lambda:settings.INSTALLED_APPS` is the actual parameter for the formal parameter `packages` in `autodiscover_tasks()`. And `sett...
Since Celery is asyncrhonous it is not fixed that `settings.Installed_Apps` will not change while performing other computations, so wrapping it inside a `lambda` encapsulates it value as a reference until it gets called. **EDIT (adding an example as commented):** ``` setting.INSTALLED_APPS = 10 app.autodiscover_tasks...