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
Python: Every possible letter combination
31,914,097
3
2015-08-10T07:42:04Z
31,914,167
9
2015-08-10T07:45:47Z
[ "python" ]
What's the most efficient way at producing every possible letter combination of the alphabet? E.g. a,b,c,d,e...z,aa,ab,ac,ad,ae... ect I've written a code that successfully produces this result but I feel like it's too inefficient at producing the desired result. Any ideas? I've also tried to explain what i've done...
Use [`itertools.product()`](https://docs.python.org/2/library/itertools.html#itertools.product) to create combinations of letters: ``` from string import ascii_lowercase from itertools import product for length in range(minimum_length, maximum_length + 1): for combo in product(ascii_lowercase, repeat=length): ...
Practical use of tuple as a singleton
31,915,428
4
2015-08-10T08:58:43Z
31,915,562
7
2015-08-10T09:05:05Z
[ "python", "tuples" ]
In the documentation on [data models](https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy) it mentions the possibility to use a single item tuple as a singleton, due to it's immutability. > **Tuples** > > A tuple of one item (a ‘singleton’) can be formed by affixing a comma > to an expre...
I don't think this is useful for implementing singletons at all, it doesn't add anything: the tuple can still be overwritten by a new single-element tuple. Anyway, in your example your value is a string, which is already immutable itself. But I think the line of documentation you refer to ("A tuple of one item (a ‘s...
Concatenate two lists side by side
31,915,812
3
2015-08-10T09:17:06Z
31,915,845
8
2015-08-10T09:18:44Z
[ "python", "list" ]
I am looking for the shortest way of doing the following (one line solution) ``` a = ["a", "b", "c"] b = ["w", "e", "r"] ``` I want the following output: ``` q = ["a w", "b e", "c r"] ``` Of course this can be achieved by applying a for loop. But I am wondering if there is a smart solution to this?
You can use `str.join()` and [`zip()`](https://docs.python.org/2/library/functions.html#zip) , Example - ``` q = [' '.join(x) for x in zip(a,b)] ``` Example/Demo - ``` >>> a = ["a", "b", "c"] >>> b = ["w", "e", "r"] >>> q = [' '.join(x) for x in zip(a,b)] >>> q ['a w', 'b e', 'c r'] ```
Can someone explain how the source code of staticmethod works in python
31,916,048
9
2015-08-10T09:28:36Z
31,916,107
9
2015-08-10T09:31:37Z
[ "python", "decorator", "static-methods", "python-internals" ]
First of all, I understand how, in general, a decorator work. And I know `@staticmethod` strips off the instance argument in the signature, making ``` class C(object): @staticmethod def foo(): print 'foo' C.foo //<function foo at 0x10efd4050> C().foo //<function foo at 0x10efd4050> ``` valid. How...
A `staticmethod` object is a [*descriptor*](https://docs.python.org/2/howto/descriptor.html). The magic you are missing is that Python calls the `__get__` method when accessing the object as an attribute on a class or instance. So accessing the object as `C.foo` results in Python translating that to `C.__dict__['foo']...
How do you translate strings to padded binary in python?
31,917,211
4
2015-08-10T10:28:34Z
31,917,271
12
2015-08-10T10:31:26Z
[ "python" ]
I have made a program that translates a text into binary code but its really messy. This is my code: ``` def converter(): print("message:") inputMsg = input() msg = '' for letter in inputMsg: if letter == 'a': msg = msg + '01100001' elif letter == 'b': msg = msg ...
``` >>> st = "hello" >>> ' '.join(format(ord(x), '08b') for x in st) '01101000 01100101 01101100 01101100 01101111 ``` What happens here is that we loop over every character, `x`, in string `st`. On each of those items we run [`ord()`](https://docs.python.org/2/library/functions.html#ord), which converts the character...
Why is string's startswith slower than in?
31,917,372
48
2015-08-10T10:35:51Z
31,917,646
35
2015-08-10T10:52:10Z
[ "python", "python-2.7", "cpython", "python-internals", "startswith" ]
Surprisingly, I find `startswith` is slower than `in`: ``` In [10]: s="ABCD"*10 In [11]: %timeit s.startswith("XYZ") 1000000 loops, best of 3: 307 ns per loop In [12]: %timeit "XYZ" in s 10000000 loops, best of 3: 81.7 ns per loop ``` As we all know, the `in` operation needs to search the whole string and `startswi...
As already mentioned in the comments, if you use `s.__contains__("XYZ")` you get a result that is more similar to `s.startswith("XYZ")` because it needs to take the same route: Member lookup on the string object, followed by a function call. This is usually somewhat expensive (not enough that you should worry about of ...
Boto3 to download all files from a S3 Bucket
31,918,960
12
2015-08-10T11:58:16Z
31,929,277
14
2015-08-10T21:13:18Z
[ "python", "amazon-s3", "boto3" ]
I'm using boto3 to get files from s3 bucket. I need a similar functionality like `aws s3 sync` My current code is ``` #!/usr/bin/python import boto3 s3=boto3.client('s3') list=s3.list_objects(Bucket='my_bucket_name')['Contents'] for key in list: s3.download_file('my_bucket_name', key['Key'], key['Key']) ``` This...
Amazon S3 does not have folders/directories. It is a **flat file structure**. To maintain the appearance of directories, **path names are stored as part of the object Key** (filename). For example: * `images/foo.jpg` In this case, they whole Key is `images/foo.jpg`, rather than just `foo.jpg`. I suspect that your p...
Boto3 to download all files from a S3 Bucket
31,918,960
12
2015-08-10T11:58:16Z
33,350,380
18
2015-10-26T16:06:54Z
[ "python", "amazon-s3", "boto3" ]
I'm using boto3 to get files from s3 bucket. I need a similar functionality like `aws s3 sync` My current code is ``` #!/usr/bin/python import boto3 s3=boto3.client('s3') list=s3.list_objects(Bucket='my_bucket_name')['Contents'] for key in list: s3.download_file('my_bucket_name', key['Key'], key['Key']) ``` This...
I got the same needs and create the following function that download recursively the files. The directories are created locally only if they contain files. ``` import boto3 import os def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'): paginator = client.get_paginator('list_objects') ...
Sum up over np.array or np.float
31,921,290
5
2015-08-10T13:47:15Z
31,921,406
9
2015-08-10T13:52:23Z
[ "python", "arrays", "numpy", "types" ]
We have a numpy-based algorithm that is supposed to handle data of different type. ``` def my_fancy_algo(a): b = np.sum(a, axis=1) # Do something b return b ``` If we pass `a=np.array[1.0, 2.0, 3.0]` then `b` evaluates to `[6.0]`. If we pass `a=6.0` then we get ``` *** ValueError: 'axis' entry is out of...
Your example array actually gives the same problem as a scalar: ``` >>> a = np.array([1.0,2.0,3.0]) >>> np.sum(a, axis=1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/numpy/core/fromnumeric.py", line 1724, in sum out=out, keepdims=keepdims) Fil...
Creating a live plot of CSV data with Matplotlib
31,922,016
2
2015-08-10T14:18:38Z
31,943,177
7
2015-08-11T13:29:22Z
[ "python", "csv", "python-3.x", "matplotlib" ]
I am trying to use Matplotlib to visualize some measurements. The measurements typically last about 24hrs and will include ~30k lines of data in the csv. I've been struggling mostly with getting my plots to actually animate. I can execute the code and it will display a snapshot up to the current point in time but nothi...
You have two issues. One is because you're effectively drawing things twice, the second is purely human psychology (the plot appears to slow over time because you're adding one point to 10000 vs adding one point to 10 or 100). --- Let's discuss the double-draw first: The `FuncAnimation` will draw things for you, but...
How to convert dictionary values to int in Python?
31,923,552
12
2015-08-10T15:30:34Z
31,923,593
19
2015-08-10T15:32:24Z
[ "python", "sorting", "dictionary" ]
I have a program that returns a set of domains with ranks like so: ``` ranks = [ {'url': 'example.com', 'rank': '11,279'}, {'url': 'facebook.com', 'rank': '2'}, {'url': 'google.com', 'rank': '1'} ] ``` I'm trying to sort them by ascending rank with `sorted`: ``` results = sorted(ranks,key=itemgetter("ran...
You are almost there. You need to convert the picked values to integers after replacing `,`, like this ``` results = sorted(ranks, key=lambda x: int(x["rank"].replace(",", ""))) ``` For example, ``` >>> ranks = [ ... {'url': 'example.com', 'rank': '11,279'}, ... {'url': 'facebook.com', 'rank': '2'}, ... ...
Importance of apps orders in INSTALLED_APPS
31,925,458
7
2015-08-10T17:16:52Z
31,925,587
8
2015-08-10T17:24:08Z
[ "python", "django" ]
Is the order of apps in `INSTALLED_APPS` is important? I ask it because I have `settings` folder with two `settings` files: `base.py` and `production.py` and I put all my settings in `base.py` and then in `production.py` write ``` `from base import *` ``` and overwrite some settings. Also in my `base.py` I make `INS...
**Yes, the order is quite important.** From Django official docs on [`INSTALLED_APPS` settings](https://docs.djangoproject.com/en/1.8/ref/settings/#installed-apps): > When several applications provide different versions of the same > resource (template, static file, management command, translation), the > application...
Python Check if String split succeeded
31,925,964
5
2015-08-10T17:49:19Z
31,926,007
7
2015-08-10T17:51:39Z
[ "python", "string" ]
I am splitting a string `"name:john"` and want to check whether the split happened or not. What is the right way doing that check? **A quick solution:** (but maybe overkill) ``` name = "name:john" splitted = name.split(":") if len(splitted) > 1: print "split" ``` Is there a more elaborate way of doing the check?
You can also choose the [EAFP](https://docs.python.org/2/glossary.html#term-eafp) approach: split, unpack and handle `ValueError`: ``` try: key, value = name.split(":") except ValueError: print "Failure" else: print "Success" ```
next_is_valid() doesn't exist in flask-login?
31,927,227
10
2015-08-10T19:06:32Z
31,967,035
8
2015-08-12T13:44:07Z
[ "python", "flask", "flask-login" ]
[Flask-login doc](https://flask-login.readthedocs.org/en/latest/) says we should validate next using `next_is_valid()`, but I can't find any such method: > Warning: You MUST validate the value of the next parameter. If you do not, your application will be vulnerable to open redirects. ``` @app.route('/login', methods...
It doesn't say you must validate `next` with `next_is_valid`, only that > You MUST validate the value of the next parameter. **`next_is_valid` is just an example function.** You must determine if `next` is valid based on your own criteria. `next` is the url to redirect to on a successful login. If you have any permi...
How to get a list of all indexes in python-elasticsearch
31,928,506
3
2015-08-10T20:26:17Z
31,928,663
8
2015-08-10T20:36:04Z
[ "python", "elasticsearch" ]
How would I get a list of the names of an index in Python? Here is what I have so far: ``` >>> es=e.es >>> es <Elasticsearch([{'host': '14555f777d8097.us-east-1.aws.found.io', 'port': 9200}])> >>> es.indices <elasticsearch.client.indices.IndicesClient object at 0x10de86790> # how to get a list of all indexes in this c...
Here is one way to do it with the [`get_aliases()`](https://elasticsearch-py.readthedocs.org/en/master/api.html?highlight=indicesclient#elasticsearch.client.IndicesClient.get_alias) method: ``` >>> indices=es.indices.get_aliases().keys() >>> sorted(indices) [u'avails', u'hey', u'kibana-int'] ```
How to install Rodeo IDE in Anaconda python distribution?
31,935,714
6
2015-08-11T07:28:59Z
37,713,789
7
2016-06-08T22:09:12Z
[ "python", "python-3.x", "ipython", "anaconda", "rodeo" ]
I have a 64bit anaconda python distribution version 2.3 with python 3.4.3 installed on windows 7 machine. I searched about installing rodeo on top of this but seems like "conda install rodeo" wont work, so i did "pip install rodeo". ``` "pip install rodeo" gave me the following message "Successfully installed rodeo". ...
# Updated Answer (as of 2016-6-8) Rodeo has been undergoing a significant re-write since the latest major release, **v1.3** which is the [currently downloadable version](https://www.yhat.com/products/rodeo) on yhat's website. I recommend checking out the latest release, **v2.0**, downloadable from the [Rodeo project ...
Plot a (polar) color wheel based on a colormap using Python/Matplotlib
31,940,285
11
2015-08-11T11:14:45Z
31,942,626
11
2015-08-11T13:04:55Z
[ "python", "matplotlib", "plot", "colors", "scipy" ]
I am trying to create a color wheel in Python, preferably using Matplotlib. The following works OK: ``` import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt xval = np.arange(0, 2*pi, 0.01) yval = np.ones_like(xval) colormap = plt.get_cmap('hsv') norm = mpl.colors.Normalize(0.0, 2*np.pi) ax = ...
One way I have found is to produce a colormap and then project it onto a polar axis. Here is a working example - it includes a nasty hack, though (clearly commented). I'm sure there's a way to either adjust limits or (harder) write your own `Transform` to get around it, but I haven't quite managed that yet. I thought t...
Python: why the code for swapping the largest and the smallest numbers isn't working?
31,943,047
2
2015-08-11T13:24:52Z
31,943,643
7
2015-08-11T13:50:03Z
[ "python", "list" ]
Imagine we have a list of numbers `a` where all numbers are different, and we want to swap the largest one and the smallest one. The question is, why this code in Python: ``` a[a.index(min(a))], a[a.index(max(a))] = a[a.index(max(a))], a[a.index(min(a))] ``` isn't working?
Why does it fail? Let's take `a = [1, 2, 3, 4]` as example. First, the right side is evaluated: ``` a[a.index(max(a))], a[a.index(min(a))] => 4, 1 ``` That's btw of course the same as ``` max(a), min(a) => 4, 1 ``` Next, the assignments happen, [from left to right](https://docs.python.org/3.5/reference...
Localhost Endpoint to DynamoDB Local with Boto3
31,948,742
12
2015-08-11T17:56:46Z
32,260,680
13
2015-08-27T22:53:32Z
[ "python", "amazon-dynamodb", "dynamo-local" ]
Although Amazon provides documentation regarding how to connect to [dynamoDB local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html) with Java, PHP and .Net, there is no description of how to connect to localhost:8000 using Python. Existing documentation on the web points to th...
It does support DynamoDB Local. You just need to set the appropriate endpoint such as you can do with other [language SDKs](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html#Tools.DynamoDBLocal.Using) Here is a code snippet of how you can use boto3's client and resource interfac...
Localhost Endpoint to DynamoDB Local with Boto3
31,948,742
12
2015-08-11T17:56:46Z
34,530,320
7
2015-12-30T13:16:44Z
[ "python", "amazon-dynamodb", "dynamo-local" ]
Although Amazon provides documentation regarding how to connect to [dynamoDB local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html) with Java, PHP and .Net, there is no description of how to connect to localhost:8000 using Python. Existing documentation on the web points to th...
Note: You will want to extend the above response to include region. I have appended to Kyle's code above. If your initial attempt is greeted with a region error, this will return the appropriate '[]' response. ``` import boto3 ## For a Boto3 client ('client' is for low-level access to Dynamo service API) ddb1 = boto3...
How to limit python traceback to specific files
31,949,760
26
2015-08-11T18:52:37Z
32,999,522
12
2015-10-07T18:13:05Z
[ "python", "debugging", "traceback" ]
I write a lot of Python code that uses external libraries. Frequently I will write a bug, and when I run the code I get a big long traceback in the Python console. 99.999999% of the time it's due to a coding error in my code, not because of a bug in the package. But the traceback goes all the way to the line of error i...
In order to print your own stacktrace, you would need to handle all unhandled exceptions yourself; this is how the [`sys.excepthook`](https://docs.python.org/2/library/sys.html#sys.excepthook) becomes handy. The signature for this function is `sys.excepthook(type, value, traceback)` and its job is: > This function pr...
Two word boundaries (\b) to isolate a single word
31,950,532
2
2015-08-11T19:41:17Z
31,950,573
8
2015-08-11T19:43:29Z
[ "python", "regex" ]
I am trying to match the word that appears immediately after a number - in the sentence below, it is the word "meters". > The tower is 100 **meters** tall. Here's the pattern that I tried which didn't work: ## **`\d+\s*(\b.+\b)`** But this one did: ## **`\d+\s*(\w+)`** The first incorrect pattern matched this: >...
It didn't stop because `+` is [**greedy**](http://www.rexegg.com/regex-quantifiers.html#greedytrap) by default, you want `+?` for a non-greedy match. A concise explanation — `*` and `+` are greedy quantifiers/operators meaning they will match as much as they can and still allow the remainder of the regular expression ...
Start IPython notebook server without running web browser?
31,953,518
11
2015-08-11T23:11:25Z
31,953,548
13
2015-08-11T23:14:43Z
[ "python", "ipython" ]
I would like to use Emacs as main editor for ipython notebooks (with package [ein](http://tkf.github.io/emacs-ipython-notebook/#install)). I want to ask you if there is a way to run the server without the need to open a web browser.
Is this what you want? ``` $ ipython notebook --no-browser ```
Counting tuples in a list, no matter the order of each element within the tuples
31,953,807
3
2015-08-11T23:45:41Z
31,953,834
7
2015-08-11T23:48:59Z
[ "python", "list", "collections", "counter" ]
I have a question about counting occurrences within a list in Python. Here's the list: ``` aList = [(11, 0), (9, 7), (23, 9), (25, 3), (9, 9), (21, 2), (10, 9), (14, 14), (8, 13), (14, 9), (11, 4), (1, 14), (3, 9), (3, 1), (11, 9), (9, 1), (7, 0), (9, 3), (9, 3), (16, 11), (9, 7), (9, 13), (11, 9), (26, 18), (18, 9),...
This should do it: ``` counter = Counter(tuple(sorted(tup)) for tup in your_list) print counter ```
Add column sum as new column in PySpark dataframe
31,955,309
5
2015-08-12T02:59:12Z
31,955,747
10
2015-08-12T03:55:56Z
[ "python", "apache-spark", "pyspark", "spark-dataframe" ]
I'm using PySpark and I have a Spark dataframe with a bunch of numeric columns. I want to add a column that is the sum of all the other columns. Suppose my dataframe had columns "a", "b", and "c". I know I can do this: ``` df.withColumn('total_col', df.a + df.b + df.c) ``` The problem is that I don't want to type ou...
This was not obvious. I see no row-based sum of the columns defined in the spark Dataframes API. # Version 2 This can be done in a fairly simple way: ``` newdf = df.withColumn('total', sum(df[col] for col in df.columns)) ``` `df.columns` is supplied by pyspark as a list of strings giving all of the column names in ...
Numpy elementwise product of 3d array
31,957,364
6
2015-08-12T06:17:54Z
31,958,728
7
2015-08-12T07:30:09Z
[ "python", "arrays", "numpy", "matrix", "vectorization" ]
I have two 3d arrays A and B with shape (N, 2, 2) that I would like to multiply element-wise according to the N-axis with a matrix product on each of the 2x2 matrix. With a loop implementation, it looks like ``` C[i] = dot(A[i], B[i]) ``` Is there a way I could do this without using a loop? I've looked into tensordot...
It seems you are doing matrix-multiplications for each slice along the first axis. For the same, you can use [`np.einsum`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html) like so - ``` np.einsum('ijk,ikl->ijl',A,B) ``` Runtime tests and verify results - ``` In [179]: N = 10000 ...: A = np...
How to understand expression lists in Python
31,958,341
8
2015-08-12T07:11:30Z
31,958,494
7
2015-08-12T07:18:56Z
[ "python", "list" ]
When I read the Python document today, I found `Expression lists` on [Python Documents](https://docs.python.org/3/reference/expressions.html#expression-lists), the description on the site like this: > `expression_list ::= expression ( "," expression )* [","]` > > *An expression list containing at least one comma yield...
Here are some samples to help you understand what is going on: > An expression list containing at least one comma yields a tuple. This means, that if you have `1,2`, this will create a tuple. The length is how many items you have. > The trailing comma is required only to create a single tuple (a.k.a. a > singleton);...
Python string formatting with percent sign
31,964,930
14
2015-08-12T12:14:25Z
31,964,966
16
2015-08-12T12:16:09Z
[ "python", "string", "python-3.x" ]
I am trying to do exactly the following: ``` >>> x = (1,2) >>> y = 'hello' >>> '%d,%d,%s' % (x[0], x[1], y) '1,2,hello' ``` However, I have a long `x`, more than two items, so I tried: ``` >>> '%d,%d,%s' % (*x, y) ``` but it is syntax error. What would be the proper way of doing this without indexing like the first...
`str % ..` accepts a tuple as a right-hand operand, so you can do the following: ``` >>> x = (1, 2) >>> y = 'hello' >>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')` '1,2,hello' ``` Your try should work in Python 3. where [`Additional Unpacking Generalizations`](https://www.python.org/dev/peps/pep-...
Python string formatting with percent sign
31,964,930
14
2015-08-12T12:14:25Z
31,964,980
10
2015-08-12T12:17:00Z
[ "python", "string", "python-3.x" ]
I am trying to do exactly the following: ``` >>> x = (1,2) >>> y = 'hello' >>> '%d,%d,%s' % (x[0], x[1], y) '1,2,hello' ``` However, I have a long `x`, more than two items, so I tried: ``` >>> '%d,%d,%s' % (*x, y) ``` but it is syntax error. What would be the proper way of doing this without indexing like the first...
Perhaps have a look at [str.format()](https://docs.python.org/2/library/stdtypes.html#str.format). ``` >>> x = (5,7) >>> template = 'first: {}, second: {}' >>> template.format(*x) 'first: 5, second: 7' ``` ## Update: For completeness I am also including *additional unpacking generalizations* described by [PEP 448](h...
what is the difference between x.type and type(x) in Python?
31,966,126
3
2015-08-12T13:04:37Z
31,966,200
8
2015-08-12T13:07:51Z
[ "python", "theano" ]
Consider the following lines ``` import theano.tensor as T x = T.dscalar('x') y = T.dscalar('y') z = x+y ``` And then, ``` In [15]: type(x) Out[15]: theano.tensor.var.TensorVariable ``` while, ``` In [16]: x.type Out[16]: TensorType(float64, scalar) ``` Why type(x) and x.type give two different pieces of inform...
`type(x)` is a builtin. `x.type` is an attribute that's defined in your object. They are completely seperate, `type(x)` returns what type of object `x` is and `x.type` does whatever the object wants it to. In this case, it returns some information on the type of object it is
IPython notebook won't read the configuration file
31,974,797
11
2015-08-12T20:30:24Z
31,982,416
22
2015-08-13T07:47:41Z
[ "python", "ipython", "ipython-notebook", "jupyter" ]
I used the following command to initialize a profile: ``` ipython profile create myserver ``` Added thses lines to `~/.ipython/profile_myserver/ipython_notebook_config.py`: ``` c = get_config() c.NotebookApp.ip = '*' c.NotebookApp.port = 8889 ``` Tried starting the notebook with: ``` ipython notebook --profile=mys...
IPython has now moved to **[version 4.0](http://blog.jupyter.org/2015/08/12/first-release-of-jupyter/)**, which means that if you are using it, it will be reading its configuration from `~/.jupyter`, not `~/.ipython`. You have to create a new configuration file with ``` jupyter notebook --generate-config ``` and then...
Detecting lines and shapes in OpenCV using Python
31,974,843
8
2015-08-12T20:32:51Z
32,077,775
9
2015-08-18T16:25:58Z
[ "python", "opencv", "image-processing" ]
I've been playing around with OpenCV (cv2) and detecting lines and shapes. Say that my daughter drew a drawing, like so: [![enter image description here](http://i.stack.imgur.com/3jiNT.png)](http://i.stack.imgur.com/3jiNT.png) I am trying to write a Python script that would analyze the drawing and convert it into har...
Here is my attempt. It's in C++, but can be easily ported to python since most are OpenCV functions. A brief outline of the method, comments in the code should help, too. 1. Load the image 2. Convert to grayscale 3. Binaryze the image (threshold) 4. Thinning, to have thin contours and help `findContours` 5. Get conto...
Open S3 object as a string with Boto3
31,976,273
21
2015-08-12T22:10:33Z
31,976,895
29
2015-08-12T23:07:10Z
[ "python", "amazon-s3", "boto", "boto3" ]
I'm aware that with Boto 2 it's possible to open an S3 object as a string with: get\_contents\_as\_string() <http://boto.readthedocs.org/en/latest/ref/file.html?highlight=contents%20string#boto.file.key.Key.get_contents_as_string> Is there an equivalent function in boto3 ?
This isn't in the boto3 documentation. This worked for me: ``` object.get()["Body"].read() ``` object being an s3 object: <http://boto3.readthedocs.org/en/latest/reference/services/s3.html#object>
Open S3 object as a string with Boto3
31,976,273
21
2015-08-12T22:10:33Z
35,376,156
12
2016-02-13T04:41:11Z
[ "python", "amazon-s3", "boto", "boto3" ]
I'm aware that with Boto 2 it's possible to open an S3 object as a string with: get\_contents\_as\_string() <http://boto.readthedocs.org/en/latest/ref/file.html?highlight=contents%20string#boto.file.key.Key.get_contents_as_string> Is there an equivalent function in boto3 ?
`read` will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding: ``` import boto3 s3 = boto3.resource('s3') obj = s3.Object(bucket, key) obj.get()['Body'].read().decode('utf-8') ```
Is there a more pythonic way to populate a this list?
31,981,563
4
2015-08-13T07:01:57Z
31,981,585
8
2015-08-13T07:03:11Z
[ "python", "list" ]
I want to clean the strings from a django query so it can be used in latex ``` items = [] items_to_clean = items.objects.get.all().values() for dic in items_to_clean: items.append(dicttolatex(dic)) ``` This is my standard aproach to this task. Can this somehow be solved whith list comprehension. since `dicttolate...
You can avoid repeated calls to `append` by using a list comprehension: ``` items = [dicttolatex(dic) for dic in items_to_clean] ```
Specifying exact Python version for Travis CI in combination with tox
31,985,877
4
2015-08-13T10:39:12Z
31,990,486
7
2015-08-13T14:04:47Z
[ "python", "travis-ci", "tox" ]
I have the following .travis.yml: ``` language: python env: - TOXENV=py27 - TOXENV=py34 install: - pip install -U tox script: - tox ``` and the following tox.ini: ``` [tox] envlist = py27,py34 [testenv] commands = py.test tests/ deps = -rtests/test_requirements.txt ``` I need Python 3.4.3, which is [ava...
Inspired by `pip`'s [.travis.yml](https://github.com/pypa/pip/blob/166f3d20e27f06c1ca74d30ec6ceed688f295b47/.travis.yml) it seems easiest to specify the Travis matrix with different environment variables: ``` matrix: include: - python: 3.4.3 env: TOXENV=py34 - python: 2.7 env: T...
Put multiple items in a python queue
31,987,207
2
2015-08-13T11:41:11Z
31,987,220
7
2015-08-13T11:41:50Z
[ "python", "queue" ]
Suppose you have an iterable `items` containing items that should be put in a queue `q`. Of course you can do it like this: ``` for i in items: q.put(i) ``` But it feels unnecessary to write this in two lines - is that supposed to be pythonic? Is there no way to do something more readable - i.e. like this ``` q....
Using the built-in `map` function : ``` map(q.put, items) ``` It will apply `q.put` to all your items in your list. Useful one-liner. --- For Python 3, you can use it as following : ``` list(map(q.put, items)) ``` Or also : ``` from collections import deque deque(map(q.put, items)) ``` But at this point, the `f...
numpy array, difference between a /= x vs. a = a / x
31,987,713
19
2015-08-13T12:03:48Z
31,987,859
29
2015-08-13T12:10:20Z
[ "python", "arrays", "numpy", "integer-division", "in-place" ]
I'm using python 2.7.3, when I execute the following piece of code: ``` import numpy as np a = np.array([[1,2,3],[4,5,6]]) a = a / float(2**16 - 1) print a ``` This will result in he following output: ``` >> array([[1.52590219e-05, 3.05180438e-05, 4.57770657e-05], >> [6.10360876e-05, 7.62951095e-05, 9.1554131...
[From the documentation:](http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#arithmetic-and-comparison-operations) > **Warning:** > > In place operations will perform the calculation using the precision decided by the data type of the two operands, but will silently downcast the result (if necessary) so it ...
Better way to parse and search a string?
31,992,222
4
2015-08-13T15:14:14Z
31,999,847
8
2015-08-13T23:06:38Z
[ "python", "rust" ]
I have been looking to speed up a basic Python function which basically just takes a line of text and checks the line for a substring. The Python program is as follows: ``` import time def fun(line): l = line.split(" ", 10) if 'TTAGGG' in l[9]: pass # Do nothing line = "FCC2CCMACXX:4:1105:10758:1438...
As a baseline, I ran your Python program with Python 2.7.6. Over 10 runs, it had a mean time of 12.2ms with a standard deviation of 443μs. I don't know how you got the very good time of **6.5ms**. Running your Rust code with Rust 1.4.0-dev (`febdc3b20`), without optimizations, I got a mean of 958ms and a standard dev...
Why can't Python see environment variables?
31,993,885
2
2015-08-13T16:38:26Z
31,993,903
11
2015-08-13T16:39:09Z
[ "python", "bash", "environment-variables" ]
I'm working on Debian Jessie with Python 2. Why can't Python's `environ` see environment variables that are visible in bash? ``` # echo $SECRET_KEY xxx-xxx-xxxx # python >>> from os import environ >>> environ["SECRET_KEY"] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/root/.virtuale...
You need to *export* environment variables for child processes to see them: ``` export SECRET_KEY ``` Demo: ``` $ SECRET_KEY='foobar' $ bin/python -c "import os; print os.environ.get('SECRET_KEY', 'Nonesuch')" Nonesuch $ export SECRET_KEY $ bin/python -c "import os; print os.environ.get('SECRET_KEY', 'Nonesuch')" fo...
WebAssembly, JavaScript, and other languages
31,994,034
10
2015-08-13T16:45:38Z
31,994,562
10
2015-08-13T17:13:21Z
[ "javascript", "c#", "python", "webassembly" ]
With the advent of the New Era of the Web, WebAssembly, which is to be designed in cooperation by Google, Microsoft, Apple, and Mozilla: > **WebAssembly High-Level Goals** > > 1. Define a portable, size- and load-time-efficient binary format to serve as a compilation target which can be compiled to execute at native s...
The goal is indeed to support any language, but supporting any language is difficult to pull off without huge delays. WebAssembly is currently focusing on languages that are traditionally compiled ahead-of-time, work well with on linear memory heap, and which don't require dynamic recompilation, runtime code loading, ...
Python 3: How can object be instance of type?
31,995,472
9
2015-08-13T18:07:49Z
31,995,548
15
2015-08-13T18:12:41Z
[ "python", "python-3.x", "python-3.4" ]
In Python 3, `object` is an instance of `type` and `type` is also an instance of `object`! How is it possible that each class is derived from the other? Any implementation details? I checked this using `isinstance(sub, base)`, which, according to Python documentation, checks if sub class is derived from base class: ...
This is one of the edge cases in Python: * Everything in Python is an object, so since `object` is the base type of everything, `type` (being something in Python) is an instance of `object`. * Since `object` is the base *type* of everything, `object` is also a *type*, which makes `object` an instance of `type`. Note ...
Plotting oceans in maps using basemap and python
31,996,071
4
2015-08-13T18:42:57Z
32,120,065
7
2015-08-20T13:47:52Z
[ "python", "plot", "matplotlib-basemap" ]
I am plotting the netCDF file available here: <https://goo.gl/QyUI4J> Using the code below, the map looks like this: [![enter image description here](http://i.stack.imgur.com/VVt0y.png)](http://i.stack.imgur.com/VVt0y.png) However, I want the oceans to be in white color. Better still, I want to be able to specify wha...
You need to use [`maskoceans`](http://matplotlib.org/basemap/api/basemap_api.html#mpl_toolkits.basemap.maskoceans) on your `nc_vars` dataset Before `contourf`, insert this ``` nc_new = maskoceans(lons,lats,nc_vars[len(tmax)-1,:,:]) ``` and then call `contourf` with the newly masked dataset i.e. ``` cs = m.contourf(...
Why does python allow spaces between an object and the method name after the "."
31,996,132
2
2015-08-13T18:46:00Z
31,996,173
7
2015-08-13T18:48:35Z
[ "python", "python-2.7" ]
Does anyone know why python allows you to put an unlimited amount of spaces between an object and the name of the method being called the "." ? Here are some examples: ``` >>> x = [] >>> x. insert(0, 'hi') >>> print x ['hi'] ``` Another example: ``` >>> d = {} >>> d ['hi'] = 'there' >>> pr...
The `.` acts like an operator. You can do `obj . attr` the same way you can do `this + that` or `this * that` or the like. The [language reference](https://docs.python.org/2/reference/lexical_analysis.html#whitespace-between-tokens) says: > Except at the beginning of a logical line or in string literals, the whitespac...
Python: keras shape mismatch error
31,997,366
3
2015-08-13T20:00:30Z
32,938,020
10
2015-10-04T20:26:27Z
[ "python", "keras" ]
I am trying to build a very simple multilayer perceptron (MLP) in `keras`: ``` model = Sequential() model.add(Dense(16, 8, init='uniform', activation='tanh')) model.add(Dropout(0.5)) model.add(Dense(8, 2, init='uniform', activation='tanh')) sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(los...
I had the same problem and then found this thread; <https://github.com/fchollet/keras/issues/68> It appears for you to state a final output layer of 2 or for any number of categories the labels need to be of a categorical type where essentially this is a binary vector for each observation e.g a 3 class output vector ...
Python 2.7 - Why python encode a string when .append() in a list?
32,007,092
6
2015-08-14T09:45:27Z
32,007,326
11
2015-08-14T09:56:57Z
[ "python", "string", "list", "append" ]
My problem String ``` # -*- coding: utf-8 -*- print ("################################") foo = "СТ142Н.0000" print (type(foo)) print("foo: "+foo) foo_l = [] foo_l.append(foo) print ("List: " ) print (foo_l) print ("List decode: ") print([x.decode("UTF-8") for x in foo_l]) print("Pop: "+foo_l.pop()) ``` Print resul...
Because even though they look like normal `C` / `T` / `H` characters they are actually not those characters. They are *Cyrillic* characters. > С - [Cyrillic Capital letter ES](http://www.fileformat.info/info/unicode/char/0421/index.htm) > Т - [Cyrillic Capital letter TE](http://www.fileformat.info/info/unicode/c...
How to efficiently join a list with commas and add "and" before the last element
32,008,737
3
2015-08-14T11:15:11Z
32,008,908
9
2015-08-14T11:24:30Z
[ "python", "list" ]
I've been going through [Automatetheboringstuff](http://automatetheboringstuff.com/) and came across a challenge called Comma Code (end of [chapter 4](https://automatetheboringstuff.com/chapter4/)). You have to write a function that takes a list and print out a string, joining the elements with a comma and adding "and"...
You'll have to account for the case where you have just the *one* element: ``` def comma_separator(sequence): if not sequence: return '' if len(sequence) == 1: return sequence[0] return '{} and {}'.format(', '.join(sequence[:-1]), sequence[-1]) ``` Note that `bool(sequence) is True` is a v...
Is sympy pretty printing broken in new jupyter notebook?
32,010,945
7
2015-08-14T13:11:51Z
32,051,577
11
2015-08-17T13:22:49Z
[ "python", "sympy", "jupyter" ]
I have previously used pretty printing of math in the ipython notebook. After upgrading to jupyter (also upgrades many other ipython-related packages), pretty printing no longer works like before. I use this code in the top of my notebooks to set it up: ``` import sympy as sp sp.init_printing() ``` I have also tried ...
I also encountered this issue, the fix is to upgrade your `sympy` version. I found that 0.7.6 reproduces the error, but 0.7.7 has it fixed. At the moment this isn't available via `pip`, but can be found via the [github repo](https://github.com/sympy/sympy).
Convert categorical data in pandas dataframe
32,011,359
7
2015-08-14T13:31:50Z
32,011,969
22
2015-08-14T14:01:35Z
[ "python", "pandas" ]
I have a dataframe with this type of data (too many columns): ``` col1 int64 col2 int64 col3 category col4 category col5 category ``` Columns seems like this: ``` Name: col3, dtype: category Categories (8, object): [B, C, E, G, H, N, S, W] ``` I want to convert all value in column...
First, to convert a Categorical column to its numerical codes, you can do this easier with: `dataframe['c'].cat.codes`. Further, it is possible to select automatically all columns with a certain dtype in a dataframe using `select_dtypes`. This way, you can apply above operation on multiple and automatically selected ...
Pandas: resample timeseries with groupby
32,012,012
5
2015-08-14T14:04:02Z
32,012,129
8
2015-08-14T14:10:21Z
[ "python", "pandas", "group-by", "time-series" ]
Given the below pandas DataFrame: ``` In [115]: times = pd.to_datetime(pd.Series(['2014-08-25 21:00:00','2014-08-25 21:04:00', '2014-08-25 22:07:00','2014-08-25 22:09:00'])) locations = ['HK', 'LDN', 'LDN', 'LDN'] event = ['foo', 'bar', 'baz', 'qux'] ...
You could use a [`pd.TimeGrouper`](http://pandas.pydata.org/pandas-docs/stable/cookbook.html#resampling) to group the DatetimeIndex'ed DataFrame by hour: ``` grouper = df.groupby([pd.TimeGrouper('1H'), 'Location']) ``` use `count` to count the number of events in each group: ``` grouper['Event'].count() # ...
PEP 3130: Difference between switch case and if statement code blocks
32,013,751
8
2015-08-14T15:37:30Z
32,014,023
10
2015-08-14T15:51:04Z
[ "python" ]
In [PEP 3103](https://www.python.org/dev/peps/pep-3103), Guido is discussing adding a switch/case statement to Python with the various schools of thought, methods and objects. In that he makes [this statement](https://www.python.org/dev/peps/pep-3103/#option-2): > Another objection is that the first-use rule allows ob...
You need to read the description at the beginning of that section. "The oldest proposal to deal with this is to freeze the dispatch dict the first time the switch is executed." That implies that the value of `y` will be cached when the switch statement first runs, such that if you first call it as: ``` foo(10,10) ``` ...
Should I always close stdout explicitly?
32,014,310
2
2015-08-14T16:07:47Z
32,014,383
8
2015-08-14T16:12:38Z
[ "python", "c++", "windows", "pipe", "subprocess" ]
I am trying to integrate a small Win32 C++ program which reads from stdin and writes the decoded result (˜128 kbytes)to the output stream. I read entire input into buffer with ``` while (std::cin.get(c)) { } ``` After I write entire output to the stdout. Everything works fine when I run the application from comman...
**Don't close stdout** In the general case, it is actually wrong, since it is possible to register a function with [`atexit()`](http://www.cplusplus.com/reference/cstdlib/atexit/) which tries to write to stdout, and this will break if stdout is closed. When the process terminates, all handles are closed by the operat...
Django tutorial, Getting: TypeError at /admin/ argument to reversed() must be a sequence
32,015,044
4
2015-08-14T16:49:26Z
32,015,269
12
2015-08-14T17:04:51Z
[ "python", "django-1.8" ]
I'm working my way through the django tutorial for version 1.8 and I am getting an error that I am stuck on and can't seem to figure out. I thought I was following the tutorial pretty much to the T. I have the following tree set up: `. ├── dj_project │   ├── __init__.py │   ├── __init__.pyc ...
In the **polls/urls.py** file, you are declaring the urlpatterns as dict, it must be a list. change the ``` urlpatterns = { url(r'^$', views.index, name='index'), } ``` to: ``` urlpatterns = [ url(r'^$', views.index, name='index'), ] ```
convert strings into python dict
32,017,755
4
2015-08-14T19:56:24Z
32,017,839
8
2015-08-14T20:01:45Z
[ "python", "dictionary" ]
I have a string which is as follows ``` my_string = '"sender" : "md-dgenie", "text" : "your dudegenie code is 6326. welcome to the world of dudegenie! your wish, my command!", "time" : "1439155575925", "name" : "John"' ``` I want to construct a dict from the above string. I tried something as suggested [here](http://...
Your string is *almost* already a python dict, so you could just enclose it in braces and then [evaluate it](https://docs.python.org/2/library/ast.html#ast.literal_eval) as such: ``` import ast my_dict = ast.literal_eval('{{{0}}}'.format(my_string)) ```
Matplotlib Crashing tkinter Application
32,019,556
2
2015-08-14T22:32:20Z
34,109,240
8
2015-12-05T18:26:16Z
[ "python", "user-interface", "matplotlib", "tkinter", "ttk" ]
I am building an application that embeds a matplotlib figure into the GUI. The problem is that my app is crashing as soon as I add anything from matplotlib into my code (except for the imports, those work as usual). The problem occurs in my class `Solver_App` at `tk.Tk.__init__(self, *args, **kwargs)`. When I run the c...
You need to set the TkAgg backend explicitly. I could reproduce your bug. With the following code, the problem is resolved. ``` import matplotlib matplotlib.use("TkAgg") from matplotlib import pyplot as plt ``` Note that setting the TkAgg backend *after* importing pyplot does not work either; it crashes too. You need...
sudo: pip: command not found in CentOS
32,020,594
6
2015-08-15T01:19:37Z
32,020,625
16
2015-08-15T01:27:31Z
[ "python", "centos", "pip" ]
I use CentOS and I installed pip to `/usr/local/python-dir/bin/pip`. I made a link to `/usr/local/bin/pip`. Then I executed `sudo pip install xxx`, it reported an error like this: ``` sudo: pip: command not found ``` I see `$PATH` is all right: ``` /usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin ``` However,...
For security reasons, `sudo` does not rely on the `$PATH` set in your environment. There is a `secure_path` option in `/etc/sudoers` that specifies the `PATH` that `sudo` will use for locating binaries. For example: ``` Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin ``` Just add `/usr/local/bin` to this PATH...
Reference template variable within Jinja expression
32,024,551
2
2015-08-15T12:07:16Z
32,024,636
7
2015-08-15T12:17:57Z
[ "python", "flask", "jinja2" ]
I have a route defined like this: ``` @app.route('/magic/<filename>') def moremagic(filename): pass ``` And now in a template I want to call that route using `url_for()` like so: ``` <h1>you uploaded {{ name }}<h1> <a href="{{ url_for('/magic/<filename>') }}">Click to see magic happen</a> ``` I have tried: ```...
Everything inside the `{{ ... }}` is a Python-like expression. You don't need to use another `{{ ... }}` inside that to reference variables. Drop the extra brackets: ``` <h1>you uploaded {{ name }}<h1> <a href="{{ url_for('/magic', filename=name) }}">Click to see magic happen</a> ```
subtracting the mean of each row in numpy with broadcasting
32,030,343
5
2015-08-15T23:23:22Z
32,030,456
9
2015-08-15T23:40:17Z
[ "python", "numpy" ]
I try to subtract the mean of each row of a matrix in numpy using broadcasting but I get an error. Any idea why? Here is the code: ``` from numpy import * X = random.rand(5, 10) Y = X - X.mean(axis = 1) ``` Error: ``` ValueError: operands could not be broadcast together with shapes (5,10) (5,) ``` Thanks!
The `mean` method is a *reduction* operation, meaning it converts a 1-d collection of numbers to a single number. When you apply a reduction to an n-dimensional array along an axis, numpy collapses that dimension to the reduced value, resulting in an (n-1)-dimensional array. In your case, since `X` has shape (5, 10), a...
Replace single quotes with double with exclusion of some elements
32,031,353
11
2015-08-16T02:47:08Z
32,529,140
8
2015-09-11T17:35:31Z
[ "python", "regex", "replace", "nlp" ]
I want to replace all single quotes in the string with double with the exception of occurrences such as "n't", "'ll", "'m" etc. ``` input="the stackoverflow don\'t said, \'hey what\'" output="the stackoverflow don\'t said, \"hey what\"" ``` Code 1:(@<https://stackoverflow.com/users/918959/antti-haapala>) ``` def con...
## First attempt You can also use this regex: ``` (?:(?<!\w)'((?:.|\n)+?'?)'(?!\w)) ``` [DEMO IN REGEX101](https://regex101.com/r/rG6gN0/3) This regex match whole sentence/word with both quoting marks, from beginning and end, but also campure the content of quotation inside group nr 1, so you can replace matched pa...
Select everything but a list of columns from pandas dataframe
32,032,836
7
2015-08-16T07:29:28Z
32,032,989
8
2015-08-16T07:53:45Z
[ "python", "pandas" ]
Is it possible to select the negation of a given list from pandas dataframe?. For instance, say I have the following dataframe ``` T1_V2 T1_V3 T1_V4 T1_V5 T1_V6 T1_V7 T1_V8 1 15 3 2 N B N 4 16 14 5 H B N 1 10 10 5 N K N `...
If your column names are strings you can do it like this: ``` df[df.columns - ["T1_V6"]] ``` --- However, the "set minus" doesn't work for numeric column names so this is probably the preferred way to do it (works also with numeric column names): ``` df[df.columns.difference(["T1_V6"])] ```
Why is pandas.to_datetime slow for non standard time format such as '2014/12/31'
32,034,689
6
2015-08-16T11:42:40Z
32,034,914
8
2015-08-16T12:09:54Z
[ "python", "csv", "pandas", "python-datetime", "string-to-datetime" ]
I have a .csv file in such format ``` timestmp, p 2014/12/31 00:31:01:9200, 0.7 2014/12/31 00:31:12:1700, 1.9 ... ``` and when read via `pd.read_csv` and convert the time str to datetime using `pd.to_datetime`, the performance drops dramatically. Here is a minimal example. ``` import re import pandas as pd d = '201...
This is because pandas falls back to `dateutil.parser.parse` for parsing the strings when it has a non-default format or when no `format` string is supplied (this is much more flexible, but also slower). As you have shown above, you can improve the performance by supplying a `format` string to `to_datetime`. Or anothe...
Python order a dict by key value
32,036,125
3
2015-08-16T14:23:15Z
32,036,142
7
2015-08-16T14:25:16Z
[ "python", "sorting", "dictionary" ]
I've been trying to order my dict that has keys with this format: `"0:0:0:0:0:x"` where x is the variable that get incremented while filling the dict. Since dictionaries doesn't insert in order, and I need the key-value values to be showed ordered, I tried to use ``` collections.OrderedDict(sorted(observation_values....
You are sorting strings, so they are sorted lexicographically, not numerically. Give `sorted()` a custom sort key: ``` sortkey = lambda i: [int(e) for e in i[0].split(':')] collections.OrderedDict(sorted(observation_values.items(), key=sortkey)) ``` This takes the key of each key-value pair (`i[0]`), splitting it on...
How can i remove extra "s" from django admin panel?
32,047,686
3
2015-08-17T10:07:10Z
32,047,877
7
2015-08-17T10:16:58Z
[ "python", "django", "django-models" ]
I am really very much irritated by the extra "s" added after my class name in django admin eg class 'About' in my model.py becomes 'Abouts' in admin section. And i want it not to add extra 's'. Here is my model.py file- ``` class About(models.Model): about_desc = models.TextField(max_length=5000) def ...
You can add another class called `Meta` in your model to specify plural display name. For example, if the model's name is `Category`, the admin displays `Categorys`, but by adding the `Meta` class, we can change it to `Categories`. I have changed your code to fix the issue: ``` class About(models.Model): about_d...
Python float and int behavior
32,052,573
3
2015-08-17T14:09:31Z
32,052,647
10
2015-08-17T14:12:55Z
[ "python", "floating-point-conversion" ]
when i try to check whether float variable contain exact integer value i get the folowing strange behaviour. My code : ``` x = 1.7 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) print "----------------------" x = **2.7** print x, (x =...
the problem is not with conversion but with **addition**. ``` int(3.0) == 3.0 ``` returns **True** as expected. The probelm is that floating points are not infinitely accurate, and you cannot expect 2.7 + 0.1 \* 3 to be 3.0 ``` >>> 2.7 + 0.1 + 0.1 + 0.1 3.0000000000000004 >>> 2.7 + 0.1 + 0.1 + 0.1 == 3.0 False ```...
Python - how to run multiple coroutines concurrently using asyncio?
32,054,066
9
2015-08-17T15:21:54Z
32,056,300
13
2015-08-17T17:25:31Z
[ "python", "python-3.x", "websocket", "python-asyncio" ]
I'm using the [`websockets`](https://github.com/aaugustin/websockets) library to create a websocket server in Python 3.4. Here's a simple echo server: ``` import asyncio import websockets @asyncio.coroutine def connection_handler(websocket, path): while True: msg = yield from websocket.recv() if m...
**TL;DR** Use [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future) to run several coroutines concurrently. --- > Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? Tornado? No, you don't need any other framework fo...
Scrapy with TOR (Windows)
32,054,558
5
2015-08-17T15:47:49Z
32,188,821
8
2015-08-24T18:05:41Z
[ "python", "windows", "scrapy", "tor" ]
I created a Scrapy project with several spiders to crawl some websites. Now I want to use TOR to: 1. Hide my ip from the crawled servers; 2. Associate my requests to different ips, simulating accesses from different users. I have read some info about this, for example: [using tor with scrapy framework](http://stackov...
After a lot of research, I found a way to setup my Scrapy project to work with TOR on Windows OS: 1. Download TOR Expert Bundle for Windows (1) and unzip the files to a folder (ex. \tor-win32-0.2.6.10). 2. The recent TOR's versions for Windows don't come with a graphical user interface (2). It is probably possible to ...
HTTPSHandler error while installing pip with python 2.7.9
32,054,580
8
2015-08-17T15:48:42Z
32,068,819
11
2015-08-18T09:39:59Z
[ "python", "installation", "openssl", "pip", "virtualenv" ]
Hi I am trying to install pip with python 2.7.9 but keep getting following error. I want to create python virtual env. ``` python get-pip.py Traceback (most recent call last): File "get-pip.py", line 17767, in <module> main() File "get-pip.py", line 162, in main bo...
Make sure you have openssl and openssl-devel installed before you build Python 2.7 ``` yum install openssl openssl-devel ``` or ``` apt-get install openssl openssl-devel ``` or (for Debian): ``` apt-get install libssl-dev ``` To rebuild Python ``` cd ~ wget https://www.python.org/ftp/python/2.7.9/Python-2.7.9.t...
Exiting Python Debugger ipdb
32,055,062
13
2015-08-17T16:13:11Z
32,096,090
16
2015-08-19T12:53:42Z
[ "python", "debugging", "workflow", "exit", "ipdb" ]
I use ipdb fairly often in a way to just jump to a piece of code that is *isolated* i.e. it is hard to write a real script that uses it. Instead I write a minimal test case with mocking and jump into it. Exemplary for the workflow: ``` def func(): ... import ipdb ipdb.set_trace() ... def test_case(): ...
I put the following in my `.pdbrc` ``` import os alias kk os.system('kill -9 %d' % os.getpid()) ``` `kk` kills the debugger and (the process that trigger the debugger).
Python3 AttributeError: 'list' object has no attribute 'clear'
32,055,768
4
2015-08-17T16:52:22Z
32,055,799
9
2015-08-17T16:54:45Z
[ "python", "list", "python-3.x", "attributeerror", "python-3.2" ]
I am working on a Linux machine with Python version 3.2.3. Whenever I try to do `list.clear()` I get an exception ``` >>> l = [1, 2, 3, 4, 5, 6, 7] >>> l.clear() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'clear' ``` At the same time on my M...
`list.clear` was added in Python 3.3. See the [4.6.3. Mutable Sequence Types](https://docs.python.org/3/library/stdtypes.html?highlight=clear#mutable-sequence-types): > *New in version 3.3*: *clear()* and *copy()* methods. > > ... > > *s.clear()* removes all items from *s* (same as *del s[:]*) From the [issue 10516]...
Python: Is there any difference between "del a" and "del(a)"?
32,060,273
9
2015-08-17T21:50:14Z
32,060,347
10
2015-08-17T21:55:37Z
[ "python" ]
As far as I can tell, both `del a` and `del(a)` seems to work with the same effect. If that's the case, why would Python allow `del` to exist both as a statement and a function?
`del` is always a statement. Using parenthesis doesn't mean you're making a function call, but you're grouping expressions. `(1)` is just the same as `1`.
Probability function to generate values instead of calling random
32,065,067
3
2015-08-18T06:29:08Z
32,065,189
9
2015-08-18T06:35:56Z
[ "python", "statistics" ]
In my python code there are a few places where I have a population where there is `x` chance of something happening to each individual, but I just need the amount of people affected. ``` amount = 0 population = 500 chance = 0.05 for p in range(population): if random.random() < chance: amount += 1 ``` My ...
The distribution of the sum of *n* 0-1 random variables, each with probability *p* is called a [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution) with parameters *n* and *p*. I believe [`numpy.random.binomial`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html) wi...
Python Matplotlib - Impose shape dimensions with Imsave
32,069,041
6
2015-08-18T09:49:42Z
32,127,060
9
2015-08-20T19:47:31Z
[ "python", "matplotlib", "shape" ]
I plot a great number of pictures with matplotlib in order to make video with it but when i try to make the video i saw the shape of the pictures is not the same in time...It induces some errors. Is there a command to impose the shape of the output when i use Imsave? You can see a part of my code : ``` plt.close() fi...
If you're saving figures out to images on disk, you can do something like this to set the size: ``` fig.set_size_inches(10, 15) fig.savefig('image.png', dpi=100) ``` If you just want to display at a certain size you can try: ``` plt.figure(figsize=(1,1)) ``` Where the dimensions are set in inches. Here is an expla...
How do i check if input is a date
32,071,978
2
2015-08-18T12:06:20Z
32,072,044
7
2015-08-18T12:09:34Z
[ "python", "function" ]
I want to define a function that will check if input is a date. If input is not a date i want it to say: sorry try again and if it is a date i need a program to stop. I tried many things but none of them worked and I don't have codes of what I tried because I deleted the function.
Use `datetime` library: ``` import datetime def validate(date_text): try: datetime.datetime.strptime(date_text, '%Y-%m-%d') except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") ``` than validate like that: ``` validate('2015-08-18') ```
Python 3 In Memory Zipfile Error. string argument expected, got 'bytes'
32,075,135
6
2015-08-18T14:23:34Z
32,075,279
11
2015-08-18T14:29:24Z
[ "python", "python-3.x" ]
I have the following code to create an in memory zip file that throws an error running in Python 3. ``` from io import StringIO from pprint import pprint import zipfile in_memory_data = StringIO() in_memory_zip = zipfile.ZipFile( in_memory_data, "w", zipfile.ZIP_DEFLATED, False) in_memory_zip.debug = 3 filename...
`ZipFile` writes its data as bytes, not strings. This means you'll have to use `BytesIO` instead of `StringIO` on Python 3. The distinction between bytes and strings is new in Python 3. The [six](https://pythonhosted.org/six/) compatibility library has a `BytesIO` class for Python 2 if you want your program to be comp...
Flask-Session extension vs default session
32,084,646
7
2015-08-19T00:26:46Z
32,085,122
9
2015-08-19T01:29:51Z
[ "python", "flask" ]
I'm using: ``` from flask import session @app.route('/') def main_page(): if session.get('key'): print ("session exist" + session.get('key')) else: print ("could not find session") session['key'] = '34544646###########' return render_template('index.html') ``` I don't have the Fla...
The difference is in where the session data is stored. Flask's sessions are *client-side* sessions. Any data that you write to the session is written to a cookie and sent to the client to store. The client will send the cookie back to the server with every request, that is how the data that you write in the session re...
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,085,730
40
2015-08-19T02:46:22Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
If you know you're only dealing with positive numbers, this will work, and is pretty clean: ``` a, b, c = sorted((a, b, c)) if a + b == c: do_stuff() ``` As I said, this only works for positive numbers; but if you *know* they're going to be positive, this is a very readable solution IMO, even directly in the code...
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,085,900
17
2015-08-19T03:07:59Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
If you will only be using three variables then your initial method: ``` a + b == c or a + c == b or b + c == a ``` Is already very pythonic. If you plan on using more variables then your method of reasoning with: ``` a + b + c in (2*a, 2*b, 2*c) ``` Is very smart but lets think about why. Why does this work? W...
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,086,517
54
2015-08-19T04:20:34Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
Python has an `any` function that does an `or` on all the elements of a sequence. Here I've converted your statement into a 3-element tuple. ``` any((a + b == c, a + c == b, b + c == a)) ``` Note that `or` is short circuiting, so if calculating the individual conditions is expensive it might be better to keep your or...
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,097,819
103
2015-08-19T14:06:14Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
Solving the three equalities for a: ``` a in (b+c, b-c, c-b) ```
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,101,507
197
2015-08-19T17:01:07Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
If we look at the Zen of Python, emphasis mine: > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. > Explicit is better than implicit. > **Simple is better than complex.** > Complex is better than complicated. > Flat is better than nested. > Sparse is better than dense. > **Readability c...
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,102,240
12
2015-08-19T17:46:22Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
The following code can be used to iteratively compare each element with the sum of the others, which is computed from sum of the whole list, excluding that element. ``` l = [a,b,c] any(sum(l)-e == e for e in l) ```
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,130,760
9
2015-08-21T00:55:34Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
Python 3: ``` (a+b+c)/2 in (a,b,c) (a+b+c+d)/2 in (a,b,c,d) ... ``` It scales to any number of variables: ``` arr = [a,b,c,d,...] sum(arr)/2 in arr ``` However, in general I agree that unless you have more than three variables, the original version is more readable.
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,134,734
8
2015-08-21T07:31:22Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
Don't try and simplify it. Instead, *name* what you're doing with a function: ``` def any_two_sum_to_third(a, b, c): return a + b == c or a + c == b or b + c == a if any_two_sum_to_third(foo, bar, baz): ... ``` Replace the condition with something "clever" might make it shorter, but it won't make it more readabl...
Can't install virtualenvwrapper on OSX 10.11 El Capitan
32,086,631
31
2015-08-19T04:33:56Z
32,095,725
43
2015-08-19T12:37:04Z
[ "python", "osx", "virtualenv", "virtualenvwrapper", "osx-elcapitan" ]
I recently wiped my Mac and reinstalled OSX El Capitan public beta 3. I installed pip with `sudo easy_install pip` and installed virtualenv with `sudo pip install virtualenv` and did not have any problems. Now, when I try to `sudo pip install virtualenvwrapper`, I get the following: ``` Users-Air:~ User$ sudo pip ins...
You can manually install the dependencies that don't exist on a stock 10.11 install, then install the other packages with `--no-deps` to ignore the dependencies. That way it will skip `six` (and `argparse` which is also already installed). This works on my 10.11 beta 6 install: ``` sudo pip install pbr sudo pip instal...
Can't install virtualenvwrapper on OSX 10.11 El Capitan
32,086,631
31
2015-08-19T04:33:56Z
33,425,578
29
2015-10-29T22:15:59Z
[ "python", "osx", "virtualenv", "virtualenvwrapper", "osx-elcapitan" ]
I recently wiped my Mac and reinstalled OSX El Capitan public beta 3. I installed pip with `sudo easy_install pip` and installed virtualenv with `sudo pip install virtualenv` and did not have any problems. Now, when I try to `sudo pip install virtualenvwrapper`, I get the following: ``` Users-Air:~ User$ sudo pip ins...
sudo pip install virtualenvwrapper --ignore-installed six Also works
Pandas Dataframe to RDD
32,090,714
5
2015-08-19T08:50:04Z
32,093,313
7
2015-08-19T10:45:56Z
[ "python", "apache-spark", "dataframe", "pyspark", "spark-dataframe" ]
Can I convert a Pandas Dataframe to RDD? ``` if isinstance(data2, pd.DataFrame): print 'is Dataframe' else: print 'is NOT Dataframe' ``` is Dataframe Here is the output when trying to use .rdd ``` dataRDD = data2.rdd print dataRDD AttributeError Traceback (most recent call last) ...
> Can I convert a Pandas Dataframe to RDD? Well, yes you can do it. Pandas Data Frames ``` pdDF = pd.DataFrame([("foo", 1), ("bar", 2)], columns=("k", "v")) print pdDF ## k v ## 0 foo 1 ## 1 bar 2 ``` can be converted to Spark Data Frames ``` pDF = sqlContext.createDataFrame(pdDF) spDF.show() ## +---+-+ #...
morse code to english python3
32,094,525
3
2015-08-19T11:41:45Z
32,094,652
10
2015-08-19T11:48:05Z
[ "python", "dictionary" ]
i want to convert Morse Code to English using Python 3+ I have managed to convert english to morse code using this <http://code.activestate.com/recipes/578407-simple-morse-code-translator-in-python/> But i want to convert Morse Code to English I have attempted to do it one charecter at a time, but the problem is that...
Once you define the mapping in one direction, you can use a dict comprehension to map it the other way ``` CODE = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', '...
Python Gaussian Kernel density calculate score for new values
32,101,817
12
2015-08-19T17:18:55Z
32,146,454
9
2015-08-21T17:48:57Z
[ "python", "gaussian", "kde", "kernel-density" ]
this is my code: ``` import numpy as np from scipy.stats.kde import gaussian_kde from scipy.stats import norm from numpy import linspace,hstack from pylab import plot,show,hist import re import json attribute_file="path" attribute_values = [line.rstrip('\n') for line in open(attribute_file)] obs=[] #Assume the li...
The reason for that is that you have many more 1's in your observations than 768's. So even if -1 is not exactly 1, it gets a high predicted value, because the histogram has a much larger larger value at 1 than at 768. Up to a multiplicative constant, the formula for prediction is: [![enter image description here](ht...
Google App Engine app deployment
32,107,712
9
2015-08-20T00:25:02Z
34,694,577
14
2016-01-09T14:21:36Z
[ "python", "google-app-engine", "web-applications" ]
I'm trying to deploy a basic HelloWorld app on Google Engine following their tutorial for Python. I created a **helloworld.py** file and an **app.yaml** file and copied the code from their online tutorial. I signed up for Google App Engine and have tried everything but keep getting the following error: ``` 2015-08-19 ...
In my case, I got refused because the appcfg save my ouauth2 token in the file `~/.appcfg_oauth2_tokens`, which happen to be another account of appengine . Simply remove the file and try again. It should work. This is in Mac, I am not sure about windows though.
Set vs. set python
32,108,235
3
2015-08-20T01:40:45Z
32,108,276
8
2015-08-20T01:45:41Z
[ "python", "python-3.x" ]
What's the difference between `set("a")` and `sets.Set("a")`? Their types are different, but they seem to do the same thing. I can't find any resources online about it, but I've seen both used in examples.
You've tagged this Python 3, so the difference is that `sets` doesn't exist. Use `set`. In Python 2, the difference is that `sets` is deprecated. It's the old, slow, not-as-good version. Use `set`. This is explained in the [documentation for the `sets` module](https://docs.python.org/2/library/sets.html), which comes ...
Equivalent of matlab "ans" and running shell commands
32,108,471
2
2015-08-20T02:07:07Z
32,108,552
7
2015-08-20T02:18:25Z
[ "python", "matlab", "shell" ]
These days, I'm transitiong from Matlab to Python after using Matlab/Octave for more than ten years. I have two quick questions: 1. In the Python interactive mode, is there anything corresponding to Matlab's `ans`? 2. How can I run shell commands in the Python interactive mode? Of course, I can use `os.system()`, but ...
Python interactive mode is Python. You will need to use `os.system` or an equivalent. Alternately, you can suspend Python with Ctrl-Z, and get back into it with `fg`. (Assuming UNIX-like environment.) The last evaluated expression is saved in the variable `_`: ``` >>> 1 + 2 3 >>> _ * 4 12 ```
Converting a `pandas.tslib.Timestamp` object to `datetime`
32,108,564
4
2015-08-20T02:19:55Z
32,113,406
10
2015-08-20T08:36:31Z
[ "python", "pandas" ]
I am trying to convert a `pandas.tslib.Timestamp` object to `datetime`.`df['orig_iss_dt']` is the `pandas.tslib.Timestamp` object. I used the answer [here](http://stackoverflow.com/questions/25852044/converting-pandas-tslib-timestamp-to-datetime-python) to try and do this, but find that `print(type(origination))` still...
The easiest way to convert a pandas `Timestamp` to `datetime.datetime` is to use the `to_pydatetime` method. This can be called on `Timestamp` directly or on the series: ``` In [15]: s = pd.Series(pd.date_range('2012-01-01', periods=3)) In [16]: s Out[16]: 0 2012-01-01 1 2012-01-02 2 2012-01-03 dtype: datetime6...
How to implement the ReLU function in Numpy
32,109,319
7
2015-08-20T03:58:56Z
32,109,519
13
2015-08-20T04:22:14Z
[ "python", "numpy", "machine-learning", "neural-network" ]
I want to make simple neural network and I wish to use the ReLU function. Can someone give me a clue of how can I implement the function using numpy. Thanks for your time!
There are a couple of ways. ``` >>> x = np.random.random((3, 2)) - 0.5 >>> x array([[-0.00590765, 0.18932873], [-0.32396051, 0.25586596], [ 0.22358098, 0.02217555]]) >>> np.maximum(x, 0) array([[ 0. , 0.18932873], [ 0. , 0.25586596], [ 0.22358098, 0.02217555]]) >>> x * (...
What is the difference between u' ' prefix and unicode() in python?
32,111,835
6
2015-08-20T07:17:52Z
32,111,908
11
2015-08-20T07:21:19Z
[ "python", "unicode", "utf-8" ]
What is the difference between `u''` prefix and `unicode()`? ``` # -*- coding: utf-8 -*- print u'上午' # this works print unicode('上午', errors='ignore') # this works but print out nothing print unicode('上午') # error ``` For the third `print`, the error shows: UnicodeDecodeError: 'ascii' codec can't decode ...
* `u'..'` is a string literal, and decodes the characters according to the source encoding declaration. * `unicode()` is a function that converts another type to a `unicode` object, you've given it a *byte string literal*. It'll decode a byte string according to the default ASCII codec. So you created a byte string ob...
Why should not use list.sort in python
32,111,959
6
2015-08-20T07:24:07Z
32,111,976
8
2015-08-20T07:24:48Z
[ "python", "sorting" ]
While I was going through [Google Python Class Day 1 Part 2](https://www.youtube.com/watch?v=EPYupizJYQI) at 14:20 - 14:30 Guy says *"do not use `list.sort`"*. Also he mentioned that *"Dinosaurs use that!"* (i.e. it's an old way of doing sorting). But he did not mention the reason. Can anyone tell me why we should not...
Because `list.sort()` will do an in-place sorting. So this changes the original list. But `sorted(list)` would create a new list instead of modifying the original. Example: ``` >>> s = [1,2,37,4] >>> s.sort() >>> s [1, 2, 4, 37] >>> s = [1,2,37,4,45] >>> sorted(s) [1, 2, 4, 37, 45] >>> s [1, 2, 37, 4, 45] ```
Why is math.floor(x/y) != x // y for two evenly divisible floats in Python?
32,123,583
23
2015-08-20T16:29:42Z
32,126,311
24
2015-08-20T19:03:36Z
[ "python", "division", "integer-division" ]
I have been reading about division and integer division in Python and the differences between division in Python2 vs Python3. For the most part it all makes sense. Python 2 uses integer division only when both values are integers. Python 3 always performs true division. Python 2.2+ introduced the `//` operator for inte...
I didn't find the other answers satisfying. Sure, `.1` has no finite binary expansion, so our hunch is that representation error is the culprit. But that hunch alone doesn't really explain why `math.floor(.5/.1)` yields `5.0` while `.5 // .1` yields `4.0`. The punchline is that `a // b` is **actually** doing `floor((a...
Python Assignment Operator Precedence - (a, b) = a[b] = {}, 5
32,127,908
21
2015-08-20T20:36:02Z
32,127,960
15
2015-08-20T20:39:49Z
[ "python", "variable-assignment" ]
I saw this Python snippet on [Twitter](https://twitter.com/fijall/status/634260102795685890) and was quite confused by the output: ``` >>> a, b = a[b] = {}, 5 >>> a {5: ({...}, 5)} ``` What is going on here?
From the [*Assignment statements* documentation](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements): > An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting ...
yield in list comprehensions and generator expressions
32,139,885
23
2015-08-21T12:05:06Z
32,139,977
22
2015-08-21T12:08:38Z
[ "python", "generator", "list-comprehension", "yield", "generator-expression" ]
The following behaviour seems rather counterintuitive to me (Python 3.4): ``` >>> [(yield i) for i in range(3)] <generator object <listcomp> at 0x0245C148> >>> list([(yield i) for i in range(3)]) [0, 1, 2] >>> list((yield i) for i in range(3)) [0, None, 1, None, 2, None] ``` The intermediate values of the last line a...
Generator expressions, and set and dict comprehensions are compiled to (generator) function objects. In Python 3, list comprehensions get the same treatment; they are all, in essence, a new nested scope. You can see this if you try to disassemble a generator expression: ``` >>> dis.dis(compile("(i for i in range(3))"...
Python rock, paper, scissors game. not always give correct answers
32,140,140
2
2015-08-21T12:17:08Z
32,140,225
10
2015-08-21T12:21:19Z
[ "python", "python-3.x" ]
I'm trying to make a simple ***Rock, Paper, Scissors*** game in **python 3.4** and it works to a certain degree but some time i get an output of "You Won Rock crushes Rock" even though i thought i have stop this from happening and only allowed certain outcomes of the code with my elif and if statements. So can anyone t...
``` elif user == 'rock' and computer() == 'scissors': print("\nYou Won! {} crushes {}".format(user.title(), computer().title())) ``` Every time you call `computer()`, it generates a completely new value, independent of any previous calls. For example, in the code above it's entirely possible that the first...
Is "norm" equivalent to "Euclidean distance"?
32,141,856
5
2015-08-21T13:41:26Z
32,142,625
7
2015-08-21T14:16:01Z
[ "python", "arrays", "math", "numpy", "euclidean-distance" ]
I am not sure whether "norm" and "Euclidean distance" mean the same thing. Please could you help me with this distinction. I have an `n` by `m` array `a`, where `m` > 3. I want to calculate the Eculidean distance between the second data point `a[1,:]` to all the other points (including itself). So I used the `np.linal...
A [norm](https://en.wikipedia.org/wiki/Norm_(mathematics)) is a function that takes a vector as an input and returns a scalar value that can be interpreted as the "size", "length" or "magnitude" of that vector. More formally, norms are defined as having the following mathematical properties: * They scale multiplicativ...