instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
Dictionary comprehension with lambda functions gives wrong results
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 answer of f...
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 this x whose valu...
Spark program gives odd results when ran on standalone cluster
I have this spark program and I'll try to limit it to just the pertinent parts # Split by delimiter , # If the file is in unicode, we need to convert each value to a float in order to be able to # treat it as a number points = sc.textFile(filename).map(lambda line: [float(x) for x in line.split(",")]).persist() # sta...
Thank you for all of the time and attention to this problem, especially since it sounds like I could have posted more information to make your jobs easier. The problem here is in centroids = points.takeSample(False, K, 34) I didn't realize this, but after a short experiment, this function returns the same output each...
Hook the global name lookup in a python interpreter
Here is the thing, I have a proxy holding the reference to a remote module, and I put some of these proxies to the sys.modules such that I can use it just like local modules. But some other objects are put in the __builtin__ module at the remote environment (like a magic variable for convenience of debugging or referen...
Use AST transformation of IPython shell As @asmeurer said, you can write a simple AST transformer to "hook" the variable name lookup. The base class ast.NodeTransformer provide a visit_Name method that you can manipulate. You just need to overload this method to redefine those variables existing in the remote module bu...
Lowercasing script in Python vs Perl
In Perl, to lowercase a textfile, I could do the following lowercase.perl: #!/usr/bin/env perl use warnings; use strict; binmode(STDIN, ":utf8"); binmode(STDOUT, ":utf8"); while(<STDIN>) { print lc($_); } And on the command line: perl lowercase.perl < infile.txt > lowered.txt In Python, I could do with lowercase....
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
Appropriate Deep Learning Structure for multi-class classification
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 the appropria...
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 data, mo...
How do I identify sequences of values in a boolean array?
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 False begin...
As a more efficient approach for large datasets, in python 3.X you can use accumulate and groupby function from itertools module. >>> from itertools import accumulate, groupby >>> [0] + list(accumulate(sum(1 for _ in g) for _,g in groupby(bool_array))) [0, 5, 10, 13, 15, 19, 26] The logic behind the code: This code,...
Get params validation on viewsets.ModelViewSet
I am new to django and building a REST API using django-rest-framework. I have written some code to check whether the user has supplied some parameters or not.But that is very ugly with lot of if conditions, so i want to refactor it.Below is the code that i have written please suggest how to refactor it. I am looking f...
You can make serializers, they have a very easy way to validate your data. As in your case all the fields seem to be required it becomes even easier. Create a file on you api app like: serializers.py #Import Serializers lib from rest_framework import serializers #Import your models here (You can put more than one seri...
In Python, when are two objects the same?
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 immutable ...
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 supplies a ...
What does Python mean by printing "[...]" for an object reference?
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 buildPaths(graph, start, end, path...
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 [...]
Pairwise circular Python 'for' loop
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)]
How int() object using "==" operator without __eq__() method in python2?
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: 'int' object...
Python prefers to use rich comparison functions (__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” methods, and are called for comparison operators in preference to __cmp__() below....
Adding keys to defaultdict(dict)
I have a defaultdict that looks like this: my_dict = defaultdict(dict) which will print out: defaultdict(<class 'dict'>, {}) I also have two lists, which look like this: list1 = ["W", "IY", "W"] list2 = ["w", "ee", "w"] I would like to create a default dict which looks like this: defaultdict(<class 'dict'>, {'W': ...
Here is a solution using collections.Counter. import collections d = collections.defaultdict(collections.Counter) list1 = ["O", "TH", "O", "O"] list2 = ["o", "th", "o", "o1"] for key, value in zip(list1, list2): d[key].update([value]) >>> d defaultdict(<class 'collections.Counter'>, {'TH': Counter({'th': 1}), 'O...
Ansible roles/packages - Ansible Galaxy - error on instalation MAC OSX
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')) the full tra...
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.
How to crop biggest rectangle out of an image
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 as np ...
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: Generally paper (edges, at least) is white, so you may have better luck by going to a colorspace like ...
Scrapy: non-blocking pause
I have a problem. I need to stop the execution of a function for a while, but not stop the implementation of parsing as a whole. That is, I need a non-blocking pause. It's looks like: class ScrapySpider(Spider): name = 'live_function' def start_requests(self): yield Request('some url', callback=self.no...
If you're attempting to use this for rate limiting, you probably just want to use DOWNLOAD_DELAY instead. Scrapy is just a framework on top of Twisted. For the most part, you can treat it the same as any other twisted app. Instead of calling sleep, just return the next request to make and tell twisted to wait a bit. Ex...
Getting PyCharm to recognize python on the windows linux subsystem (bash on windows)
While running Linux versions of python, pip etc. "natively" on windows is amazing, I'd like to do so using a proper IDE. Since SSHD compatibility has not been implemented yet, I'm trying get PyCharm to recognize Linux python as a local interpreter. After installing the Windows Linux subsystem, typing bash -c python fr...
Well, I've managed to produce an ugly working hack. You'll have to install python-setuptools and pip manually under the Linux subsystem. Be sure to use the pip version provided by PyCharm, you'll find it at a path similar to: C:\Program Files (x86)\JetBrains\PyCharm 2016.1.2\helpers\pip-7.1.0.tar.gz Then setup the foll...
How to tell if a single line of python is syntactically valid?
It is very similar to this: 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, we say a line of python is "syntactically valid" if there exists any syntactically valid python pro...
This uses codeop.compile_command to attempt to compile the code. This is the same logic that the code module does to determine whether to ask for another line or immediately fail with a syntax error. import codeop def is_valid_code(line): try: codeop.compile_command(line) except SyntaxError: ret...
Python dictionary doesn't have all the keys assigned, or items
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'), (2, 'b')] Anyone have 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).
Times two faster than bit shift?
I was looking at the source of sorted_containers and was surprised to see this line: self._load, self._twice, self._half = load, load * 2, load >> 1 Here load is an integer. Why use bit shift in one place, and multiplication in another? It seems reasonable that bit shifting may be faster than integral division by 2, b...
This seems to be because multiplication of small numbers is optimized in CPython 3.5, in a way that left shifts by small numbers are not. Positive left shifts always create a larger integer object to store the result, as part of the calculation, while for multiplications of the sort you used in your test, a special op...
Is slicing really slower in Python 3.4?
This question and my answer got me thinking about this peculiar difference between Python 2.7 and Python 3.4. Take the simple example code: import timeit import dis c = 1000000 r = range(c) def slow(): for pos in range(c): r[pos:pos+3] dis.dis(slow) time = timeit.Timer(lambda: slow()).timeit(number=1) pr...
On Python 2.7, you're iterating over a list and slicing a list. On Python 3.4, you're iterating over a range and slicing a range. When I run a test with a list on both Python versions: from __future__ import print_function import timeit print(timeit.timeit('x[5:8]', setup='x = list(range(10))')) I get 0.243554830551 s...
How to *actually* read CSV data in TensorFlow?
I'm relatively new to the world of TensorFlow, and pretty perplexed by how you'd actually read CSV data into a usable example/label tensors in TensorFlow. The example from the TensorFlow tutorial on reading CSV data is pretty fragmented and only gets you part of the way to being able to train on CSV data. Here's my cod...
I think you are mixing up imperative and graph-construction parts here. The operation tf.train.shuffle_batch creates a new queue node, and a single node can be used to process the entire dataset. So I think you are hanging because you created a bunch of shuffle_batch queues in your for loop and didn't start queue runne...
How to add regularizations in TensorFlow?
I found in many available neural network code implemented using TensorFlow that regularization terms are often implemented by manually adding an additional term to loss value. My questions are: Is there a more elegant or recommended way of regularization than doing it manually? I also find that get_variable has an arg...
As you say in the second point, using the regularizer argument is the recommended way. You can use it in get_variable, or set it once in your variable_scope and have all your variables regularized. The losses are collected in the graph, and you need to manually add them to your cost function like this. reg_losses = t...
Custom chained comparisons
Python allows expressions like x > y > z, which, according to the docs, is equivalent to (x > y) and (y > z) except y is only evaluated once. (https://docs.python.org/3/reference/expressions.html) However, this seems to break if I customize comparison functions. E.g. suppose I have the following class: (Apologies for t...
Python allows expressions like x > y > z, which, according to the docs, is equivalent to (x > y) and (y > z) except y is only evaluated once. According to this, low > high > low will be equivalent to (low > high) and (high > low). >>> x = low > high # CompareList([False]) >>> y = high > low # CompareList([True]) ...
Why is it faster to break rather than to raise an exception?
After checking a few simple tests, it seems as if it might be faster to break from a loop to end a generator rather than to raise a StopIteration exception. Why is this the case if the standard and accepted method of stopping a generator is using the exception. source In [1]: def f(): ....: for i in range(1024):...
Why is this the case if the standard and accepted method of stopping a generator is using the exception. The exception StopIteration is raised only when the generator has nothing to produce any more. And, it is not a standard way of stopping a generator midway. Here are two statements from the documentation on genera...
Why does a generator using `()` need a lot of memory?
Problem Let's assume that I want to find n**2 for all numbers smaller than 20000000. General setup for all three variants that I test: import time, psutil, gc gc.collect() mem_before = psutil.virtual_memory()[3] time1 = time.time() # (comprehension, generator, function)-code comes here time2 ...
As others have pointed out in the comments, range creates a list in Python 2. Hence, it is not the generator per se that uses up the memory, but the range that the generator uses: x = (i**2 for i in range(20000000)) # builds a 2*10**7 element list, not for the squares , but for the bases >>> sys.getsizeof(range(100...
Choice made by Python 3.5 to choose the keys when comparing them in a dictionary
When constructing a dictionary as follows: dict = { True: 'yes', 1: 'No'} When I run it in the interactive Python interpreter the dict is represented this way: dict = {True: 'No'} I understand that the values True and 1 are equal due to the type coercion because when comparing numeric types, the narrowed type is wide...
Dictionaries are implemented as hash tables and there are two important concepts when adding keys/values here: hashing and equality. To insert a particular key/value, Python first computes the hash value of the key. This hash value is used to determine the row of the table where Python should first attempt to put the k...
Why does date + timedelta become date, not datetime?
In Python, in an operation of numbers of mixed type, the narrower type is widened to that of the other, such as int + float → float: In [57]: 3 + 0.1 Out[57]: 3.1 But for datetime.date, we have datetime.date + datetime.timedelta → datetime.date, not datetime.datetime: In [58]: datetime.date(2013, 1, 1) + datetime....
The behaviour is documented: date2 is moved forward in time if timedelta.days > 0, or backward if timedelta.days < 0. Afterward date2 - date1 == timedelta.days. timedelta.seconds and timedelta.microseconds are ignored. (My emphasis. This behaviour has remained unchanged since date objects were added in Python 2.3.) I...
Recursively search for parent child combinations and build tree in python and XML
I am trying to traverse this XML data full of parent->child relationships and need a way to build a tree. Any help will be really appreciated. Also, in this case, is it better to have attributes or nodes for the parent-->child relationship? <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <nodes> <node name...
It has been a long time since I did anything with graphs but this should be pretty close it not the most optimal approach: x = """<?xml version="1.0"?> <nodes> <node name="Car" child="Engine"></node> <node name="Engine" child="Piston"></node> <node name="Engine" child="Carb"></node> <node name="Car" chi...
Optimization of arithmetic expressions - what is this technique called?
A discussion with a friend led to the following realization: >>> import dis >>> i = lambda n: n*24*60*60 >>> dis.dis(i) 1 0 LOAD_FAST 0 (n) 3 LOAD_CONST 1 (24) 6 BINARY_MULTIPLY 7 LOAD_CONST 2 (60) 10 BINARY_MU...
This optimization technique is called constant folding. The reason for constant folding occurring in the latter code but not in the former is that Python has dynamic typing, and while in mathematics a product of real numbers is commutative and freely associative, it is not so in Python in the general case, because nei...
Using Deep Learning to Predict Subsequence from Sequence
I have a data that looks like this: It can be viewed here and has been included in the code below. In actuality I have ~7000 samples (row), downloadable too. The task is given antigen, predict the corresponding epitope. So epitope is always an exact substring of antigen. This is equivalent with the Sequence to Seque...
Can RNN, LSTM or GRU used to predict subsequence as posed above? Yes, you can use any of these. LSTMs and GRUs are types of RNNs; if by RNN you mean a fully-connected RNN, these have fallen out of favor because of the vanishing gradients problem (1, 2). Because of the relatively small number of examples in your da...
How to have list() consume __iter__ without calling __len__?
I have a class with both an __iter__ and a __len__ methods. The latter uses the former to count all elements. It works like the following: class A: def __iter__(self): print("iter") for _ in range(5): yield "something" def __len__(self): print("len") n = 0 fo...
It's a safe bet that the list() constructor is detecting that len() is available and calling it in order to pre-allocate storage for the list. Your implementation is pretty much completely backwards. You are implementing __len__() by using __iter__(), which is not what Python expects. The expectation is that len() is a...
In Python: How to remove an object from a list if it is only referenced in that list?
I want to keep track of objects of a certain type that are currently in use. For example: Keep track of all instances of a class or all classes that have been created by a metaclass. It is easy to keep track of instances like this: class A(): instances = [] def __init__(self): self.instances.append(self...
This answer is the same as Kevin's but I was working up an example implementation with weak references and am posting it here. Using weak references solves the problem where an object is referenced by the self.instance list, so it will never be deleted. One of the things about creating a weak reference for an object is...
ImportError: cannot import name NUMPY_MKL
I am trying to run the following simple code import scipy scipy.test() But I am getting the following error Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 586, in runfile execfile(filename, name...
If you look at the line which is causing the error, you'll see this: from numpy._distributor_init import NUMPY_MKL # requires numpy+mkl This line comment states the dependency as numpy+mkl (numpy with Intel Math Kernel Library). This means that you've installed the numpy by pip, but the scipy was installed by precomp...
"Fire and forget" python async/await
Sometimes there is some non-critical asynchronous operation that needs to happen but I don't want to wait for it to complete. In Tornado's coroutine implementation you can "fire & forget" an asynchronous function by simply ommitting the yield key-word. I've been trying to figure out how to "fire & forget" with the new...
asyncio.Task to “fire and forget” asyncio.Task is a way to start some coroutine to executing "in background". Task created by asyncio.ensure_future function wouldn't block execution (function always return immediately). Looks like a way to “fire and forget” you search. import asyncio async def async_foo(): ...
ScrapyRT vs Scrapyd
We've been using Scrapyd service for a while up until now. It provides a nice wrapper around a scrapy project and its spiders letting to control the spiders via an HTTP API: Scrapyd is a service for running Scrapy spiders. It allows you to deploy your Scrapy projects and control their spiders using a HTTP JSON API. ...
They don't have thaaat much in common. As you have already seen you have to deploy your spiders to scrapyd and then schedule crawls. scrapyd is a standalone service running on a server where you can deploy and run every project/spider you like. With ScrapyRT you choose one of your projects and you cd to that directory....
Attributes of Python module `this`
Typing import this returns Tim Peters' Zen of Python. But I noticed that there are 4 properties on the module: this.i this.c this.d this.s I can see that the statement print(''.join(this.d.get(el, el) for el in this.s)) uses this.d to decode this.s to print the Zen. But can someone tell me what the attributes this.i...
i and c are simply loop variables, used to build the d dictionary. From the module source code: d = {} for c in (65, 97): for i in range(26): d[chr(i+c)] = chr((i+13) % 26 + c) This builds a ROT-13 mapping; each ASCII letter (codepoints 65 through 90 for uppercase, 97 through 122 for lowercase) is mapped t...
What's the meaning of "(1,) == 1," in Python?
I'm testing the tuple structure, and I found it's strange when I use the == operator like: >>> (1,) == 1, Out: (False,) When I assign these two expressions to a variable, the result is true: >>> a = (1,) >>> b = 1, >>> a==b Out: True This questions is different from Python tuple trailing comma syntax rule in my view...
This is just operator precedence. Your first (1,) == 1, groups like so: ((1,) == 1), so builds a tuple with a single element from the result of comparing the one-element tuple 1, to the integer 1 for equality They're not equal, so you get the 1-tuple False, for a result.
Tweaking axis labels and names orientation for 3D plots in matplotlib
I am making this 3D plot using matplotlib: ax.plot_surface(x_surf, y_surf, np.reshape(npp, (max_temp/step, max_temp/step)), linewidth=0.2,cmap=palettable.colorbrewer.sequential.Greens_9.mpl_colormap) How can I make the axis label and axis names look more like this plot:
As far as I understood, you want change the "axis label" and "axis names". Unfortunately I could only do part of it (I hope that's something new to you and that someone else finds the second part of it): I did some changes in http://matplotlib.org/examples/mplot3d/pathpatch3d_demo.html in order to obtain the images a...
Why are literal formatted strings so slow in Python 3.6 alpha?
I've downloaded a Python 3.6 alpha build from the Python Github repository, and one of my favourite new features is literal string formatting. It can be used like so: >>> x = 2 >>> f"x is {x}" "x is 2" This appears to do the same thing as using the format function on a str instance. However, one thing that I've notice...
The f"..." syntax is effectively converted to a str.join() operation on the literal string parts around the {...} expressions, and the results of the expressions themselves passed through the object.__format__() method (passing any :.. format specification in). You can see this when disassembling: >>> import dis >>> di...
Gauss-Legendre over intervals -x -> infinity: adaptive algorithm to transform weights and nodes efficiently
Okay I know this has been asked before with a limited example for scaling [-1, 1] intervals [a, b] Different intervals for Gauss-Legendre quadrature in numpy BUT no one has posted how to generalize this for [-a, Infinity] (as is done below, but not (yet) fast). Also this shows how to call a complex function (in quanti...
I think that code does the job: import numpy as np import math deg = 10 x, w = np.polynomial.legendre.leggauss(deg) def function(x): # the function to integrate return math.exp(-x) def function2(x, a): return function(a+x/(1-x))/((1-x)**2); def anotherOne(x,...
In Python Dictionaries, how does ( (j*5)+1 ) % 2**i cycle through all 2**i
I am researching how python implements dictionaries. One of the equations in the python dictionary implementation relates the the pseudo random probing for an empty dictionary slot using the equation j = ((j*5) + 1) % 2**i which is explained here. I have read this question, How are Python's Built In Dictionaries Imp...
This is the same principle that pseudo-random number generators use, as Jasper hinted at, namely linear congruential generators. A linear congruential generator is a sequence that follows the relationship X_(n+1) = (a * X_n + c) mod m. From the wiki page, The period of a general LCG is at most m, and for some choices ...
Replacing repeated captures
This is sort of a follow-up to Python regex - Replace single quotes and brackets thread. The task: Sample input strings: RSQ(name['BAKD DK'], name['A DKJ']) SMT(name['BAKD DK'], name['A DKJ'], name['S QRT']) Desired outputs: XYZ(BAKD DK, A DKJ) XYZ(BAKD DK, A DKJ, S QRT) The number of name['something']-like items is ...
You can indeed use the regex module and repeated captures. The main interest is that you can check the structure of the matched string: import regex regO = regex.compile(r''' \w+ \( (?: name\['([^']*)'] (?: ,[ ] | (?=\)) ) )* \) ''', regex.VERBOSE); regO.sub(lambda m: 'XYZ(' + (', '.join(m.captures(1))) + ')'...
'super' object has no attribute '__eq__'
When I try to override the magic method __eq__, and use super to access the base method found in object, I get an error. There's no way this is a bug, but it sure feels like one: class A(object): def __eq__(self, other): return super(A, self).__eq__(other) A() == 0 # raises AttributeError: 'super' object h...
As noted in Will's answer, object() does not actually implement __eq__ at all for instances (in python 2.7). You are being deceived by the fact that object.__eq__ exists into believing it must be a method that checks if instances of object are equal Instead, object.__eq__ is actually a class method, inherited from type...
How can I create a type hint that my returned list contains strings?
I want to use Type Hints in my Python program. How can I create Type Hints for complex data structures like lists with strings a generator returning integers? Example def names() -> list: # I would like to specify that the list contains strings? return ['Amelie', 'John', 'Carmen'] def numbers(): # Which...
Use the typing module; it contains generics, type objects you can use to specify containers with constraints on their contents: import typing def names() -> typing.List[str]: # list object with strings return ['Amelie', 'John', 'Carmen'] def numbers() -> typing.Iterator[int]: # iterator yielding integers fo...
Spurious newlines added in Django management commands
Running Django v1.10 on Python 3.5.0: from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): print('hello ', end='', file=self.stdout) print('world', file=self.stdout) Expected output: hello world Actual output: hello world How do I ...
As is mentioned in Django 1.10's Custom Management Commands document: When you are using management commands and wish to provide console output, you should write to self.stdout and self.stderr, instead of printing to stdout and stderr directly. By using these proxies, it becomes much easier to test your custom command...
Why is dict definition faster in Python 2.7 than in Python 3.x?
I have encountered a (not very unusual) situation in which I had to either use a map() or a list comprehension expression. And then I wondered which one is faster. This StackOverflow answer provided me the solution, but then I started to test it myself. Basically the results were the same, but I found an unexpected beh...
Because nobody cares The differences you are citing are on the order of tens or hundreds of nanoseconds. A slight difference in how the C compiler optimizes register use could easily cause such changes (as could any number of other C-level optimization differences). That, in turn, could be caused by any number of thi...
What is the advantage of using a lambda:None function?
I saw the following code: eris = lambda:None eris.jkcpp = np.einsum('iipq->ipq', eriaa[:ncore[0],:ncore[0],:,:]) eris.jc_PP = np.einsum('iipq->pq', eriab[:ncore[0],:ncore[0],:,:]) Can we define arbitrary attributes for a function defined by lambda:None?
This looks like a trick to create a simple object to hold values in one line. Most built-in objects don't allow you to set arbitrary attributes on them: >>> object().x = 0 Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'object' object has no attribute 'x' >>> ''.x = 0 Traceback...
Why is statistics.mean() so slow?
I compared the performance of the mean function of the statistics module with the simple sum(l)/len(l) method and found the mean function to be very slow for some reason. I used timeit with the two code snippets below to compare them, does anyone know what causes the massive difference in execution speed? I'm using Pyt...
Python's statistics module is not built for speed, but for precision In the specs for this module, it appears that The built-in sum can lose accuracy when dealing with floats of wildly differing magnitude. Consequently, the above naive mean fails this "torture test" assert mean([1e30, 1, 3, -1e30]) == 1 returning...
addCleanUp vs tearDown
Recently, Ned Batchelder during his talk at PyCon 2016 noted: If you are using unittest to write your tests, definitely use addCleanup, it's much better than tearDown. Up until now, I've never used addCleanUp() and got used to setUp()/tearDown() pair of methods for test "set up" and "tear down" phases. Why should I...
Per the addCleanup doc string: Cleanup items are called even if setUp fails (unlike tearDown) addCleanup can be used to register multiple functions, so you could use separate functions for each resource you wish to clean up. That would allow your code to be a bit more reusable/modular.
Generating random vectors of Euclidean norm <= 1 in Python?
More specifically, given a natural number d, how can I generate random vectors in R^d such that each vector x has Euclidean norm <= 1? Generating random vectors via numpy.random.rand(1,d) is no problem, but the likelihood of such a random vector having norm <= 1 is predictably bad for even not-small d. For example, eve...
Based on the Wolfram Mathworld article on hypersphere point picking and Nate Eldredge's answer to a similar question on math.stackexchange.com, you can generate such a vector by generating a vector of d independent Gaussian random variables and a random number U uniformly distributed over the closed interval [0, 1], th...
When is hash(n) == n in Python?
I've been playing with Python's hash function. For small integers, it appears hash(n) == n always. However this does not extend to large numbers: >>> hash(2**100) == 2**100 False I'm not surprised, I understand hash takes a finite range of values. What is that range? I tried using binary search to find the smallest nu...
2305843009213693951 is 2^61 - 1. It's the largest Mersenne prime that fits into 64 bits. If you have to make a hash just by taking the value mod some number, then a large Mersenne prime is a good choice -- it's easy to compute and ensures an even distribution of possibilities. (Although I personally would never make a ...
How can I make sense of the `else` statement in Python loops?
Many Python programmers are probably unaware that the syntax of while loops and for loops includes an optional else: clause: for val in iterable: do_something(val) else: clean_up() The body of the else clause is a good place for certain kinds of clean-up actions, and is executed on normal termination of the lo...
(This is inspired by @Mark Tolonen's answer.) An if statement runs its else clause if its condition evaluates to false. Identically, a while loop runs the else clause if its condition evaluates to false. This rule matches the behavior you described: In normal execution, the while loop repeatedly runs until the conditi...
How to classify blurry numbers with openCV
I would like to capture the number from this kind of picture. I tried multi-scale matching from the following link. http://www.pyimagesearch.com/2015/01/26/multi-scale-template-matching-using-python-opencv/ All I want to know is the red number. But the problem is, the red number is blurry for openCV recognize/match ...
Classifying Digits You clarified in comments that you've already isolated the number part of the image pre-detection, so I'll start under that assumption. Perhaps you can approximate the perspective effects and "blurriness" of the number by treating it as a hand-written number. In this case, there is a famous data-set ...
Fast Numpy Loops
How do you optimize this code (without vectorizing, as this leads up to using the semantics of the calculation, which is quite often far from being non-trivial): slow_lib.py: import numpy as np def foo(): size = 200 np.random.seed(1000031212) bar = np.random.rand(size, size) moo = np.zeros((size,size),...
Here's the code for outer: def outer(a, b, out=None): a = asarray(a) b = asarray(b) return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis,:], out) So each call to outer involves a number of python calls. Those eventually call compiled code to perform the multiplication. But each incurs an overhead...
Variable step in a for loop
I am trying to loop between 0.01 and 10, but between 0.01 and 0.1 use 0.01 as the step, then between 0.1 and 1.0 use 0.1 as step, and between 1.0 and 10.0 use 1.0 as step. I have the while loop code written, but want to make it more pythonic. i = 0.01 while i < 10: # do something print i if i < 0.1: i +...
A special-purse generator function might be the right way to go. This would effectively separate the boring part (getting the list of numbers right) from the interesting part (the # do something in your example). def my_range(): for j in .01, .1, 1.: for i in range(1, 10, 1): yield i * j for x ...
How can I perform two-dimensional interpolation using scipy?
This Q&A is intended as a canonical(-ish) concerning two-dimensional (and multi-dimensional) interpolation using scipy. There are often questions concerning the basic syntax of various multidimensional interpolation methods, I hope to set these straight too. I have a set of scattered two-dimensional data points, and ...
Disclaimer: I'm mostly writing this post with syntactical considerations and general behaviour in mind. I'm not familiar with the memory and CPU aspect of the methods described, and I aim this answer at those who have reasonably small sets of data, such that the quality of the interpolation can be the main aspect to co...
How to round a number to a chosen integer
In Denmark we have an odd grading system that goes as follows. [-3,00,02,4,7,10,12] Our assignment is to take a vector with different decimal numbers, and round it to the nearest valid grade. Here is our code so far. import numpy as np def roundGrade(grades): if (-5<grades<-1.5): gradesRounded = -3 ...
You are getting that error because when you print, you are using incorrect syntax: print(roundGrade(np.array[-2.1,6.3,8.9,9])) needs to be print(roundGrade(np.array([-2.1,6.3,8.9,9]))) Notice the extra parentheses: np.array(<whatever>) However, this won't work, since your function expects a single number. Fortunatel...
mod_wsgi: Reload Code via Inotify - not every N seconds
Up to now I followed this advice to reload the code: https://code.google.com/archive/p/modwsgi/wikis/ReloadingSourceCode.wiki This has the drawback, that the code changes get detected only every N second. I could use N=0.1, but this results in useless disk IO. AFAIK the inotify callback of the linux kernel is available...
Preliminaries. Developers can use runserver or mod_wsgi. Using runserver has the benefit that you it easy for debugging, mod_wsgi has the benefit that you don't need to start the server first. But you do, the server needs to be setup first and that takes a lot of effort. And the server needs to be started here as...
Meaning of '>>' in Python byte code
I have disassembled the following python code def factorial(n): if n <= 1: return 1 elif n == 2: return 2 elif n ==4: print('hi') return n * 2 and the resulting bytecode 2 0 LOAD_FAST 0 (n) 3 LOAD_CONST 1 (1) 6 COMPARE_O...
They are jump targets; positions earlier *JUMP* bytecode jumps to when the condition is met. The first jump: 9 POP_JUMP_IF_FALSE 16 jumps to offset 16, so at offset 16 the output has a target >>: 4 >> 16 LOAD_FAST 0 (n) From the dis.disassemble() function docs names each column: [.....
Is there a Python constant for Unicode whitespace?
The string module contains a whitespace attribute, which is a string consisting of all the ASCII characters that are considered whitespace. Is there a corresponding constant that includes Unicode spaces too, such as the no-break space (U+00A0)? We can see from the question "strip() and strip(string.whitespace) give dif...
Is there a Python constant for Unicode whitespace? Short answer: No. I have personally grepped for these characters (specifically, the numeric code points) in the Python code base, and such a constant is not there. The sections below explains why it is not necessary, and how it is implemented without this information...
Cut within a pattern using Python regex
Objective: I am trying to perform a cut in Python RegEx where split doesn't quite do what I want. I need to cut within a pattern, but between characters. What I am looking for: I need to recognize the pattern below in a string, and split the string at the location of the pipe. The pipe isn't actually in the string, it ...
A non regex way would be to replace the pattern with the piped value and then split. >>> pattern = 'CDE|FG' >>> s = 'ABCDEFGHIJKLMNOCDEFGZYPE' >>> s.replace('CDEFG',pattern).split('|') ['ABCDE', 'FGHIJKLMNOCDE', 'FGZYPE']
Empty class size in python
I just trying to know the rationale behind the empty class size in python, In C++ as everyone knows the size of empty class will always shows 1 byte(as far as i have seen) this let the run time to create unique object,and i trying to find out what size of empty class in python: class Empty:pass # i hope this will creat...
I assume you are running a 64 bit version of Python 3. On 32 bit Python 3.6 (on Linux), your code prints show 508. However, that's the size of the class object itself, which inherits quite a lot of things from the base object class. If you instead get the size of an instance of your class the result is much smaller. On...
Implementing an asynchronous iterator
Per PEP-492 I am trying to implement an asynchronous iterator, such that I can do e.g. async for foo in bar: ... Here is a trivial example, similar to the one in the docs, with a very basic test of instantiation and async iteration: import pytest class TestImplementation: def __aiter__(self): return ...
If you read a little further down the documentation it mentions that (emphasis mine): PEP 492 was accepted in CPython 3.5.0 with __aiter__ defined as a method, that was expected to return an awaitable resolving to an asynchronous iterator. In 3.5.2 (as PEP 492 was accepted on a provisional basis) the __aiter__ p...
Django Left Outer Join
I have a website where users can see a list of movies, and create reviews for them. The user should be able to see the list of all the movies. Additionally, IF they have reviewed the movie, they should be able to see the score that they gave it. If not, the movie is just displayed without the score. They do not care at...
First of all, there is not a way (atm Django 1.9.7) to have a representation with Django's ORM of the raw query you posted, exactly as you want; although, you can get the same desired result with something like: >>> Topic.objects.annotate(f=Case(When(record__user=johnny, then=F('record__value')), output_field=IntegerFi...
Rename a worksheet in google Spreadsheet using API - python
I have been trying/looking to solve this problem for a long while. I have read the documentation for gspread and I cannot find that there is a way to rename a worksheet. Any of you know how to? I would massively appreciate it! There is indeed worksheet.title which gives the name of the worksheet, but I cannot find a wa...
This is an extraction of a library which I've coded personally: def _batch(self, requests): body = { 'requests': requests } return self._service.spreadsheets().batchUpdate(spreadsheetId=self.spreadsheetId, body=body).execute() def renameSheet(self, sheetId, newName): return self._batch({ ...
Is there any legitimate use of list[True], list[False] in Python?
Since True and False are instances of int, the following is valid in Python: >>> l = [0, 1, 2] >>> l[False] 0 >>> l[True] 1 I understand why this happens. However, I find this behaviour a bit unexpected and can lead to hard-to-debug bugs. It has certainly bitten me a couple of times. Can anyone think of a legit use of...
In the past, some people have used this behaviour to produce a poor-man's conditional expression: ['foo', 'bar'][eggs > 5] # produces 'bar' when eggs is 6 or higher, 'foo' otherwise However, with a proper conditional expression having been added to the language in Python 2.5, this is very much frowned upon, for the r...
How do I reliably split a string in Python?
In Perl I can do: my ($x, $y) = split /:/, $str; And it will work whether or not the string contains the pattern. In Python, however this won't work: a, b = "foo".split(":") # ValueError: not enough values to unpack What's the canonical way to prevent errors in such cases?
If you're splitting into just two parts (like in your example) you can use str.partition() to get a guaranteed argument unpacking size of 3: >>> a, sep, b = "foo".partition(":") >>> a, sep, b ('foo', '', '') str.partition() always returns a 3-tuple, whether the separator is found or not. Another alternative for Pytho...
What is a good explanation of how to read the histogram feature of TensorBoard?
Question is simple, how do you read those graphs? I read their explanation and it doesn't make sense to me. I was reading TensorFlow's newly updated readme file for TensorBoard and in it it tries to explain what a "histogram" is. First it clarifies that its not really a histogram: Right now, its name is a bit of a mis...
The lines that they are talking about are described below: as for the meaning of percentile, check out the wikipedia article, basically, the 93rd percentile means that 93% of the values are situated below the 93rd percentile line
compare list of datetime to dict of datetime
I have a task to create sets of dates based on specific condition, for example "greater than 2" will be passed and I need to create a set of all dates in this month that have a day > 2. also Ill be getting a start time and a stop time for e.g. 10am-6pm in this case I will create a set of all the dates > 2 and in every ...
It sounds like you're trying to optimize your algorithm. To be honest, with data this size, it's probably not necessary. However, if you are interested, the general rule of thumb is that sets are faster than lists in Python when checking for membership. In this case, it's not clear what your sets might be. I've as...
Digit separators in Python code
Is there any way to group digits in a Python code to increase code legibility? I've tried ' and _ which are digit separators of some other languages, but no avail. A weird operator which concatenates its left hand side with its right hand side could also work out.
This is not implemented in python at the present time. You can look at the lexical analysis for strict definitions python2.7, python3.5 ... Supposedly it will be implemented for python3.6, but it doesn't look like the documentation has been updated for that yet, nor is it available in python3.6.0a2: Python 3.6.0a2 (v3...
Find unique pairs in list of pairs
I have a (large) list of lists of integers, e.g., a = [ [1, 2], [3, 6], [2, 1], [3, 5], [3, 6] ] Most of the pairs will appear twice, where the order of the integers doesn't matter (i.e., [1, 2] is equivalent to [2, 1]). I'd now like to find the pairs that appear only once, and get a Boolean li...
ctr = Counter(frozenset(x) for x in a) b = [ctr[frozenset(x)] == 1 for x in a] We can use Counter to get counts of each list (turn list to frozenset to ignore order) and then for each list check if it only appears once.
Two variables in Python have same id, but not lists or tuples
Two variables in Python have the same id: a = 10 b = 10 a is b >>> True If I take two lists: a = [1, 2, 3] b = [1, 2, 3] a is b >>> False according to this link Senderle answered that immutable object references have the same id and mutable objects like lists have different ids. So now according to his answer, tuples...
Immutable objects don't have the same id, and as a mater of fact this is not true for any type of objects that you define separately. Every time you define an object in Python, you'll create a new object with a new identity. But there are some exceptions for small integers (between -5 and 256) and small strings (intern...
Exception during list comprehension. Are intermediate results kept anywhere?
When using try-except in a for loop context, the commands executed so far are obviously done with a = [1, 2, 3, 'text', 5] b = [] try: for k in range(len(a)): b.append(a[k] + 4) except: print('Error!') print(b) results with Error! [5, 6, 7] However the same is not true for list comprehensions c=[] t...
The list comprehension intermediate results are kept on an internal CPython stack, and are not accessible from the Python expressions that are part of the list comprehension. Note that Python executes the [.....] first, which produces a list object, and only then assigns that result to the name c. If an exception occur...
How to split data into 3 sets (train, validation and test)?
I have a pandas dataframe and I wish to divide it to 3 seprate sets. I know that using train_test_split from sklearn.cross_validation, one can divide the data in two sets (train and test). However, I couldn't find any solution about splitting the data into three sets. Preferably, I'd like to have the indices of the ori...
Numpy solution (thanks to root for the randomizing hint) - we will split our data set into the following parts: (60% - train set, 20% - validation set, 20% - test set): In [305]: train, validate, test = np.split(df.sample(frac=1), [int(.6*len(df)), int(.8*len(df))]) In [306]: train Out[306]: A B ...
Create a list of tuples with adjacent list elements if a condition is true
I am trying to create a list of tuples where the tuple contents are the number 9 and the number before it in the list. Input List: myList = [1, 8, 9, 2, 4, 9, 6, 7, 9, 8] Desired Output: sets = [(8, 9), (4, 9), (7, 9)] Code: sets = [list(zip(myList[i:i], myList[-1:])) for i in myList if i==9] Current Result: [[], ...
Cleaner Pythonic approach: >>> [(x,y) for x,y in zip(myList, myList[1:]) if y == 9] [(8, 9), (4, 9), (7, 9)] What is the code above doing: zip(some_list, some_list[1:]) would generate a list of pairs of adjacent elements. Now with that tuple, filter on the condition that the second element is equal to 9. You're done...
Comparison of Pandas lookup times
After experimenting with timing various types of lookups on a Pandas DataFrame I am left with a few questions. Here is the set up... import pandas as pd import numpy as np import itertools letters = [chr(x) for x in range(ord('a'), ord('z'))] letter_combinations = [''.join(x) for x in itertools.combinations(letters, ...
The disparity in these %timeit results In [273]: %timeit df1[df1['letter'] == 'ben'] 10 loops, best of 3: 36.1 ms per loop In [274]: %timeit df2[df2['letter'] == 'ben'] 10 loops, best of 3: 108 ms per loop also shows up in the pure NumPy equality comparisons: In [275]: %timeit df1['letter'].values == 'ben' 10 loops, ...
Can generators be recursive?
I naively tried to create a recursive generator. Didn't work. This is what I did: def recursive_generator(lis): yield lis[0] recursive_generator(lis[1:]) for k in recursive_generator([6,3,9,1]): print(k) All I got was the first item 6. Is there a way to make such code work? Essentially transferring the ...
Try this: def recursive_generator(lis): yield lis[0] yield from recursive_generator(lis[1:]) for k in recursive_generator([6,3,9,1]): print(k) I should point out this doesn't work because of a bug in your function. It should probably include a check that lis isn't empty, as shown below: def recursive_gene...
Max recursion is not exactly what sys.getrecursionlimit() claims. How come?
I've made a small function that will actually measure the max recursion limit: def f(x): r = x try: r = f(x+1) except Exception as e: print(e) finally: return r To know what to expect I've checked: In [28]: import sys In [29]: sys.getrecursionlimit() Out[29]: 1000 However In [...
The recursion limit is not the limit on recursion but the maximum depth of the python interpreter stack.There is something on the stack before your function gets executed. Spyder executes some python stuff before it calls your script, as do other interpreters like ipython. You can inspect the stack via methods in the i...
Is extending a Python list (e.g. l += [1]) guaranteed to be thread-safe?
If I have an integer i, it is not safe to do i += 1 on multiple threads: >>> i = 0 >>> def increment_i(): ... global i ... for j in range(1000): i += 1 ... >>> threads = [threading.Thread(target=increment_i) for j in range(10)] >>> for thread in threads: thread.start() ... >>> for thread in threads: thread.join...
There isn't a happy ;-) answer to this. There's nothing guaranteed about any of it, which you can confirm simply by noting that the Python reference manual makes no guarantees about atomicity. In CPython it's a matter of pragmatics. As a snipped part of effbot's article says, In theory, this means an exact accountin...
Applications of '~' (tilde) operator in Python
I just discovered the bitwise complement unary operation in Python via this question and have been trying to come up with an actual application for it, and if not, to determine if it's generally safe to overload the operator (by overriding the __invert__ method) for other uses. The example given in the question fails w...
The standard use cases for the bitwise NOT operator are bitwise operations, just like the bitwise AND &, the bitwise OR |, the bitwise XOR ^, and bitwise shifting << and >>. Although they are rarely used in higher level applications, there are still some times where you need to do bitwise manipulations, so that’s why...
Unpack a Python tuple from left to right?
Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right? For example for j = 1,2,3,4,5,6,7 (1,2,3,4,5,6,7) v,b,n = j[4:7] Can I modify the slice notation so that v = j[6], b=j[5], n=j[4] ? I realise I can just order the left side to get the desired element but there might...
This should do: v,b,n = j[6:3:-1] A step value of -1 starting at 6
Why is str.strip() so much faster than str.strip(' ')?
Splitting on white-space can be done in two ways with str.strip. You can either issue a call with no arguments, str.strip(), which defaults to using a white-space delimiter or explicitly supply the argument yourself with str.strip(' '). But, why is it that when timed these functions perform so differently? Using a sam...
In a tl;dr fashion: This is because two functions exist for the two different cases, as can be seen in unicode_strip; do_strip and _PyUnicodeXStrip the first executing much faster than the second. Function do_strip is for the common case str.strip() where no arguments exist and do_argstrip (which wraps _PyUnicode_XSt...
Is there special significance to 16331239353195370.0?
Using import numpy as np I've noticed that np.tan(np.pi/2) gives the number in the title and not np.inf 16331239353195370.0 I'm curious about this number. Is it related to some system machine precision parameter? Could I have calculated it from something? (I'm thinking along the lines of something similar to sys.flo...
pi isn't exactly representable as Python float (same as the platform C's double type). The closest representable approximation is used. Here's the exact approximation in use on my box (probably the same as on your box): >>> import math >>> (math.pi / 2).as_integer_ratio() (884279719003555, 562949953421312) To find th...
Django CSRF cookie not set correctly
Update 7-18: Here is my nginx config for the proxy server: server { listen 80; server_name blah.com; # the blah is intentional access_log /home/cheng/logs/access.log; error_log /home/cheng/logs/error.log; location / { proxy_pass http://127.0.0.1:8001; } locati...
Here is the issue: You cannot have a cookie which key contains either the character '[' or ']' I discovered the solution following @Todor's link, then I found out about this SO post. Basically there was a bug in python 2.7.x that does not parse cookies with ']' in the value. The bug was fixed in 2.7.10. I thought it wo...
Why does '() is ()' return True when '[] is []' and '{} is {}' return False?
From what I've been aware of, using [], {}, () to instantiate objects returns a new instance of list, dict, tuple respectively; a new instance object with a new identity*. This was pretty clear to me until I actually tested it where I noticed that () is () actually returns False instead of the expected True: >>> () is...
In short: Python internally creates a C list of tuple objects whose first element contains the empty tuple. Every time tuple() or () is used, Python will return the existing object contained in the aforementioned C list and not create a new one. Such mechanism does not exist for dict or list objects which are, on the c...
Why does `str.format()` ignore additional/unused arguments?
I saw "Why doesn't join() automatically convert its arguments to strings?" and the accepted answer made me think: since Explicit is better than implicit. and Errors should never pass silently. why does str.format() ignore additional/unused (sometimes accidentally passed) arguments? To me it looks like an error whic...
Ignoring un-used arguments makes it possible to create arbitrary format strings for arbitrary-sized dictionaries or objects. Say you wanted to give your program the feature to let the end-user change the output. You document what fields are available, and tell users to put those fields in {...} slots in a string. The e...
What is the best way to remove accents with apache spark dataframes in PySpark?
I need to delete accents from characters in spanish and others languages from different datasets. I already did a function based in the code provided in this post that removes special the accents. The problem is that the function is slow because it uses an UDF. I'm just wondering if I can improve the performance of m...
One possible improvement is to build a custom Transformer, which will handle Unicode normalization, and corresponding Python wrapper. It should reduce overall overhead of passing data between JVM and Python and doesn't require any modifications in Spark itself or access to private API. On JVM side you'll need a transfo...
Lambdas from a list comprehension are returning a lambda when called
I am trying to iterate the lambda func over a list as in test.py, and I want to get the call result of the lambda, not the function object itself. However, the following output really confused me. ------test.py--------- #!/bin/env python #coding: utf-8 a = [lambda: i for i in range(5)] for i in a: print i() ---...
In Python 2 list comprehension 'leaks' the variables to outer scope: >>> [i for i in xrange(3)] [0, 1, 2] >>> i 2 Note that the behavior is different on Python 3: >>> [i for i in range(3)] [0, 1, 2] >>> i Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'i' is not defined When ...
Simplifying / optimizing a chain of for-loops
I have a chain of for-loops that works on an original list of strings and then gradually filtering the list as it goes down the chain, e.g.: import re # Regex to check that a cap exist in string. pattern1 = re.compile(r'\d.*?[A-Z].*?[a-z]') vocab = ['dog', 'lazy', 'the', 'fly'] # Imagine it's a longer list. def check...
First of all is the overall process that you make on your strings. You are taking some strings and to each of them you apply certain functions. Then you cleanup the list. Let's say for a while that all the functions you apply to strings works at a constant time (it's no true, but for now it won't matter). In your solut...
Python: PEP 8 class name as variable
Which is the convention according to PEP 8 for writing variables that identify class names (not instances)? That is, given two classes, A and B, which of the following statements would be the right one? target_class = A if some_condition else B instance = target_class() or TargetClass = A if some_condition else B inst...
In lack of a specific covering of this case in PEP 8, one can make up an argument for both sides of the medal: One side is: As A and B both are variables as well, but hold a reference to a class, use CamelCase (TargetClass) in this case. Nothing prevents you from doing class A: pass class B: pass x = A A = B B = x Now...
Individual timeouts for concurrent.futures
I see two ways to specify timeouts in concurrent.futures. as_completed() wait() Both methods handle N running futures. I would like to specify an individual timeout for each future. Use Case: Future for getting data from DB has a timeout of 0.5 secs. Future for getting data from a HTTP server has a timeout of 1.2 se...
How about implementing your own: wait(dbfutures + httpfutures, timeout=0.5) [fut.cancel() for fut in bdfutures if not fut.done()] wait(httpfutures, timeout=0.7) [fut.cancel() for fut in httpfutures if not fut.done()] (or a while loop with sleep/check or wait with short timeout)
why is a sum of strings converted to floats
Setup consider the following dataframe (note the strings): df = pd.DataFrame([['3', '11'], ['0', '2']], columns=list('AB')) df df.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 2 entries, 0 to 1 Data columns (total 2 columns): A 2 non-null object B 2 non-null object dtypes: object(2) memory usage: 10...
Went with the good old stack trace. Learned a bit about pdb through Pycharm as well. Turns out what happens is the following: 1) cls.sum = _make_stat_function( 'sum', name, name2, axis_descr, 'Return the sum of the values for the requested axis', nanops.nansum) Let's have a look at...
django-debug-toolbar breaking on admin while getting sql stats
Environment:django debug toolbar breaking while using to get sql stats else it's working fine on the other pages, breaking only on the pages which have sql queries. Request Method: GET Request URL: http://www.blog.local/admin/ Django Version: 1.9.7 Python Version: 2.7.6 Installed Applications: [ .... 'django.contrib...
sqlparse latest version was released today and it's not compatible with django-debug-toolbar version 1.4, Django version 1.9 workaround is force pip to install sqlparse==0.1.19
Why and how are Python functions hashable?
I recently tried the following commands in Python: >>> {lambda x: 1: 'a'} {<function __main__.<lambda>>: 'a'} >>> def p(x): return 1 >>> {p: 'a'} {<function __main__.p>: 'a'} The success of both dict creations indicates that both lambda and regular functions are hashable. (Something like {[]: 'a'} fails with TypeErro...
It's nothing special. As you can see if you examine the unbound __hash__ method of the function type: >>> def f(): pass ... >>> type(f).__hash__ <slot wrapper '__hash__' of 'object' objects> it just inherits __hash__ from object. Function == and hash work by identity. The difference between id and hash is normal for a...
How to assign member variables temporarily?
I often find that I need to assign some member variables temporarily, e.g. old_x = c.x old_y = c.y # keep c.z unchanged c.x = new_x c.y = new_y do_something(c) c.x = old_x c.y = old_y but I wish I could simply write with c.x = new_x; c.y = new_y: do_something(c) or even do_something(c with x = new_x; y = new_y...
Context managers may be used for it easily. Quoting official docs: Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc. It seems like saving and restoring state is exactly what we want to do here. Example: from con...
Pycharm import RuntimeWarning after updating to 2016.2
After updating to new version 2016.2, I am getting RuntimeWarning: Parent module 'tests' not found while handling absolute import import unittest RuntimeWarning: Parent module 'tests' not found while handling absolute import import datetime as dt 'tests' is a package inside my main app package, and I receive these...
This is a known issue with the 2016.2 release. Progress can be followed on the JetBrains website here. According to this page it's due to be fixed in the 2016.3 release but you can follow the utrunner.py workaround that others have mentioned in the meantime (I downloaded the 2016.1 release and copied the file over from...
rounding errors in Python floor division
I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one: >>> 8.0 / 0.4 # as expected 20.0 >>> floor(8.0 / 0.4) # int works too 20 >>> 8.0 // 0.4 # expecting 20.0 19.0 This happens on both Python 2 and 3 on x64. As far as I see it this is either a bug or a very dum...
As you and khelwood already noticed, 0.4 cannot be exactly represented as a float. Why? It is two fifth (4/10 == 2/5) which does not have a finite binary fraction representation. Try this: from fractions import Fraction Fraction('8.0') // Fraction('0.4') # or equivalently # Fraction(8, 1) // Fraction(2, 5) ...
Convert Python sequence to NumPy array, filling missing values
The implicit conversion of a Python sequence of variable-length lists into a NumPy array cause the array to be of type object. v = [[1], [1, 2]] np.array(v) >>> array([[1], [1, 2]], dtype=object) Trying to force another type will cause an exception: np.array(v, dtype=np.int32) ValueError: setting an array element with...
Pandas and its DataFrame-s deal beautifully with missing data. import numpy as np import pandas as pd v = [[1], [1, 2]] print(pd.DataFrame(v).fillna(0).values.astype(np.int32)) # array([[1, 0], # [1, 2]], dtype=int32)
IPython 5.0 and key bindings in console
The new release of IPython does not depend any more on readline but uses the pure Python library prompt-toolkit, solving maintenance problems on Apple's and Windows' systems. A new feature is the ability to edit a multi-line code block, using the cursor keys to move freely in the code block — with this power it comes...
You could change xterm's configuration. xterm is configurable (and documented). In the xterm manual, the Default Key Bindings section shows the default binding for this key: Alt <Key>Return:fullscreen() \n\ You can suppress that binding in more than one way: using the omitTranslation resource...
A surprise with 1**math.nan and 0j**math.nan
I'm surprised that >>> import math >>> 1**math.nan 1.0 And while we are at it, also that >>> 0j**math.nan 0j I didn't find any other examples. Is there a reason or some logic I've missed that makes this the right choice? Or is this a slip? I was expecting nan. As for every other number except 1 or 0j. Edit 1: Thank...
Quoting this question which in turns quotes IEEE 754 (see Wikipedia), The 2008 version of the IEEE 754 standard says that pow(1,qNaN) and pow(qNaN,0) should both return 1 since they return 1 whatever else is used instead of quiet NaN. For details see page 56 of IEEE 754 2008: pow(x, ±0) is 1 for any x (even a zero,...